summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatt A. Tobin <email@mattatobin.com>2018-02-03 06:00:38 -0500
committerMatt A. Tobin <email@mattatobin.com>2018-02-03 06:00:38 -0500
commit8148615da179fdd60f19018e13b4e94b95609cc6 (patch)
tree771fccdd99fa3adf35fdd2c81d8197b415a89b91
parent494802c1be7888025b95260d23db187467d2b9dd (diff)
downloadUXP-8148615da179fdd60f19018e13b4e94b95609cc6.tar
UXP-8148615da179fdd60f19018e13b4e94b95609cc6.tar.gz
UXP-8148615da179fdd60f19018e13b4e94b95609cc6.tar.lz
UXP-8148615da179fdd60f19018e13b4e94b95609cc6.tar.xz
UXP-8148615da179fdd60f19018e13b4e94b95609cc6.zip
Remove browser tests - Part 1: The Tests (except for experiments)
-rw-r--r--browser/base/content/test/alerts/.eslintrc.js7
-rw-r--r--browser/base/content/test/alerts/browser.ini12
-rw-r--r--browser/base/content/test/alerts/browser_notification_close.js71
-rw-r--r--browser/base/content/test/alerts/browser_notification_do_not_disturb.js80
-rw-r--r--browser/base/content/test/alerts/browser_notification_open_settings.js58
-rw-r--r--browser/base/content/test/alerts/browser_notification_permission_migration.js45
-rw-r--r--browser/base/content/test/alerts/browser_notification_remove_permission.js72
-rw-r--r--browser/base/content/test/alerts/browser_notification_replace.js38
-rw-r--r--browser/base/content/test/alerts/browser_notification_tab_switching.js80
-rw-r--r--browser/base/content/test/alerts/file_dom_notifications.html39
-rw-r--r--browser/base/content/test/alerts/head.js71
-rw-r--r--browser/base/content/test/captivePortal/browser.ini9
-rw-r--r--browser/base/content/test/captivePortal/browser_CaptivePortalWatcher.js119
-rw-r--r--browser/base/content/test/captivePortal/browser_CaptivePortalWatcher_1.js91
-rw-r--r--browser/base/content/test/captivePortal/browser_captivePortal_certErrorUI.js82
-rw-r--r--browser/base/content/test/captivePortal/head.js181
-rw-r--r--browser/base/content/test/chrome/.eslintrc.js7
-rw-r--r--browser/base/content/test/chrome/chrome.ini3
-rw-r--r--browser/base/content/test/chrome/test_aboutCrashed.xul86
-rw-r--r--browser/base/content/test/general/.eslintrc.js8
-rw-r--r--browser/base/content/test/general/POSTSearchEngine.xml6
-rw-r--r--browser/base/content/test/general/aboutHome_content_script.js6
-rw-r--r--browser/base/content/test/general/accounts_testRemoteCommands.html83
-rw-r--r--browser/base/content/test/general/alltabslistener.html8
-rw-r--r--browser/base/content/test/general/app_bug575561.html18
-rw-r--r--browser/base/content/test/general/app_subframe_bug575561.html12
-rw-r--r--browser/base/content/test/general/audio.oggbin14293 -> 0 bytes
-rw-r--r--browser/base/content/test/general/benignPage.html12
-rw-r--r--browser/base/content/test/general/browser.ini494
-rw-r--r--browser/base/content/test/general/browser_PageMetaData_pushstate.js29
-rw-r--r--browser/base/content/test/general/browser_aboutAccounts.js499
-rw-r--r--browser/base/content/test/general/browser_aboutCertError.js409
-rw-r--r--browser/base/content/test/general/browser_aboutHealthReport.js139
-rw-r--r--browser/base/content/test/general/browser_aboutHome.js668
-rw-r--r--browser/base/content/test/general/browser_aboutHome_wrapsCorrectly.js28
-rw-r--r--browser/base/content/test/general/browser_aboutNetError.js47
-rw-r--r--browser/base/content/test/general/browser_aboutSupport_newtab_security_state.js26
-rw-r--r--browser/base/content/test/general/browser_accesskeys.js82
-rw-r--r--browser/base/content/test/general/browser_addCertException.js50
-rw-r--r--browser/base/content/test/general/browser_addKeywordSearch.js81
-rw-r--r--browser/base/content/test/general/browser_alltabslistener.js206
-rw-r--r--browser/base/content/test/general/browser_audioTabIcon.js504
-rw-r--r--browser/base/content/test/general/browser_backButtonFitts.js42
-rw-r--r--browser/base/content/test/general/browser_beforeunload_duplicate_dialogs.js76
-rw-r--r--browser/base/content/test/general/browser_blob-channelname.js11
-rw-r--r--browser/base/content/test/general/browser_blockHPKP.js101
-rw-r--r--browser/base/content/test/general/browser_bookmark_popup.js431
-rw-r--r--browser/base/content/test/general/browser_bookmark_titles.js98
-rw-r--r--browser/base/content/test/general/browser_bug1015721.js54
-rw-r--r--browser/base/content/test/general/browser_bug1045809.js68
-rw-r--r--browser/base/content/test/general/browser_bug1064280_changeUrlInPinnedTab.js36
-rw-r--r--browser/base/content/test/general/browser_bug1261299.js73
-rw-r--r--browser/base/content/test/general/browser_bug1297539.js114
-rw-r--r--browser/base/content/test/general/browser_bug1299667.js71
-rw-r--r--browser/base/content/test/general/browser_bug321000.js80
-rw-r--r--browser/base/content/test/general/browser_bug356571.js93
-rw-r--r--browser/base/content/test/general/browser_bug380960.js11
-rw-r--r--browser/base/content/test/general/browser_bug386835.js89
-rw-r--r--browser/base/content/test/general/browser_bug406216.js54
-rw-r--r--browser/base/content/test/general/browser_bug408415.js45
-rw-r--r--browser/base/content/test/general/browser_bug409481.js83
-rw-r--r--browser/base/content/test/general/browser_bug409624.js57
-rw-r--r--browser/base/content/test/general/browser_bug413915.js62
-rw-r--r--browser/base/content/test/general/browser_bug416661.js43
-rw-r--r--browser/base/content/test/general/browser_bug417483.js30
-rw-r--r--browser/base/content/test/general/browser_bug419612.js32
-rw-r--r--browser/base/content/test/general/browser_bug422590.js50
-rw-r--r--browser/base/content/test/general/browser_bug423833.js138
-rw-r--r--browser/base/content/test/general/browser_bug424101.js52
-rw-r--r--browser/base/content/test/general/browser_bug427559.js38
-rw-r--r--browser/base/content/test/general/browser_bug431826.js50
-rw-r--r--browser/base/content/test/general/browser_bug432599.js127
-rw-r--r--browser/base/content/test/general/browser_bug435035.js17
-rw-r--r--browser/base/content/test/general/browser_bug435325.js69
-rw-r--r--browser/base/content/test/general/browser_bug441778.js46
-rw-r--r--browser/base/content/test/general/browser_bug455852.js20
-rw-r--r--browser/base/content/test/general/browser_bug460146.js51
-rw-r--r--browser/base/content/test/general/browser_bug462289.js81
-rw-r--r--browser/base/content/test/general/browser_bug462673.js36
-rw-r--r--browser/base/content/test/general/browser_bug477014.js25
-rw-r--r--browser/base/content/test/general/browser_bug479408.js17
-rw-r--r--browser/base/content/test/general/browser_bug479408_sample.html4
-rw-r--r--browser/base/content/test/general/browser_bug481560.js21
-rw-r--r--browser/base/content/test/general/browser_bug484315.js23
-rw-r--r--browser/base/content/test/general/browser_bug491431.js34
-rw-r--r--browser/base/content/test/general/browser_bug495058.js38
-rw-r--r--browser/base/content/test/general/browser_bug517902.js42
-rw-r--r--browser/base/content/test/general/browser_bug519216.js45
-rw-r--r--browser/base/content/test/general/browser_bug520538.js15
-rw-r--r--browser/base/content/test/general/browser_bug521216.js50
-rw-r--r--browser/base/content/test/general/browser_bug533232.js36
-rw-r--r--browser/base/content/test/general/browser_bug537013.js135
-rw-r--r--browser/base/content/test/general/browser_bug537474.js8
-rw-r--r--browser/base/content/test/general/browser_bug550565.js44
-rw-r--r--browser/base/content/test/general/browser_bug553455.js1200
-rw-r--r--browser/base/content/test/general/browser_bug555224.js40
-rw-r--r--browser/base/content/test/general/browser_bug555767.js54
-rw-r--r--browser/base/content/test/general/browser_bug559991.js42
-rw-r--r--browser/base/content/test/general/browser_bug561636.js370
-rw-r--r--browser/base/content/test/general/browser_bug563588.js30
-rw-r--r--browser/base/content/test/general/browser_bug565575.js14
-rw-r--r--browser/base/content/test/general/browser_bug567306.js50
-rw-r--r--browser/base/content/test/general/browser_bug575561.js97
-rw-r--r--browser/base/content/test/general/browser_bug575830.js33
-rw-r--r--browser/base/content/test/general/browser_bug577121.js29
-rw-r--r--browser/base/content/test/general/browser_bug578534.js23
-rw-r--r--browser/base/content/test/general/browser_bug579872.js28
-rw-r--r--browser/base/content/test/general/browser_bug580638.js60
-rw-r--r--browser/base/content/test/general/browser_bug580956.js26
-rw-r--r--browser/base/content/test/general/browser_bug581242.js21
-rw-r--r--browser/base/content/test/general/browser_bug581253.js86
-rw-r--r--browser/base/content/test/general/browser_bug585558.js153
-rw-r--r--browser/base/content/test/general/browser_bug585785.js35
-rw-r--r--browser/base/content/test/general/browser_bug585830.js25
-rw-r--r--browser/base/content/test/general/browser_bug590206.js163
-rw-r--r--browser/base/content/test/general/browser_bug592338.js163
-rw-r--r--browser/base/content/test/general/browser_bug594131.js21
-rw-r--r--browser/base/content/test/general/browser_bug595507.js36
-rw-r--r--browser/base/content/test/general/browser_bug596687.js25
-rw-r--r--browser/base/content/test/general/browser_bug597218.js38
-rw-r--r--browser/base/content/test/general/browser_bug609700.js20
-rw-r--r--browser/base/content/test/general/browser_bug623893.js37
-rw-r--r--browser/base/content/test/general/browser_bug624734.js29
-rw-r--r--browser/base/content/test/general/browser_bug633691.js28
-rw-r--r--browser/base/content/test/general/browser_bug647886.js40
-rw-r--r--browser/base/content/test/general/browser_bug655584.js23
-rw-r--r--browser/base/content/test/general/browser_bug664672.js19
-rw-r--r--browser/base/content/test/general/browser_bug676619.js124
-rw-r--r--browser/base/content/test/general/browser_bug678392-1.html12
-rw-r--r--browser/base/content/test/general/browser_bug678392-2.html12
-rw-r--r--browser/base/content/test/general/browser_bug678392.js191
-rw-r--r--browser/base/content/test/general/browser_bug710878.js34
-rw-r--r--browser/base/content/test/general/browser_bug719271.js95
-rw-r--r--browser/base/content/test/general/browser_bug724239.js11
-rw-r--r--browser/base/content/test/general/browser_bug734076.js114
-rw-r--r--browser/base/content/test/general/browser_bug735471.js23
-rw-r--r--browser/base/content/test/general/browser_bug749738.js29
-rw-r--r--browser/base/content/test/general/browser_bug763468_perwindowpb.js70
-rw-r--r--browser/base/content/test/general/browser_bug767836_perwindowpb.js90
-rw-r--r--browser/base/content/test/general/browser_bug817947.js55
-rw-r--r--browser/base/content/test/general/browser_bug822367.js187
-rw-r--r--browser/base/content/test/general/browser_bug832435.js23
-rw-r--r--browser/base/content/test/general/browser_bug839103.js120
-rw-r--r--browser/base/content/test/general/browser_bug882977.js29
-rw-r--r--browser/base/content/test/general/browser_bug902156.js174
-rw-r--r--browser/base/content/test/general/browser_bug906190.js240
-rw-r--r--browser/base/content/test/general/browser_bug963945.js23
-rw-r--r--browser/base/content/test/general/browser_bug970746.js121
-rw-r--r--browser/base/content/test/general/browser_bug970746.xhtml20
-rw-r--r--browser/base/content/test/general/browser_clipboard.js174
-rw-r--r--browser/base/content/test/general/browser_clipboard_pastefile.js62
-rw-r--r--browser/base/content/test/general/browser_contentAltClick.js107
-rw-r--r--browser/base/content/test/general/browser_contentAreaClick.js307
-rw-r--r--browser/base/content/test/general/browser_contentSearchUI.js771
-rw-r--r--browser/base/content/test/general/browser_contextmenu.js996
-rw-r--r--browser/base/content/test/general/browser_contextmenu_childprocess.js84
-rw-r--r--browser/base/content/test/general/browser_contextmenu_input.js243
-rw-r--r--browser/base/content/test/general/browser_csp_block_all_mixedcontent.js55
-rw-r--r--browser/base/content/test/general/browser_ctrlTab.js185
-rw-r--r--browser/base/content/test/general/browser_datachoices_notification.js221
-rw-r--r--browser/base/content/test/general/browser_decoderDoctor.js122
-rw-r--r--browser/base/content/test/general/browser_devedition.js129
-rw-r--r--browser/base/content/test/general/browser_discovery.js162
-rw-r--r--browser/base/content/test/general/browser_documentnavigation.js266
-rw-r--r--browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js221
-rw-r--r--browser/base/content/test/general/browser_double_close_tab.js80
-rw-r--r--browser/base/content/test/general/browser_drag.js45
-rw-r--r--browser/base/content/test/general/browser_duplicateIDs.js8
-rw-r--r--browser/base/content/test/general/browser_e10s_about_process.js114
-rw-r--r--browser/base/content/test/general/browser_e10s_chrome_process.js150
-rw-r--r--browser/base/content/test/general/browser_e10s_javascript.js11
-rw-r--r--browser/base/content/test/general/browser_e10s_switchbrowser.js261
-rw-r--r--browser/base/content/test/general/browser_favicon_change.js41
-rw-r--r--browser/base/content/test/general/browser_favicon_change_not_in_document.js34
-rw-r--r--browser/base/content/test/general/browser_feed_discovery.js33
-rw-r--r--browser/base/content/test/general/browser_findbarClose.js35
-rw-r--r--browser/base/content/test/general/browser_focusonkeydown.js26
-rw-r--r--browser/base/content/test/general/browser_fullscreen-window-open.js347
-rw-r--r--browser/base/content/test/general/browser_fxa_migrate.js18
-rw-r--r--browser/base/content/test/general/browser_fxa_oauth.html30
-rw-r--r--browser/base/content/test/general/browser_fxa_oauth.js327
-rw-r--r--browser/base/content/test/general/browser_fxa_oauth_with_keys.html33
-rw-r--r--browser/base/content/test/general/browser_fxa_web_channel.html138
-rw-r--r--browser/base/content/test/general/browser_fxa_web_channel.js210
-rw-r--r--browser/base/content/test/general/browser_fxaccounts.js261
-rw-r--r--browser/base/content/test/general/browser_gZipOfflineChild.js80
-rw-r--r--browser/base/content/test/general/browser_gestureSupport.js670
-rw-r--r--browser/base/content/test/general/browser_getshortcutoruri.js143
-rw-r--r--browser/base/content/test/general/browser_hide_removing.js39
-rw-r--r--browser/base/content/test/general/browser_homeDrop.js90
-rw-r--r--browser/base/content/test/general/browser_identity_UI.js146
-rw-r--r--browser/base/content/test/general/browser_insecureLoginForms.js162
-rw-r--r--browser/base/content/test/general/browser_invalid_uri_back_forward_manipulation.js39
-rw-r--r--browser/base/content/test/general/browser_keywordBookmarklets.js54
-rw-r--r--browser/base/content/test/general/browser_keywordSearch.js88
-rw-r--r--browser/base/content/test/general/browser_keywordSearch_postData.js94
-rw-r--r--browser/base/content/test/general/browser_lastAccessedTab.js47
-rw-r--r--browser/base/content/test/general/browser_mcb_redirect.js314
-rw-r--r--browser/base/content/test/general/browser_menuButtonBadgeManager.js46
-rw-r--r--browser/base/content/test/general/browser_menuButtonFitts.js32
-rw-r--r--browser/base/content/test/general/browser_middleMouse_noJSPaste.js34
-rw-r--r--browser/base/content/test/general/browser_minimize.js18
-rw-r--r--browser/base/content/test/general/browser_misused_characters_in_strings.js244
-rw-r--r--browser/base/content/test/general/browser_mixedContentFramesOnHttp.js34
-rw-r--r--browser/base/content/test/general/browser_mixedContentFromOnunload.js49
-rw-r--r--browser/base/content/test/general/browser_mixed_content_cert_override.js54
-rw-r--r--browser/base/content/test/general/browser_mixedcontent_securityflags.js70
-rw-r--r--browser/base/content/test/general/browser_modifiedclick_inherit_principal.js30
-rw-r--r--browser/base/content/test/general/browser_newTabDrop.js99
-rw-r--r--browser/base/content/test/general/browser_newWindowDrop.js120
-rw-r--r--browser/base/content/test/general/browser_newwindow_focus.js96
-rw-r--r--browser/base/content/test/general/browser_no_mcb_on_http_site.js106
-rw-r--r--browser/base/content/test/general/browser_offlineQuotaNotification.js95
-rw-r--r--browser/base/content/test/general/browser_overflowScroll.js91
-rw-r--r--browser/base/content/test/general/browser_pageInfo.js38
-rw-r--r--browser/base/content/test/general/browser_page_style_menu.js97
-rw-r--r--browser/base/content/test/general/browser_page_style_menu_update.js67
-rw-r--r--browser/base/content/test/general/browser_pageinfo_svg_image.js38
-rw-r--r--browser/base/content/test/general/browser_parsable_css.js376
-rw-r--r--browser/base/content/test/general/browser_parsable_script.js132
-rw-r--r--browser/base/content/test/general/browser_permissions.js202
-rw-r--r--browser/base/content/test/general/browser_pinnedTabs.js75
-rw-r--r--browser/base/content/test/general/browser_plainTextLinks.js146
-rw-r--r--browser/base/content/test/general/browser_printpreview.js74
-rw-r--r--browser/base/content/test/general/browser_private_browsing_window.js65
-rw-r--r--browser/base/content/test/general/browser_private_no_prompt.js12
-rw-r--r--browser/base/content/test/general/browser_purgehistory_clears_sh.js60
-rw-r--r--browser/base/content/test/general/browser_refreshBlocker.js135
-rw-r--r--browser/base/content/test/general/browser_registerProtocolHandler_notification.html15
-rw-r--r--browser/base/content/test/general/browser_registerProtocolHandler_notification.js43
-rw-r--r--browser/base/content/test/general/browser_relatedTabs.js51
-rw-r--r--browser/base/content/test/general/browser_remoteTroubleshoot.js93
-rw-r--r--browser/base/content/test/general/browser_remoteWebNavigation_postdata.js50
-rw-r--r--browser/base/content/test/general/browser_removeTabsToTheEnd.js24
-rw-r--r--browser/base/content/test/general/browser_restore_isAppTab.js160
-rw-r--r--browser/base/content/test/general/browser_sanitize-passwordDisabledHosts.js39
-rw-r--r--browser/base/content/test/general/browser_sanitize-sitepermissions.js52
-rw-r--r--browser/base/content/test/general/browser_sanitize-timespans.js733
-rw-r--r--browser/base/content/test/general/browser_sanitizeDialog.js1027
-rw-r--r--browser/base/content/test/general/browser_save_link-perwindowpb.js199
-rw-r--r--browser/base/content/test/general/browser_save_link_when_window_navigates.js173
-rw-r--r--browser/base/content/test/general/browser_save_private_link_perwindowpb.js116
-rw-r--r--browser/base/content/test/general/browser_save_video.js87
-rw-r--r--browser/base/content/test/general/browser_save_video_frame.js125
-rw-r--r--browser/base/content/test/general/browser_scope.js10
-rw-r--r--browser/base/content/test/general/browser_selectTabAtIndex.js81
-rw-r--r--browser/base/content/test/general/browser_selectpopup.js563
-rw-r--r--browser/base/content/test/general/browser_ssl_error_reports.js174
-rw-r--r--browser/base/content/test/general/browser_star_hsts.js85
-rw-r--r--browser/base/content/test/general/browser_star_hsts.sjs13
-rw-r--r--browser/base/content/test/general/browser_subframe_favicons_not_used.js20
-rw-r--r--browser/base/content/test/general/browser_syncui.js205
-rw-r--r--browser/base/content/test/general/browser_tabDrop.js103
-rw-r--r--browser/base/content/test/general/browser_tabReorder.js49
-rw-r--r--browser/base/content/test/general/browser_tab_close_dependent_window.js24
-rw-r--r--browser/base/content/test/general/browser_tab_detach_restore.js34
-rw-r--r--browser/base/content/test/general/browser_tab_drag_drop_perwindow.js216
-rw-r--r--browser/base/content/test/general/browser_tab_dragdrop.js186
-rw-r--r--browser/base/content/test/general/browser_tab_dragdrop2.js57
-rw-r--r--browser/base/content/test/general/browser_tab_dragdrop2_frame1.xul169
-rw-r--r--browser/base/content/test/general/browser_tabbar_big_widgets.js29
-rw-r--r--browser/base/content/test/general/browser_tabfocus.js565
-rw-r--r--browser/base/content/test/general/browser_tabkeynavigation.js156
-rw-r--r--browser/base/content/test/general/browser_tabopen_reflows.js157
-rw-r--r--browser/base/content/test/general/browser_tabs_close_beforeunload.js49
-rw-r--r--browser/base/content/test/general/browser_tabs_isActive.js152
-rw-r--r--browser/base/content/test/general/browser_tabs_owner.js44
-rw-r--r--browser/base/content/test/general/browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js126
-rw-r--r--browser/base/content/test/general/browser_trackingUI_1.js170
-rw-r--r--browser/base/content/test/general/browser_trackingUI_2.js96
-rw-r--r--browser/base/content/test/general/browser_trackingUI_3.js52
-rw-r--r--browser/base/content/test/general/browser_trackingUI_4.js109
-rw-r--r--browser/base/content/test/general/browser_trackingUI_5.js131
-rw-r--r--browser/base/content/test/general/browser_trackingUI_6.js46
-rw-r--r--browser/base/content/test/general/browser_trackingUI_telemetry.js145
-rw-r--r--browser/base/content/test/general/browser_typeAheadFind.js22
-rw-r--r--browser/base/content/test/general/browser_unknownContentType_title.js33
-rw-r--r--browser/base/content/test/general/browser_unloaddialogs.js41
-rw-r--r--browser/base/content/test/general/browser_utilityOverlay.js112
-rw-r--r--browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js55
-rw-r--r--browser/base/content/test/general/browser_visibleFindSelection.js52
-rw-r--r--browser/base/content/test/general/browser_visibleTabs.js97
-rw-r--r--browser/base/content/test/general/browser_visibleTabs_bookmarkAllPages.js34
-rw-r--r--browser/base/content/test/general/browser_visibleTabs_bookmarkAllTabs.js66
-rw-r--r--browser/base/content/test/general/browser_visibleTabs_contextMenu.js72
-rw-r--r--browser/base/content/test/general/browser_visibleTabs_tabPreview.js41
-rw-r--r--browser/base/content/test/general/browser_web_channel.html189
-rw-r--r--browser/base/content/test/general/browser_web_channel.js436
-rw-r--r--browser/base/content/test/general/browser_web_channel_iframe.html96
-rw-r--r--browser/base/content/test/general/browser_windowactivation.js183
-rw-r--r--browser/base/content/test/general/browser_windowopen_reflows.js117
-rw-r--r--browser/base/content/test/general/browser_zbug569342.js80
-rw-r--r--browser/base/content/test/general/bug1262648_string_with_newlines.dtd3
-rw-r--r--browser/base/content/test/general/bug364677-data.xml5
-rw-r--r--browser/base/content/test/general/bug364677-data.xml^headers^1
-rw-r--r--browser/base/content/test/general/bug395533-data.txt6
-rw-r--r--browser/base/content/test/general/bug592338.html24
-rw-r--r--browser/base/content/test/general/bug792517-2.html5
-rw-r--r--browser/base/content/test/general/bug792517.html5
-rw-r--r--browser/base/content/test/general/bug792517.sjs13
-rw-r--r--browser/base/content/test/general/bug839103.css1
-rw-r--r--browser/base/content/test/general/clipboard_pastefile.html37
-rw-r--r--browser/base/content/test/general/close_beforeunload.html8
-rw-r--r--browser/base/content/test/general/close_beforeunload_opens_second_tab.html3
-rw-r--r--browser/base/content/test/general/contentSearchUI.html21
-rw-r--r--browser/base/content/test/general/contentSearchUI.js209
-rw-r--r--browser/base/content/test/general/content_aboutAccounts.js87
-rw-r--r--browser/base/content/test/general/contextmenu_common.js324
-rw-r--r--browser/base/content/test/general/ctxmenu-image.pngbin5401 -> 0 bytes
-rw-r--r--browser/base/content/test/general/discovery.html8
-rw-r--r--browser/base/content/test/general/download_page.html47
-rw-r--r--browser/base/content/test/general/dummy_page.html9
-rw-r--r--browser/base/content/test/general/feed_discovery.html73
-rw-r--r--browser/base/content/test/general/feed_tab.html17
-rw-r--r--browser/base/content/test/general/file_bug1045809_1.html7
-rw-r--r--browser/base/content/test/general/file_bug1045809_2.html7
-rw-r--r--browser/base/content/test/general/file_bug822367_1.html18
-rw-r--r--browser/base/content/test/general/file_bug822367_1.js1
-rw-r--r--browser/base/content/test/general/file_bug822367_2.html16
-rw-r--r--browser/base/content/test/general/file_bug822367_3.html27
-rw-r--r--browser/base/content/test/general/file_bug822367_4.html18
-rw-r--r--browser/base/content/test/general/file_bug822367_4.js1
-rw-r--r--browser/base/content/test/general/file_bug822367_4B.html18
-rw-r--r--browser/base/content/test/general/file_bug822367_5.html24
-rw-r--r--browser/base/content/test/general/file_bug822367_6.html16
-rw-r--r--browser/base/content/test/general/file_bug902156.js5
-rw-r--r--browser/base/content/test/general/file_bug902156_1.html15
-rw-r--r--browser/base/content/test/general/file_bug902156_2.html17
-rw-r--r--browser/base/content/test/general/file_bug902156_3.html15
-rw-r--r--browser/base/content/test/general/file_bug906190.js5
-rw-r--r--browser/base/content/test/general/file_bug906190.sjs17
-rw-r--r--browser/base/content/test/general/file_bug906190_1.html15
-rw-r--r--browser/base/content/test/general/file_bug906190_2.html15
-rw-r--r--browser/base/content/test/general/file_bug906190_3_4.html14
-rw-r--r--browser/base/content/test/general/file_bug906190_redirected.html15
-rw-r--r--browser/base/content/test/general/file_bug970276_favicon1.icobin1406 -> 0 bytes
-rw-r--r--browser/base/content/test/general/file_bug970276_favicon2.icobin1406 -> 0 bytes
-rw-r--r--browser/base/content/test/general/file_bug970276_popup1.html14
-rw-r--r--browser/base/content/test/general/file_bug970276_popup2.html12
-rw-r--r--browser/base/content/test/general/file_csp_block_all_mixedcontent.html9
-rw-r--r--browser/base/content/test/general/file_csp_block_all_mixedcontent.js3
-rw-r--r--browser/base/content/test/general/file_documentnavigation_frameset.html12
-rw-r--r--browser/base/content/test/general/file_double_close_tab.html15
-rw-r--r--browser/base/content/test/general/file_favicon_change.html13
-rw-r--r--browser/base/content/test/general/file_favicon_change_not_in_document.html21
-rw-r--r--browser/base/content/test/general/file_fullscreen-window-open.html24
-rw-r--r--browser/base/content/test/general/file_generic_favicon.icobin1406 -> 0 bytes
-rw-r--r--browser/base/content/test/general/file_mediaPlayback.html2
-rw-r--r--browser/base/content/test/general/file_mixedContentFramesOnHttp.html14
-rw-r--r--browser/base/content/test/general/file_mixedContentFromOnunload.html18
-rw-r--r--browser/base/content/test/general/file_mixedContentFromOnunload_test1.html14
-rw-r--r--browser/base/content/test/general/file_mixedContentFromOnunload_test2.html15
-rw-r--r--browser/base/content/test/general/file_mixedPassiveContent.html13
-rw-r--r--browser/base/content/test/general/file_trackingUI_6.html16
-rw-r--r--browser/base/content/test/general/file_trackingUI_6.js2
-rw-r--r--browser/base/content/test/general/file_trackingUI_6.js^headers^1
-rw-r--r--browser/base/content/test/general/file_with_favicon.html12
-rw-r--r--browser/base/content/test/general/fxa_profile_handler.sjs34
-rw-r--r--browser/base/content/test/general/gZipOfflineChild.cacheManifest2
-rw-r--r--browser/base/content/test/general/gZipOfflineChild.cacheManifest^headers^1
-rw-r--r--browser/base/content/test/general/gZipOfflineChild.htmlbin303 -> 0 bytes
-rw-r--r--browser/base/content/test/general/gZipOfflineChild.html^headers^2
-rw-r--r--browser/base/content/test/general/gZipOfflineChild_uncompressed.html21
-rw-r--r--browser/base/content/test/general/head.js1069
-rw-r--r--browser/base/content/test/general/head_plain.js27
-rw-r--r--browser/base/content/test/general/healthreport_pingData.js17
-rw-r--r--browser/base/content/test/general/healthreport_testRemoteCommands.html243
-rw-r--r--browser/base/content/test/general/insecure_opener.html9
-rw-r--r--browser/base/content/test/general/mochitest.ini27
-rw-r--r--browser/base/content/test/general/moz.pngbin580 -> 0 bytes
-rw-r--r--browser/base/content/test/general/navigating_window_with_download.html7
-rw-r--r--browser/base/content/test/general/offlineByDefault.js17
-rw-r--r--browser/base/content/test/general/offlineChild.cacheManifest2
-rw-r--r--browser/base/content/test/general/offlineChild.cacheManifest^headers^1
-rw-r--r--browser/base/content/test/general/offlineChild.html20
-rw-r--r--browser/base/content/test/general/offlineChild2.cacheManifest2
-rw-r--r--browser/base/content/test/general/offlineChild2.cacheManifest^headers^1
-rw-r--r--browser/base/content/test/general/offlineChild2.html20
-rw-r--r--browser/base/content/test/general/offlineEvent.cacheManifest2
-rw-r--r--browser/base/content/test/general/offlineEvent.cacheManifest^headers^1
-rw-r--r--browser/base/content/test/general/offlineEvent.html9
-rw-r--r--browser/base/content/test/general/offlineQuotaNotification.cacheManifest7
-rw-r--r--browser/base/content/test/general/offlineQuotaNotification.html9
-rw-r--r--browser/base/content/test/general/page_style_sample.html41
-rw-r--r--browser/base/content/test/general/parsingTestHelpers.jsm131
-rw-r--r--browser/base/content/test/general/permissions.html14
-rw-r--r--browser/base/content/test/general/pinning_headers.sjs23
-rw-r--r--browser/base/content/test/general/print_postdata.sjs22
-rw-r--r--browser/base/content/test/general/refresh_header.sjs24
-rw-r--r--browser/base/content/test/general/refresh_meta.sjs36
-rw-r--r--browser/base/content/test/general/searchSuggestionEngine.sjs9
-rw-r--r--browser/base/content/test/general/searchSuggestionEngine.xml9
-rw-r--r--browser/base/content/test/general/searchSuggestionEngine2.xml9
-rw-r--r--browser/base/content/test/general/ssl_error_reports.sjs91
-rw-r--r--browser/base/content/test/general/subtst_contextmenu.html73
-rw-r--r--browser/base/content/test/general/subtst_contextmenu_input.html29
-rw-r--r--browser/base/content/test/general/subtst_contextmenu_xul.xul9
-rw-r--r--browser/base/content/test/general/svg_image.html11
-rw-r--r--browser/base/content/test/general/test-mixedcontent-securityerrors.html21
-rw-r--r--browser/base/content/test/general/test_bug364677.html32
-rw-r--r--browser/base/content/test/general/test_bug395533.html38
-rw-r--r--browser/base/content/test/general/test_bug435035.html1
-rw-r--r--browser/base/content/test/general/test_bug462673.html18
-rw-r--r--browser/base/content/test/general/test_bug628179.html10
-rw-r--r--browser/base/content/test/general/test_bug839103.html10
-rw-r--r--browser/base/content/test/general/test_bug959531.html9
-rw-r--r--browser/base/content/test/general/test_mcb_double_redirect_image.html23
-rw-r--r--browser/base/content/test/general/test_mcb_redirect.html15
-rw-r--r--browser/base/content/test/general/test_mcb_redirect.js5
-rw-r--r--browser/base/content/test/general/test_mcb_redirect.sjs22
-rw-r--r--browser/base/content/test/general/test_mcb_redirect_image.html23
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_font.css10
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_font.html47
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_font2.css1
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_font2.html48
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_img.css3
-rw-r--r--browser/base/content/test/general/test_no_mcb_on_http_site_img.html47
-rw-r--r--browser/base/content/test/general/test_offlineNotification.html129
-rw-r--r--browser/base/content/test/general/test_offline_gzip.html21
-rw-r--r--browser/base/content/test/general/test_process_flags_chrome.html10
-rw-r--r--browser/base/content/test/general/test_remoteTroubleshoot.html50
-rw-r--r--browser/base/content/test/general/title_test.svg59
-rw-r--r--browser/base/content/test/general/trackingPage.html12
-rw-r--r--browser/base/content/test/general/unknownContentType_file.pif1
-rw-r--r--browser/base/content/test/general/unknownContentType_file.pif^headers^1
-rw-r--r--browser/base/content/test/general/video.oggbin285310 -> 0 bytes
-rw-r--r--browser/base/content/test/general/web_video.html10
-rw-r--r--browser/base/content/test/general/web_video1.ogvbin28942 -> 0 bytes
-rw-r--r--browser/base/content/test/general/web_video1.ogv^headers^3
-rw-r--r--browser/base/content/test/general/zoom_test.html14
-rw-r--r--browser/base/content/test/newtab/.eslintrc.js7
-rw-r--r--browser/base/content/test/newtab/browser.ini55
-rw-r--r--browser/base/content/test/newtab/browser_newtab_1188015.js26
-rw-r--r--browser/base/content/test/newtab/browser_newtab_background_captures.js64
-rw-r--r--browser/base/content/test/newtab/browser_newtab_block.js95
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug1145428.js87
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug1178586.js83
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug1194895.js146
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug1271075.js32
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug721442.js28
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug722273.js73
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug723102.js24
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug723121.js42
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug725996.js35
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug734043.js34
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug735987.js32
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug752841.js56
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug765628.js32
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug876313.js24
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug991111.js35
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug991210.js34
-rw-r--r--browser/base/content/test/newtab/browser_newtab_bug998387.js39
-rw-r--r--browser/base/content/test/newtab/browser_newtab_disable.js49
-rw-r--r--browser/base/content/test/newtab/browser_newtab_drag_drop.js95
-rw-r--r--browser/base/content/test/newtab/browser_newtab_drag_drop_ext.js63
-rw-r--r--browser/base/content/test/newtab/browser_newtab_drop_preview.js41
-rw-r--r--browser/base/content/test/newtab/browser_newtab_enhanced.js228
-rw-r--r--browser/base/content/test/newtab/browser_newtab_focus.js48
-rw-r--r--browser/base/content/test/newtab/browser_newtab_perwindow_private_browsing.js56
-rw-r--r--browser/base/content/test/newtab/browser_newtab_reflow_load.js37
-rw-r--r--browser/base/content/test/newtab/browser_newtab_reportLinkAction.js83
-rw-r--r--browser/base/content/test/newtab/browser_newtab_search.js247
-rw-r--r--browser/base/content/test/newtab/browser_newtab_sponsored_icon_click.js53
-rw-r--r--browser/base/content/test/newtab/browser_newtab_undo.js47
-rw-r--r--browser/base/content/test/newtab/browser_newtab_unpin.js56
-rw-r--r--browser/base/content/test/newtab/browser_newtab_update.js48
-rw-r--r--browser/base/content/test/newtab/content-reflows.js26
-rw-r--r--browser/base/content/test/newtab/head.js552
-rw-r--r--browser/base/content/test/newtab/searchEngine1x2xLogo.xml9
-rw-r--r--browser/base/content/test/newtab/searchEngine1xLogo.xml7
-rw-r--r--browser/base/content/test/newtab/searchEngine2xLogo.xml7
-rw-r--r--browser/base/content/test/newtab/searchEngineFavicon.xml6
-rw-r--r--browser/base/content/test/newtab/searchEngineNoLogo.xml5
-rw-r--r--browser/base/content/test/plugins/.eslintrc.js7
-rw-r--r--browser/base/content/test/plugins/blockNoPlugins.xml7
-rw-r--r--browser/base/content/test/plugins/blockPluginHard.xml11
-rw-r--r--browser/base/content/test/plugins/blockPluginInfoURL.xml12
-rw-r--r--browser/base/content/test/plugins/blockPluginVulnerableNoUpdate.xml11
-rw-r--r--browser/base/content/test/plugins/blockPluginVulnerableUpdatable.xml11
-rw-r--r--browser/base/content/test/plugins/blocklist_proxy.js78
-rw-r--r--browser/base/content/test/plugins/browser.ini78
-rw-r--r--browser/base/content/test/plugins/browser_CTP_context_menu.js69
-rw-r--r--browser/base/content/test/plugins/browser_CTP_crashreporting.js233
-rw-r--r--browser/base/content/test/plugins/browser_CTP_data_urls.js255
-rw-r--r--browser/base/content/test/plugins/browser_CTP_drag_drop.js96
-rw-r--r--browser/base/content/test/plugins/browser_CTP_hide_overlay.js88
-rw-r--r--browser/base/content/test/plugins/browser_CTP_iframe.js48
-rw-r--r--browser/base/content/test/plugins/browser_CTP_multi_allow.js99
-rw-r--r--browser/base/content/test/plugins/browser_CTP_nonplugins.js58
-rw-r--r--browser/base/content/test/plugins/browser_CTP_notificationBar.js151
-rw-r--r--browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js120
-rw-r--r--browser/base/content/test/plugins/browser_CTP_remove_navigate.js79
-rw-r--r--browser/base/content/test/plugins/browser_CTP_resize.js130
-rw-r--r--browser/base/content/test/plugins/browser_CTP_zoom.js62
-rw-r--r--browser/base/content/test/plugins/browser_blocking.js349
-rw-r--r--browser/base/content/test/plugins/browser_blocklist_content.js104
-rw-r--r--browser/base/content/test/plugins/browser_bug743421.js119
-rw-r--r--browser/base/content/test/plugins/browser_bug744745.js50
-rw-r--r--browser/base/content/test/plugins/browser_bug787619.js65
-rw-r--r--browser/base/content/test/plugins/browser_bug797677.js43
-rw-r--r--browser/base/content/test/plugins/browser_bug812562.js80
-rw-r--r--browser/base/content/test/plugins/browser_bug818118.js40
-rw-r--r--browser/base/content/test/plugins/browser_bug820497.js71
-rw-r--r--browser/base/content/test/plugins/browser_clearplugindata.html30
-rw-r--r--browser/base/content/test/plugins/browser_clearplugindata.js127
-rw-r--r--browser/base/content/test/plugins/browser_clearplugindata_noage.html30
-rw-r--r--browser/base/content/test/plugins/browser_globalplugin_crashinfobar.js34
-rw-r--r--browser/base/content/test/plugins/browser_pageInfo_plugins.js191
-rw-r--r--browser/base/content/test/plugins/browser_pluginCrashCommentAndURL.js207
-rw-r--r--browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js254
-rw-r--r--browser/base/content/test/plugins/browser_plugin_reloading.js85
-rw-r--r--browser/base/content/test/plugins/browser_pluginnotification.js626
-rw-r--r--browser/base/content/test/plugins/browser_plugins_added_dynamically.js137
-rw-r--r--browser/base/content/test/plugins/browser_private_clicktoplay.js216
-rw-r--r--browser/base/content/test/plugins/head.js396
-rw-r--r--browser/base/content/test/plugins/plugin_add_dynamically.html18
-rw-r--r--browser/base/content/test/plugins/plugin_alternate_content.html9
-rw-r--r--browser/base/content/test/plugins/plugin_big.html9
-rw-r--r--browser/base/content/test/plugins/plugin_both.html10
-rw-r--r--browser/base/content/test/plugins/plugin_both2.html10
-rw-r--r--browser/base/content/test/plugins/plugin_bug744745.html12
-rw-r--r--browser/base/content/test/plugins/plugin_bug749455.html8
-rw-r--r--browser/base/content/test/plugins/plugin_bug787619.html9
-rw-r--r--browser/base/content/test/plugins/plugin_bug797677.html5
-rw-r--r--browser/base/content/test/plugins/plugin_bug820497.html17
-rw-r--r--browser/base/content/test/plugins/plugin_clickToPlayAllow.html9
-rw-r--r--browser/base/content/test/plugins/plugin_clickToPlayDeny.html9
-rw-r--r--browser/base/content/test/plugins/plugin_crashCommentAndURL.html27
-rw-r--r--browser/base/content/test/plugins/plugin_data_url.html11
-rw-r--r--browser/base/content/test/plugins/plugin_hidden_to_visible.html11
-rw-r--r--browser/base/content/test/plugins/plugin_iframe.html9
-rw-r--r--browser/base/content/test/plugins/plugin_outsideScrollArea.html25
-rw-r--r--browser/base/content/test/plugins/plugin_overlayed.html27
-rw-r--r--browser/base/content/test/plugins/plugin_positioned.html12
-rw-r--r--browser/base/content/test/plugins/plugin_small.html9
-rw-r--r--browser/base/content/test/plugins/plugin_small_2.html9
-rw-r--r--browser/base/content/test/plugins/plugin_syncRemoved.html15
-rw-r--r--browser/base/content/test/plugins/plugin_test.html9
-rw-r--r--browser/base/content/test/plugins/plugin_test2.html10
-rw-r--r--browser/base/content/test/plugins/plugin_test3.html9
-rw-r--r--browser/base/content/test/plugins/plugin_two_types.html9
-rw-r--r--browser/base/content/test/plugins/plugin_unknown.html9
-rw-r--r--browser/base/content/test/plugins/plugin_zoom.html10
-rw-r--r--browser/base/content/test/popupNotifications/.eslintrc.js7
-rw-r--r--browser/base/content/test/popupNotifications/browser.ini18
-rw-r--r--browser/base/content/test/popupNotifications/browser_displayURI.js28
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification.js203
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification_2.js266
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification_3.js305
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification_4.js294
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js211
-rw-r--r--browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js74
-rw-r--r--browser/base/content/test/popupNotifications/browser_reshow_in_background.js52
-rw-r--r--browser/base/content/test/popupNotifications/head.js303
-rw-r--r--browser/base/content/test/popups/browser.ini4
-rw-r--r--browser/base/content/test/popups/browser_popupUI.js37
-rw-r--r--browser/base/content/test/popups/browser_popup_blocker.js96
-rw-r--r--browser/base/content/test/popups/popup_blocker.html13
-rw-r--r--browser/base/content/test/referrer/.eslintrc.js7
-rw-r--r--browser/base/content/test/referrer/browser.ini24
-rw-r--r--browser/base/content/test/referrer/browser_referrer_middle_click.js20
-rw-r--r--browser/base/content/test/referrer/browser_referrer_middle_click_in_container.js27
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab.js59
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab2.js31
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab3.js63
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_private.js22
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_tab.js21
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_window.js22
-rw-r--r--browser/base/content/test/referrer/browser_referrer_open_link_in_window_in_container.js32
-rw-r--r--browser/base/content/test/referrer/browser_referrer_simple_click.js20
-rw-r--r--browser/base/content/test/referrer/file_referrer_policyserver.sjs37
-rw-r--r--browser/base/content/test/referrer/file_referrer_policyserver_attr.sjs36
-rw-r--r--browser/base/content/test/referrer/file_referrer_testserver.sjs31
-rw-r--r--browser/base/content/test/referrer/head.js265
-rw-r--r--browser/base/content/test/siteIdentity/browser.ini8
-rw-r--r--browser/base/content/test/siteIdentity/browser_identityBlock_focus.js62
-rw-r--r--browser/base/content/test/siteIdentity/browser_identityPopup_focus.js27
-rw-r--r--browser/base/content/test/siteIdentity/head.js6
-rw-r--r--browser/base/content/test/social/.eslintrc.js7
-rw-r--r--browser/base/content/test/social/blocklist.xml6
-rw-r--r--browser/base/content/test/social/browser.ini23
-rw-r--r--browser/base/content/test/social/browser_aboutHome_activation.js229
-rw-r--r--browser/base/content/test/social/browser_addons.js217
-rw-r--r--browser/base/content/test/social/browser_blocklist.js211
-rw-r--r--browser/base/content/test/social/browser_share.js396
-rw-r--r--browser/base/content/test/social/browser_social_activation.js270
-rw-r--r--browser/base/content/test/social/head.js273
-rw-r--r--browser/base/content/test/social/microformats.html18
-rw-r--r--browser/base/content/test/social/moz.pngbin580 -> 0 bytes
-rw-r--r--browser/base/content/test/social/opengraph/og_invalid_url.html11
-rw-r--r--browser/base/content/test/social/opengraph/opengraph.html13
-rw-r--r--browser/base/content/test/social/opengraph/shortlink_linkrel.html10
-rw-r--r--browser/base/content/test/social/opengraph/shorturl_link.html10
-rw-r--r--browser/base/content/test/social/opengraph/shorturl_linkrel.html25
-rw-r--r--browser/base/content/test/social/share.html9
-rw-r--r--browser/base/content/test/social/share_activate.html35
-rw-r--r--browser/base/content/test/social/social_activate.html41
-rw-r--r--browser/base/content/test/social/social_activate_basic.html41
-rw-r--r--browser/base/content/test/social/social_activate_iframe.html11
-rw-r--r--browser/base/content/test/social/social_crash_content_helper.js31
-rw-r--r--browser/base/content/test/social/social_postActivation.html12
-rw-r--r--browser/base/content/test/tabPrompts/.eslintrc.js7
-rw-r--r--browser/base/content/test/tabPrompts/browser.ini4
-rw-r--r--browser/base/content/test/tabPrompts/browser_closeTabSpecificPanels.js41
-rw-r--r--browser/base/content/test/tabPrompts/browser_multiplePrompts.js72
-rw-r--r--browser/base/content/test/tabPrompts/browser_openPromptInBackgroundTab.js66
-rw-r--r--browser/base/content/test/tabPrompts/openPromptOffTimeout.html10
-rw-r--r--browser/base/content/test/tabcrashed/browser.ini13
-rw-r--r--browser/base/content/test/tabcrashed/browser_autoSubmitRequest.js152
-rw-r--r--browser/base/content/test/tabcrashed/browser_clearEmail.js85
-rw-r--r--browser/base/content/test/tabcrashed/browser_showForm.js40
-rw-r--r--browser/base/content/test/tabcrashed/browser_shown.js203
-rw-r--r--browser/base/content/test/tabcrashed/browser_withoutDump.js36
-rw-r--r--browser/base/content/test/tabcrashed/head.js110
-rw-r--r--browser/base/content/test/tabs/.eslintrc.js7
-rw-r--r--browser/base/content/test/tabs/browser.ini4
-rw-r--r--browser/base/content/test/tabs/browser_tabSpinnerProbe.js93
-rw-r--r--browser/base/content/test/tabs/browser_tabSwitchPrintPreview.js29
-rw-r--r--browser/base/content/test/urlbar/.eslintrc.js7
-rw-r--r--browser/base/content/test/urlbar/authenticate.sjs220
-rw-r--r--browser/base/content/test/urlbar/browser.ini101
-rw-r--r--browser/base/content/test/urlbar/browser_URLBarSetURI.js100
-rw-r--r--browser/base/content/test/urlbar/browser_action_keyword.js119
-rw-r--r--browser/base/content/test/urlbar/browser_action_keyword_override.js40
-rw-r--r--browser/base/content/test/urlbar/browser_action_searchengine.js36
-rw-r--r--browser/base/content/test/urlbar/browser_action_searchengine_alias.js35
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js57
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_autoselect.js92
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_cursor.js17
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_edit_completed.js48
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_enter_race.js122
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_no_title.js15
-rw-r--r--browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js102
-rw-r--r--browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js61
-rw-r--r--browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js37
-rw-r--r--browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js124
-rw-r--r--browser/base/content/test/urlbar/browser_bug1070778.js55
-rw-r--r--browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js29
-rw-r--r--browser/base/content/test/urlbar/browser_bug1225194-remotetab.js16
-rw-r--r--browser/base/content/test/urlbar/browser_bug304198.js109
-rw-r--r--browser/base/content/test/urlbar/browser_bug556061.js98
-rw-r--r--browser/base/content/test/urlbar/browser_bug562649.js24
-rw-r--r--browser/base/content/test/urlbar/browser_bug623155.js137
-rw-r--r--browser/base/content/test/urlbar/browser_bug783614.js13
-rw-r--r--browser/base/content/test/urlbar/browser_canonizeURL.js42
-rw-r--r--browser/base/content/test/urlbar/browser_dragdropURL.js15
-rw-r--r--browser/base/content/test/urlbar/browser_locationBarCommand.js218
-rw-r--r--browser/base/content/test/urlbar/browser_locationBarExternalLoad.js65
-rw-r--r--browser/base/content/test/urlbar/browser_moz_action_link.js31
-rw-r--r--browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js49
-rw-r--r--browser/base/content/test/urlbar/browser_search_favicon.js52
-rw-r--r--browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js216
-rw-r--r--browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar_perwindowpb.js84
-rw-r--r--browser/base/content/test/urlbar/browser_urlHighlight.js134
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js104
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js49
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarCopying.js232
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarDecode.js97
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarDelete.js39
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarEnter.js45
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarEnterAfterMouseOver.js69
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarFocusedCmdK.js17
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarHashChangeProxyState.js111
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarKeepStateAcrossTabSwitches.js49
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarOneOffs.js232
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarPrivateBrowsingWindowChange.js41
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarRaceWithTabs.js57
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarRevert.js37
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js198
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js66
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js254
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js216
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarStop.js30
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarTrimURLs.js98
-rw-r--r--browser/base/content/test/urlbar/browser_urlbarUpdateForDomainCompletion.js17
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_autoFill_backspaced.js146
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_blanking.js35
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_locationchange_urlbar_edit_dos.js41
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_remoteness_switch.js39
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_searchsettings.js30
-rw-r--r--browser/base/content/test/urlbar/browser_urlbar_stop_pending.js138
-rw-r--r--browser/base/content/test/urlbar/browser_wyciwyg_urlbarCopying.js31
-rw-r--r--browser/base/content/test/urlbar/dummy_page.html9
-rw-r--r--browser/base/content/test/urlbar/file_blank_but_not_blank.html2
-rw-r--r--browser/base/content/test/urlbar/file_urlbar_edit_dos.html23
-rw-r--r--browser/base/content/test/urlbar/head.js205
-rw-r--r--browser/base/content/test/urlbar/moz.pngbin580 -> 0 bytes
-rw-r--r--browser/base/content/test/urlbar/print_postdata.sjs22
-rw-r--r--browser/base/content/test/urlbar/redirect_bug623155.sjs16
-rw-r--r--browser/base/content/test/urlbar/searchSuggestionEngine.sjs9
-rw-r--r--browser/base/content/test/urlbar/searchSuggestionEngine.xml9
-rw-r--r--browser/base/content/test/urlbar/slow-page.sjs22
-rw-r--r--browser/base/content/test/urlbar/test_wyciwyg_copying.html13
-rw-r--r--browser/base/content/test/webrtc/.eslintrc.js7
-rw-r--r--browser/base/content/test/webrtc/browser.ini11
-rw-r--r--browser/base/content/test/webrtc/browser_devices_get_user_media.js554
-rw-r--r--browser/base/content/test/webrtc/browser_devices_get_user_media_anim.js109
-rw-r--r--browser/base/content/test/webrtc/browser_devices_get_user_media_in_frame.js266
-rw-r--r--browser/base/content/test/webrtc/browser_devices_get_user_media_tear_off_tab.js109
-rw-r--r--browser/base/content/test/webrtc/get_user_media.html55
-rw-r--r--browser/base/content/test/webrtc/get_user_media_content_script.js85
-rw-r--r--browser/base/content/test/webrtc/head.js453
-rw-r--r--browser/components/contextualidentity/test/browser/.eslintrc.js11
-rw-r--r--browser/components/contextualidentity/test/browser/browser.ini30
-rw-r--r--browser/components/contextualidentity/test/browser/browser_aboutURLs.js49
-rw-r--r--browser/components/contextualidentity/test/browser/browser_blobUrl.js78
-rw-r--r--browser/components/contextualidentity/test/browser/browser_broadcastchannel.js80
-rw-r--r--browser/components/contextualidentity/test/browser/browser_count_and_remove.js34
-rw-r--r--browser/components/contextualidentity/test/browser/browser_eme.js186
-rw-r--r--browser/components/contextualidentity/test/browser/browser_favicon.js140
-rw-r--r--browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js219
-rw-r--r--browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js86
-rw-r--r--browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js147
-rw-r--r--browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js352
-rw-r--r--browser/components/contextualidentity/test/browser/browser_imageCache.js59
-rw-r--r--browser/components/contextualidentity/test/browser/browser_middleClick.js41
-rw-r--r--browser/components/contextualidentity/test/browser/browser_newtabButton.js35
-rw-r--r--browser/components/contextualidentity/test/browser/browser_serviceworkers.js108
-rw-r--r--browser/components/contextualidentity/test/browser/browser_usercontext.js86
-rw-r--r--browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js134
-rw-r--r--browser/components/contextualidentity/test/browser/browser_windowName.js74
-rw-r--r--browser/components/contextualidentity/test/browser/browser_windowOpen.js41
-rw-r--r--browser/components/contextualidentity/test/browser/empty_file.html5
-rw-r--r--browser/components/contextualidentity/test/browser/favicon-normal32.pngbin344 -> 0 bytes
-rw-r--r--browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html23
-rw-r--r--browser/components/contextualidentity/test/browser/file_set_storages.html41
-rw-r--r--browser/components/contextualidentity/test/browser/serviceworker.html12
-rw-r--r--browser/components/contextualidentity/test/browser/worker.js1
-rw-r--r--browser/components/customizableui/test/.eslintrc.js7
-rw-r--r--browser/components/customizableui/test/browser.ini154
-rw-r--r--browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js107
-rw-r--r--browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js108
-rw-r--r--browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js71
-rw-r--r--browser/components/customizableui/test/browser_1042100_default_placements_update.js107
-rw-r--r--browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js25
-rw-r--r--browser/components/customizableui/test/browser_1087303_button_fullscreen.js46
-rw-r--r--browser/components/customizableui/test/browser_1087303_button_preferences.js50
-rw-r--r--browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js24
-rw-r--r--browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js31
-rw-r--r--browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js78
-rw-r--r--browser/components/customizableui/test/browser_873501_handle_specials.js79
-rw-r--r--browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js185
-rw-r--r--browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js61
-rw-r--r--browser/components/customizableui/test/browser_877006_missing_view.js41
-rw-r--r--browser/components/customizableui/test/browser_877178_unregisterArea.js50
-rw-r--r--browser/components/customizableui/test/browser_877447_skip_missing_ids.js25
-rw-r--r--browser/components/customizableui/test/browser_878452_drag_to_panel.js65
-rw-r--r--browser/components/customizableui/test/browser_880164_customization_context_menus.js414
-rw-r--r--browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js497
-rw-r--r--browser/components/customizableui/test/browser_884402_customize_from_overflow.js81
-rw-r--r--browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js45
-rw-r--r--browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js134
-rw-r--r--browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js46
-rw-r--r--browser/components/customizableui/test/browser_887438_currentset_shim.js75
-rw-r--r--browser/components/customizableui/test/browser_888817_currentset_updating.js57
-rw-r--r--browser/components/customizableui/test/browser_890140_orphaned_placeholders.js210
-rw-r--r--browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js68
-rw-r--r--browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js30
-rw-r--r--browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js24
-rw-r--r--browser/components/customizableui/test/browser_901207_searchbar_in_panel.js113
-rw-r--r--browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js31
-rw-r--r--browser/components/customizableui/test/browser_913972_currentset_overflow.js55
-rw-r--r--browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js131
-rw-r--r--browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js16
-rw-r--r--browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js38
-rw-r--r--browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js24
-rw-r--r--browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js26
-rw-r--r--browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js35
-rw-r--r--browser/components/customizableui/test/browser_934113_menubar_removable.js30
-rw-r--r--browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js89
-rw-r--r--browser/components/customizableui/test/browser_938980_navbar_collapsed.js121
-rw-r--r--browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js25
-rw-r--r--browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js70
-rw-r--r--browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js136
-rw-r--r--browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js22
-rw-r--r--browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js31
-rw-r--r--browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js106
-rw-r--r--browser/components/customizableui/test/browser_943683_migration_test.js50
-rw-r--r--browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js17
-rw-r--r--browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js35
-rw-r--r--browser/components/customizableui/test/browser_947914_button_addons.js33
-rw-r--r--browser/components/customizableui/test/browser_947914_button_copy.js59
-rw-r--r--browser/components/customizableui/test/browser_947914_button_cut.js57
-rw-r--r--browser/components/customizableui/test/browser_947914_button_find.js22
-rw-r--r--browser/components/customizableui/test/browser_947914_button_history.js24
-rw-r--r--browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js48
-rw-r--r--browser/components/customizableui/test/browser_947914_button_newWindow.js47
-rw-r--r--browser/components/customizableui/test/browser_947914_button_paste.js41
-rw-r--r--browser/components/customizableui/test/browser_947914_button_print.js45
-rw-r--r--browser/components/customizableui/test/browser_947914_button_savePage.js20
-rw-r--r--browser/components/customizableui/test/browser_947914_button_zoomIn.js37
-rw-r--r--browser/components/customizableui/test/browser_947914_button_zoomOut.js38
-rw-r--r--browser/components/customizableui/test/browser_947914_button_zoomReset.js40
-rw-r--r--browser/components/customizableui/test/browser_947987_removable_default.js68
-rw-r--r--browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js32
-rw-r--r--browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js52
-rw-r--r--browser/components/customizableui/test/browser_956602_remove_special_widget.js31
-rw-r--r--browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js54
-rw-r--r--browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js67
-rw-r--r--browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js34
-rw-r--r--browser/components/customizableui/test/browser_967000_button_charEncoding.js62
-rw-r--r--browser/components/customizableui/test/browser_967000_button_feeds.js60
-rw-r--r--browser/components/customizableui/test/browser_967000_button_sync.js335
-rw-r--r--browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js65
-rw-r--r--browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js56
-rw-r--r--browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js34
-rw-r--r--browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js26
-rw-r--r--browser/components/customizableui/test/browser_970511_undo_restore_default.js128
-rw-r--r--browser/components/customizableui/test/browser_972267_customizationchange_events.js46
-rwxr-xr-xbrowser/components/customizableui/test/browser_973641_button_addon.js71
-rw-r--r--browser/components/customizableui/test/browser_973932_addonbar_currentset.js30
-rw-r--r--browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js145
-rw-r--r--browser/components/customizableui/test/browser_976792_insertNodeInWindow.js414
-rw-r--r--browser/components/customizableui/test/browser_978084_dragEnd_after_move.js46
-rw-r--r--browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js51
-rw-r--r--browser/components/customizableui/test/browser_981305_separator_insertion.js73
-rw-r--r--browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js93
-rw-r--r--browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js57
-rw-r--r--browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js267
-rw-r--r--browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js45
-rw-r--r--browser/components/customizableui/test/browser_987177_destroyWidget_xul.js33
-rw-r--r--browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js74
-rwxr-xr-xbrowser/components/customizableui/test/browser_987185_syncButton.js77
-rw-r--r--browser/components/customizableui/test/browser_987492_window_api.js54
-rw-r--r--browser/components/customizableui/test/browser_987640_charEncoding.js60
-rw-r--r--browser/components/customizableui/test/browser_988072_sidebar_events.js392
-rw-r--r--browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js56
-rw-r--r--browser/components/customizableui/test/browser_989751_subviewbutton_class.js62
-rw-r--r--browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js26
-rw-r--r--browser/components/customizableui/test/browser_993322_widget_notoolbar.js36
-rw-r--r--browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js149
-rw-r--r--browser/components/customizableui/test/browser_996364_registerArea_different_properties.js112
-rw-r--r--browser/components/customizableui/test/browser_996635_remove_non_widgets.js43
-rw-r--r--browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js81
-rw-r--r--browser/components/customizableui/test/browser_check_tooltips_in_navbar.js14
-rw-r--r--browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js24
-rw-r--r--browser/components/customizableui/test/browser_panel_toggle.js43
-rw-r--r--browser/components/customizableui/test/browser_switch_to_customize_mode.js34
-rw-r--r--browser/components/customizableui/test/head.js499
-rw-r--r--browser/components/customizableui/test/support/feeds_test_page.html10
-rw-r--r--browser/components/customizableui/test/support/test-feed.xml23
-rw-r--r--browser/components/customizableui/test/support/test_967000_charEncoding_page.html11
-rw-r--r--browser/components/dirprovider/tests/unit/.eslintrc.js7
-rw-r--r--browser/components/downloads/test/browser/.eslintrc.js7
-rw-r--r--browser/components/downloads/test/browser/browser.ini15
-rw-r--r--browser/components/downloads/test/browser/browser_basic_functionality.js56
-rw-r--r--browser/components/downloads/test/browser/browser_confirm_unblock_download.js92
-rw-r--r--browser/components/downloads/test/browser/browser_downloads_panel_block.js183
-rw-r--r--browser/components/downloads/test/browser/browser_downloads_panel_footer.js95
-rw-r--r--browser/components/downloads/test/browser/browser_downloads_panel_height.js29
-rw-r--r--browser/components/downloads/test/browser/browser_first_download_panel.js57
-rw-r--r--browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js62
-rw-r--r--browser/components/downloads/test/browser/browser_indicatorDrop.js67
-rw-r--r--browser/components/downloads/test/browser/browser_libraryDrop.js72
-rw-r--r--browser/components/downloads/test/browser/browser_overflow_anchor.js115
-rw-r--r--browser/components/downloads/test/browser/head.js300
-rw-r--r--browser/components/downloads/test/unit/.eslintrc.js7
-rw-r--r--browser/components/downloads/test/unit/head.js18
-rw-r--r--browser/components/downloads/test/unit/test_DownloadsCommon.js37
-rw-r--r--browser/components/downloads/test/unit/xpcshell.ini7
-rw-r--r--browser/components/extensions/test/browser/.eslintrc.js36
-rw-r--r--browser/components/extensions/test/browser/browser.ini115
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_context.js398
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js68
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js321
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js210
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_popup.js413
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js304
-rw-r--r--browser/components/extensions/test/browser/browser_ext_browserAction_simple.js59
-rw-r--r--browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js113
-rw-r--r--browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js133
-rw-r--r--browser/components/extensions/test/browser/browser_ext_commands_getAll.js81
-rw-r--r--browser/components/extensions/test/browser/browser_ext_commands_onCommand.js229
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contentscript_connect.js67
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus.js342
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js96
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js76
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js196
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js100
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js84
-rw-r--r--browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js254
-rw-r--r--browser/components/extensions/test/browser/browser_ext_currentWindow.js149
-rw-r--r--browser/components/extensions/test/browser/browser_ext_getViews.js198
-rw-r--r--browser/components/extensions/test/browser/browser_ext_incognito_popup.js108
-rw-r--r--browser/components/extensions/test/browser/browser_ext_incognito_views.js121
-rw-r--r--browser/components/extensions/test/browser/browser_ext_lastError.js55
-rw-r--r--browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js173
-rw-r--r--browser/components/extensions/test/browser/browser_ext_omnibox.js286
-rw-r--r--browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js66
-rw-r--r--browser/components/extensions/test/browser/browser_ext_pageAction_context.js178
-rw-r--r--browser/components/extensions/test/browser/browser_ext_pageAction_popup.js238
-rw-r--r--browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js169
-rw-r--r--browser/components/extensions/test/browser/browser_ext_pageAction_simple.js60
-rw-r--r--browser/components/extensions/test/browser/browser_ext_pageAction_title.js226
-rw-r--r--browser/components/extensions/test/browser/browser_ext_popup_api_injection.js101
-rw-r--r--browser/components/extensions/test/browser/browser_ext_popup_background.js133
-rw-r--r--browser/components/extensions/test/browser/browser_ext_popup_corners.js98
-rw-r--r--browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js93
-rw-r--r--browser/components/extensions/test/browser/browser_ext_popup_shutdown.js77
-rw-r--r--browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js276
-rw-r--r--browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js101
-rw-r--r--browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js94
-rw-r--r--browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js97
-rw-r--r--browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js61
-rw-r--r--browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js96
-rw-r--r--browser/components/extensions/test/browser/browser_ext_sessions_restore.js134
-rw-r--r--browser/components/extensions/test/browser/browser_ext_simple.js57
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js74
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_audio.js203
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js155
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js156
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_create.js166
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js66
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js47
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js146
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_events.js280
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js234
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js217
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js189
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js67
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js107
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js70
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js86
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_move.js103
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_move_window.js98
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js43
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js42
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js126
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js198
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_query.js224
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_reload.js54
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js58
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js95
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js227
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_update.js45
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_update_url.js110
-rw-r--r--browser/components/extensions/test/browser/browser_ext_tabs_zoom.js222
-rw-r--r--browser/components/extensions/test/browser/browser_ext_topwindowid.js23
-rw-r--r--browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js45
-rw-r--r--browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js168
-rw-r--r--browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js251
-rw-r--r--browser/components/extensions/test/browser/browser_ext_webRequest.js95
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows.js33
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js61
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_create.js142
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_create_params.js33
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js140
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_create_url.js84
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_events.js115
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_size.js114
-rw-r--r--browser/components/extensions/test/browser/browser_ext_windows_update.js189
-rw-r--r--browser/components/extensions/test/browser/context.html23
-rw-r--r--browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html19
-rw-r--r--browser/components/extensions/test/browser/context_tabs_onUpdated_page.html18
-rw-r--r--browser/components/extensions/test/browser/ctxmenu-image.pngbin5401 -> 0 bytes
-rw-r--r--browser/components/extensions/test/browser/file_bypass_cache.sjs11
-rw-r--r--browser/components/extensions/test/browser/file_dummy.html9
-rw-r--r--browser/components/extensions/test/browser/file_iframe_document.html10
-rw-r--r--browser/components/extensions/test/browser/file_iframe_document.sjs41
-rw-r--r--browser/components/extensions/test/browser/file_language_fr_en.html14
-rw-r--r--browser/components/extensions/test/browser/file_language_ja.html10
-rw-r--r--browser/components/extensions/test/browser/file_language_tlh.html12
-rw-r--r--browser/components/extensions/test/browser/file_popup_api_injection_a.html10
-rw-r--r--browser/components/extensions/test/browser/file_popup_api_injection_b.html10
-rw-r--r--browser/components/extensions/test/browser/head.js263
-rw-r--r--browser/components/extensions/test/browser/head_pageAction.js157
-rw-r--r--browser/components/extensions/test/browser/head_sessions.js47
-rw-r--r--browser/components/extensions/test/browser/searchSuggestionEngine.sjs9
-rw-r--r--browser/components/extensions/test/browser/searchSuggestionEngine.xml9
-rw-r--r--browser/components/extensions/test/mochitest/mochitest.ini6
-rw-r--r--browser/components/extensions/test/mochitest/test_ext_all_apis.html75
-rw-r--r--browser/components/extensions/test/xpcshell/.eslintrc.js9
-rw-r--r--browser/components/extensions/test/xpcshell/head.js55
-rw-r--r--browser/components/extensions/test/xpcshell/test_ext_bookmarks.js601
-rw-r--r--browser/components/extensions/test/xpcshell/test_ext_history.js487
-rw-r--r--browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js24
-rw-r--r--browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js61
-rw-r--r--browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js57
-rw-r--r--browser/components/extensions/test/xpcshell/xpcshell.ini11
-rw-r--r--browser/components/feeds/test/.eslintrc.js7
-rw-r--r--browser/components/feeds/test/bug368464-data.xml18
-rw-r--r--browser/components/feeds/test/bug408328-data.xml63
-rw-r--r--browser/components/feeds/test/bug436801-data.xml44
-rw-r--r--browser/components/feeds/test/bug494328-data.xml24
-rw-r--r--browser/components/feeds/test/bug589543-data.xml23
-rw-r--r--browser/components/feeds/test/chrome/.eslintrc.js7
-rw-r--r--browser/components/feeds/test/chrome/chrome.ini10
-rw-r--r--browser/components/feeds/test/chrome/sample_feed.atom23
-rw-r--r--browser/components/feeds/test/chrome/test_423060.xul56
-rw-r--r--browser/components/feeds/test/chrome/test_bug368464.html32
-rw-r--r--browser/components/feeds/test/chrome/test_bug408328.html37
-rw-r--r--browser/components/feeds/test/chrome/test_maxSniffing.html37
-rw-r--r--browser/components/feeds/test/mochitest.ini14
-rw-r--r--browser/components/feeds/test/test_bug436801.html118
-rw-r--r--browser/components/feeds/test/test_bug494328.html36
-rw-r--r--browser/components/feeds/test/test_bug589543.html32
-rw-r--r--browser/components/feeds/test/test_registerHandler.html85
-rw-r--r--browser/components/feeds/test/unit/.eslintrc.js7
-rw-r--r--browser/components/feeds/test/unit/head_feeds.js5
-rw-r--r--browser/components/feeds/test/unit/test_355473.js43
-rw-r--r--browser/components/feeds/test/unit/test_758990.js42
-rw-r--r--browser/components/feeds/test/unit/xpcshell.ini8
-rw-r--r--browser/components/feeds/test/valid-feed.xml23
-rw-r--r--browser/components/feeds/test/valid-unsniffable-feed.xml32
-rw-r--r--browser/components/migration/tests/browser/.eslintrc.js9
-rw-r--r--browser/components/migration/tests/browser/browser.ini3
-rw-r--r--browser/components/migration/tests/browser/browser_undo_notification.js67
-rw-r--r--browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js122
-rw-r--r--browser/components/migration/tests/browser/browser_undo_notification_wording.js67
-rw-r--r--browser/components/migration/tests/marionette/manifest.ini5
-rw-r--r--browser/components/migration/tests/marionette/test_refresh_firefox.py416
-rw-r--r--browser/components/migration/tests/unit/.eslintrc.js7
-rw-r--r--browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Databin22528 -> 0 bytes
-rw-r--r--browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookiesbin10240 -> 0 bytes
-rw-r--r--browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State22
-rw-r--r--browser/components/migration/tests/unit/Library/Safari/Bookmarks.plistbin1860 -> 0 bytes
-rw-r--r--browser/components/migration/tests/unit/head_migration.js69
-rw-r--r--browser/components/migration/tests/unit/test_Chrome_cookies.js51
-rw-r--r--browser/components/migration/tests/unit/test_Chrome_passwords.js219
-rw-r--r--browser/components/migration/tests/unit/test_Edge_availability.js20
-rw-r--r--browser/components/migration/tests/unit/test_Edge_db_migration.js471
-rw-r--r--browser/components/migration/tests/unit/test_IE7_passwords.js397
-rw-r--r--browser/components/migration/tests/unit/test_IE_bookmarks.js44
-rw-r--r--browser/components/migration/tests/unit/test_IE_cookies.js111
-rw-r--r--browser/components/migration/tests/unit/test_Safari_bookmarks.js46
-rw-r--r--browser/components/migration/tests/unit/test_automigration.js695
-rw-r--r--browser/components/migration/tests/unit/test_fx_telemetry.js288
-rw-r--r--browser/components/migration/tests/unit/xpcshell.ini26
-rw-r--r--browser/components/newtab/tests/browser/.eslintrc.js7
-rw-r--r--browser/components/newtab/tests/browser/blue_page.html9
-rw-r--r--browser/components/newtab/tests/browser/browser.ini16
-rw-r--r--browser/components/newtab/tests/browser/browser_PreviewProvider.js90
-rw-r--r--browser/components/newtab/tests/browser/browser_newtab_overrides.js139
-rw-r--r--browser/components/newtab/tests/browser/browser_newtabmessages.js222
-rw-r--r--browser/components/newtab/tests/browser/browser_newtabwebchannel.js251
-rw-r--r--browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js52
-rw-r--r--browser/components/newtab/tests/browser/dummy_page.html10
-rw-r--r--browser/components/newtab/tests/browser/newtabmessages_places.html49
-rw-r--r--browser/components/newtab/tests/browser/newtabmessages_prefs.html32
-rw-r--r--browser/components/newtab/tests/browser/newtabmessages_preview.html37
-rw-r--r--browser/components/newtab/tests/browser/newtabmessages_search.html113
-rw-r--r--browser/components/newtab/tests/browser/newtabwebchannel_basic.html36
-rw-r--r--browser/components/newtab/tests/xpcshell/.eslintrc.js7
-rw-r--r--browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js236
-rw-r--r--browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js50
-rw-r--r--browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js82
-rw-r--r--browser/components/newtab/tests/xpcshell/test_NewTabURL.js52
-rw-r--r--browser/components/newtab/tests/xpcshell/test_PlacesProvider.js358
-rw-r--r--browser/components/newtab/tests/xpcshell/xpcshell.ini11
-rw-r--r--browser/components/originattributes/moz.build16
-rw-r--r--browser/components/originattributes/test/browser/.eslintrc.js7
-rw-r--r--browser/components/originattributes/test/browser/browser.ini64
-rw-r--r--browser/components/originattributes/test/browser/browser_blobURLIsolation.js97
-rw-r--r--browser/components/originattributes/test/browser/browser_broadcastChannel.js47
-rw-r--r--browser/components/originattributes/test/browser/browser_cache.js259
-rw-r--r--browser/components/originattributes/test/browser/browser_clientAuth.js44
-rw-r--r--browser/components/originattributes/test/browser/browser_cookieIsolation.js31
-rw-r--r--browser/components/originattributes/test/browser/browser_favicon_firstParty.js343
-rw-r--r--browser/components/originattributes/test/browser/browser_favicon_userContextId.js257
-rw-r--r--browser/components/originattributes/test/browser/browser_firstPartyIsolation.js174
-rw-r--r--browser/components/originattributes/test/browser/browser_httpauth.js54
-rw-r--r--browser/components/originattributes/test/browser/browser_imageCacheIsolation.js80
-rw-r--r--browser/components/originattributes/test/browser/browser_localStorageIsolation.js24
-rw-r--r--browser/components/originattributes/test/browser/browser_sharedworker.js26
-rw-r--r--browser/components/originattributes/test/browser/dummy.html9
-rw-r--r--browser/components/originattributes/test/browser/file_broadcastChannel.html16
-rw-r--r--browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html15
-rw-r--r--browser/components/originattributes/test/browser/file_cache.html25
-rw-r--r--browser/components/originattributes/test/browser/file_favicon.html11
-rw-r--r--browser/components/originattributes/test/browser/file_favicon.pngbin344 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_favicon.png^headers^1
-rw-r--r--browser/components/originattributes/test/browser/file_favicon_cache.html11
-rw-r--r--browser/components/originattributes/test/browser/file_favicon_cache.pngbin344 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_favicon_thirdParty.html11
-rw-r--r--browser/components/originattributes/test/browser/file_firstPartyBasic.html8
-rw-r--r--browser/components/originattributes/test/browser/file_sharedworker.html10
-rw-r--r--browser/components/originattributes/test/browser/file_sharedworker.js9
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.audio.oggbin2603 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.embed.pngbin95 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html8
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html18
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.img.pngbin95 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.import.js1
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.link.css1
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.object.pngbin95 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.request.html8
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.script.js1
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js1
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt13
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogvbin16049 -> 0 bytes
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html8
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js9
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html8
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html8
-rw-r--r--browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html8
-rw-r--r--browser/components/originattributes/test/browser/head.js365
-rw-r--r--browser/components/originattributes/test/browser/test.html20
-rw-r--r--browser/components/originattributes/test/browser/test.js1
-rw-r--r--browser/components/originattributes/test/browser/test.js^headers^1
-rw-r--r--browser/components/originattributes/test/browser/test2.html12
-rw-r--r--browser/components/originattributes/test/browser/test2.js1
-rw-r--r--browser/components/originattributes/test/browser/test2.js^headers^1
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty.html15
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_cookie.html13
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_html_redirect.html9
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_http_redirect.html9
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^2
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html13
-rw-r--r--browser/components/originattributes/test/browser/test_firstParty_postMessage.html28
-rw-r--r--browser/components/originattributes/test/browser/window.html13
-rw-r--r--browser/components/originattributes/test/browser/worker_blobify.js11
-rw-r--r--browser/components/originattributes/test/browser/worker_deblobify.js31
-rw-r--r--browser/components/originattributes/test/mochitest/file_empty.html2
-rw-r--r--browser/components/originattributes/test/mochitest/mochitest.ini5
-rw-r--r--browser/components/originattributes/test/mochitest/test_permissions_api.html207
-rw-r--r--browser/components/places/tests/browser/.eslintrc.js7
-rw-r--r--browser/components/places/tests/browser/bookmark_dummy_1.html9
-rw-r--r--browser/components/places/tests/browser/bookmark_dummy_2.html9
-rw-r--r--browser/components/places/tests/browser/browser.ini58
-rw-r--r--browser/components/places/tests/browser/browser_0_library_left_pane_migration.js90
-rw-r--r--browser/components/places/tests/browser/browser_410196_paste_into_tags.js114
-rw-r--r--browser/components/places/tests/browser/browser_416459_cut.js83
-rw-r--r--browser/components/places/tests/browser/browser_423515.js173
-rw-r--r--browser/components/places/tests/browser/browser_425884.js127
-rw-r--r--browser/components/places/tests/browser/browser_435851_copy_query.js59
-rw-r--r--browser/components/places/tests/browser/browser_475045.js65
-rw-r--r--browser/components/places/tests/browser/browser_555547.js66
-rw-r--r--browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js53
-rw-r--r--browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js110
-rw-r--r--browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js39
-rw-r--r--browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js71
-rw-r--r--browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js42
-rw-r--r--browser/components/places/tests/browser/browser_bookmark_all_tabs.js37
-rw-r--r--browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js61
-rw-r--r--browser/components/places/tests/browser/browser_bookmarksProperties.js450
-rw-r--r--browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js256
-rw-r--r--browser/components/places/tests/browser/browser_forgetthissite_single.js78
-rw-r--r--browser/components/places/tests/browser/browser_history_sidebar_search.js64
-rw-r--r--browser/components/places/tests/browser/browser_library_batch_delete.js114
-rw-r--r--browser/components/places/tests/browser/browser_library_commands.js235
-rw-r--r--browser/components/places/tests/browser/browser_library_downloads.js70
-rw-r--r--browser/components/places/tests/browser/browser_library_infoBox.js197
-rw-r--r--browser/components/places/tests/browser/browser_library_left_pane_fixnames.js94
-rw-r--r--browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js41
-rw-r--r--browser/components/places/tests/browser/browser_library_middleclick.js279
-rw-r--r--browser/components/places/tests/browser/browser_library_openFlatContainer.js42
-rw-r--r--browser/components/places/tests/browser/browser_library_open_leak.js23
-rw-r--r--browser/components/places/tests/browser/browser_library_panel_leak.js54
-rw-r--r--browser/components/places/tests/browser/browser_library_search.js182
-rw-r--r--browser/components/places/tests/browser/browser_library_views_liveupdate.js300
-rw-r--r--browser/components/places/tests/browser/browser_markPageAsFollowedLink.js68
-rw-r--r--browser/components/places/tests/browser/browser_sidebarpanels_click.js157
-rw-r--r--browser/components/places/tests/browser/browser_sort_in_library.js249
-rw-r--r--browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js53
-rw-r--r--browser/components/places/tests/browser/browser_views_liveupdate.js475
-rw-r--r--browser/components/places/tests/browser/frameLeft.html8
-rw-r--r--browser/components/places/tests/browser/frameRight.html8
-rw-r--r--browser/components/places/tests/browser/framedPage.html9
-rw-r--r--browser/components/places/tests/browser/head.js460
-rw-r--r--browser/components/places/tests/browser/keyword_form.html17
-rw-r--r--browser/components/places/tests/browser/pageopeningwindow.html9
-rw-r--r--browser/components/places/tests/browser/sidebarpanels_click_test_page.html7
-rw-r--r--browser/components/places/tests/chrome/.eslintrc.js7
-rw-r--r--browser/components/places/tests/chrome/chrome.ini15
-rw-r--r--browser/components/places/tests/chrome/head.js7
-rw-r--r--browser/components/places/tests/chrome/test_0_bug510634.xul99
-rw-r--r--browser/components/places/tests/chrome/test_0_multiple_left_pane.xul85
-rw-r--r--browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul89
-rw-r--r--browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul91
-rw-r--r--browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul83
-rw-r--r--browser/components/places/tests/chrome/test_bug549192.xul120
-rw-r--r--browser/components/places/tests/chrome/test_bug549491.xul78
-rw-r--r--browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul170
-rw-r--r--browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul99
-rw-r--r--browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul204
-rw-r--r--browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul86
-rw-r--r--browser/components/places/tests/chrome/test_treeview_date.xul159
-rw-r--r--browser/components/places/tests/unit/.eslintrc.js7
-rw-r--r--browser/components/places/tests/unit/bookmarks.glue.html16
-rw-r--r--browser/components/places/tests/unit/bookmarks.glue.json1
-rw-r--r--browser/components/places/tests/unit/corruptDB.sqlitebin32772 -> 0 bytes
-rw-r--r--browser/components/places/tests/unit/distribution.ini27
-rw-r--r--browser/components/places/tests/unit/head_bookmarks.js133
-rw-r--r--browser/components/places/tests/unit/test_421483.js103
-rw-r--r--browser/components/places/tests/unit/test_PUIU_makeTransaction.js361
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js33
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_corrupt.js59
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js52
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js55
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_distribution.js125
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_migrate.js70
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_prefs.js240
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_restore.js62
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js285
-rw-r--r--browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js150
-rw-r--r--browser/components/places/tests/unit/test_clearHistory_shutdown.js181
-rw-r--r--browser/components/places/tests/unit/test_leftpane_corruption_handling.js174
-rw-r--r--browser/components/places/tests/unit/xpcshell.ini25
-rw-r--r--browser/components/preferences/in-content/tests/.eslintrc.js7
-rw-r--r--browser/components/preferences/in-content/tests/browser.ini43
-rw-r--r--browser/components/preferences/in-content/tests/browser_advanced_update.js158
-rw-r--r--browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js76
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js24
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js43
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js92
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul33
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug410900.js46
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug705422.js144
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug731866.js52
-rw-r--r--browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js52
-rw-r--r--browser/components/preferences/in-content/tests/browser_change_app_handler.js98
-rw-r--r--browser/components/preferences/in-content/tests/browser_connection.js99
-rw-r--r--browser/components/preferences/in-content/tests/browser_connection_bug388287.js125
-rw-r--r--browser/components/preferences/in-content/tests/browser_cookies_exceptions.js348
-rw-r--r--browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js103
-rw-r--r--browser/components/preferences/in-content/tests/browser_healthreport.js62
-rw-r--r--browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js20
-rw-r--r--browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js44
-rw-r--r--browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js45
-rw-r--r--browser/components/preferences/in-content/tests/browser_privacypane_1.js18
-rw-r--r--browser/components/preferences/in-content/tests/browser_privacypane_3.js17
-rw-r--r--browser/components/preferences/in-content/tests/browser_privacypane_4.js25
-rw-r--r--browser/components/preferences/in-content/tests/browser_privacypane_5.js17
-rw-r--r--browser/components/preferences/in-content/tests/browser_privacypane_8.js26
-rw-r--r--browser/components/preferences/in-content/tests/browser_proxy_backup.js65
-rw-r--r--browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js37
-rw-r--r--browser/components/preferences/in-content/tests/browser_searchsuggestions.js43
-rw-r--r--browser/components/preferences/in-content/tests/browser_security.js130
-rw-r--r--browser/components/preferences/in-content/tests/browser_subdialogs.js293
-rw-r--r--browser/components/preferences/in-content/tests/browser_telemetry.js52
-rw-r--r--browser/components/preferences/in-content/tests/head.js165
-rw-r--r--browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js330
-rw-r--r--browser/components/preferences/in-content/tests/subdialog.xul27
-rw-r--r--browser/components/preferences/in-content/tests/subdialog2.xul27
-rw-r--r--browser/components/privatebrowsing/test/browser/.eslintrc.js7
-rw-r--r--browser/components/privatebrowsing/test/browser/browser.ini54
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js282
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js115
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js24
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js23
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js45
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js138
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js53
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js88
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html33
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js60
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js42
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js93
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js95
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js105
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js293
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js54
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html13
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js49
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js25
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js36
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html11
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html10
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html10
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html10
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js61
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js23
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js19
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js133
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html8
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js72
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js95
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js70
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js47
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html13
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js92
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js38
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js82
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js43
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js77
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html9
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js37
-rw-r--r--browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js64
-rw-r--r--browser/components/privatebrowsing/test/browser/empty_file.html1
-rw-r--r--browser/components/privatebrowsing/test/browser/file_favicon.html11
-rw-r--r--browser/components/privatebrowsing/test/browser/file_favicon.pngbin344 -> 0 bytes
-rw-r--r--browser/components/privatebrowsing/test/browser/file_favicon.png^headers^1
-rw-r--r--browser/components/privatebrowsing/test/browser/head.js63
-rw-r--r--browser/components/privatebrowsing/test/browser/popup.html12
-rw-r--r--browser/components/privatebrowsing/test/browser/title.sjs22
-rw-r--r--browser/components/safebrowsing/content/test/.eslintrc.js7
-rw-r--r--browser/components/safebrowsing/content/test/browser.ini8
-rw-r--r--browser/components/safebrowsing/content/test/browser_bug400731.js58
-rw-r--r--browser/components/safebrowsing/content/test/browser_bug415846.js86
-rw-r--r--browser/components/safebrowsing/content/test/browser_whitelisted.js41
-rw-r--r--browser/components/safebrowsing/content/test/head.js55
-rw-r--r--browser/components/search/test/.eslintrc.js7
-rw-r--r--browser/components/search/test/426329.xml11
-rw-r--r--browser/components/search/test/483086-1.xml10
-rw-r--r--browser/components/search/test/483086-2.xml10
-rw-r--r--browser/components/search/test/browser.ini44
-rw-r--r--browser/components/search/test/browser_426329.js250
-rw-r--r--browser/components/search/test/browser_483086.js49
-rw-r--r--browser/components/search/test/browser_aboutSearchReset.js159
-rw-r--r--browser/components/search/test/browser_abouthome_behavior.js144
-rw-r--r--browser/components/search/test/browser_addEngine.js105
-rw-r--r--browser/components/search/test/browser_amazon.js82
-rw-r--r--browser/components/search/test/browser_amazon_behavior.js166
-rw-r--r--browser/components/search/test/browser_bing.js118
-rw-r--r--browser/components/search/test/browser_bing_behavior.js166
-rw-r--r--browser/components/search/test/browser_contextSearchTabPosition.js62
-rw-r--r--browser/components/search/test/browser_contextmenu.js101
-rw-r--r--browser/components/search/test/browser_google.js100
-rw-r--r--browser/components/search/test/browser_google_behavior.js165
-rw-r--r--browser/components/search/test/browser_google_codes.js161
-rw-r--r--browser/components/search/test/browser_healthreport.js82
-rw-r--r--browser/components/search/test/browser_hiddenOneOffs_cleanup.js99
-rw-r--r--browser/components/search/test/browser_hiddenOneOffs_diacritics.js59
-rw-r--r--browser/components/search/test/browser_oneOffContextMenu.js105
-rw-r--r--browser/components/search/test/browser_oneOffContextMenu_setDefault.js195
-rw-r--r--browser/components/search/test/browser_oneOffHeader.js142
-rw-r--r--browser/components/search/test/browser_private_search_perwindowpb.js76
-rw-r--r--browser/components/search/test/browser_searchbar_keyboard_navigation.js425
-rw-r--r--browser/components/search/test/browser_searchbar_openpopup.js521
-rw-r--r--browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js354
-rw-r--r--browser/components/search/test/browser_webapi.js92
-rw-r--r--browser/components/search/test/browser_yahoo.js132
-rw-r--r--browser/components/search/test/browser_yahoo_behavior.js166
-rw-r--r--browser/components/search/test/head.js156
-rw-r--r--browser/components/search/test/opensearch.html9
-rw-r--r--browser/components/search/test/test.html8
-rw-r--r--browser/components/search/test/testEngine.xml12
-rw-r--r--browser/components/search/test/testEngine_diacritics.xml12
-rw-r--r--browser/components/search/test/testEngine_dupe.xml12
-rw-r--r--browser/components/search/test/testEngine_mozsearch.xml14
-rw-r--r--browser/components/search/test/webapi.html16
-rw-r--r--browser/components/selfsupport/test/.eslintrc.js7
-rw-r--r--browser/components/selfsupport/test/browser.ini3
-rw-r--r--browser/components/selfsupport/test/browser_selfsupportAPI.js88
-rw-r--r--browser/components/sessionstore/test/.eslintrc.js7
-rw-r--r--browser/components/sessionstore/test/browser.ini242
-rw-r--r--browser/components/sessionstore/test/browser_1234021.js18
-rw-r--r--browser/components/sessionstore/test/browser_1234021_page.html6
-rw-r--r--browser/components/sessionstore/test/browser_248970_b_perwindowpb.js166
-rw-r--r--browser/components/sessionstore/test/browser_248970_b_sample.html37
-rw-r--r--browser/components/sessionstore/test/browser_339445.js32
-rw-r--r--browser/components/sessionstore/test/browser_339445_sample.html18
-rw-r--r--browser/components/sessionstore/test/browser_345898.js44
-rw-r--r--browser/components/sessionstore/test/browser_350525.js102
-rw-r--r--browser/components/sessionstore/test/browser_354894_perwindowpb.js474
-rw-r--r--browser/components/sessionstore/test/browser_367052.js41
-rw-r--r--browser/components/sessionstore/test/browser_393716.js71
-rw-r--r--browser/components/sessionstore/test/browser_394759_basic.js92
-rw-r--r--browser/components/sessionstore/test/browser_394759_behavior.js76
-rw-r--r--browser/components/sessionstore/test/browser_394759_perwindowpb.js55
-rw-r--r--browser/components/sessionstore/test/browser_394759_purge.js130
-rw-r--r--browser/components/sessionstore/test/browser_423132.js59
-rw-r--r--browser/components/sessionstore/test/browser_423132_sample.html14
-rw-r--r--browser/components/sessionstore/test/browser_447951.js65
-rw-r--r--browser/components/sessionstore/test/browser_447951_sample.html5
-rw-r--r--browser/components/sessionstore/test/browser_454908.js47
-rw-r--r--browser/components/sessionstore/test/browser_454908_sample.html8
-rw-r--r--browser/components/sessionstore/test/browser_456342.js49
-rw-r--r--browser/components/sessionstore/test/browser_456342_sample.xhtml36
-rw-r--r--browser/components/sessionstore/test/browser_459906.js62
-rw-r--r--browser/components/sessionstore/test/browser_459906_empty.html3
-rw-r--r--browser/components/sessionstore/test/browser_459906_sample.html41
-rw-r--r--browser/components/sessionstore/test/browser_461634.js85
-rw-r--r--browser/components/sessionstore/test/browser_461743.js39
-rw-r--r--browser/components/sessionstore/test/browser_461743_sample.html56
-rw-r--r--browser/components/sessionstore/test/browser_463205.js40
-rw-r--r--browser/components/sessionstore/test/browser_463205_sample.html7
-rw-r--r--browser/components/sessionstore/test/browser_463206.js53
-rw-r--r--browser/components/sessionstore/test/browser_463206_sample.html11
-rw-r--r--browser/components/sessionstore/test/browser_464199.js85
-rw-r--r--browser/components/sessionstore/test/browser_464620_a.html54
-rw-r--r--browser/components/sessionstore/test/browser_464620_a.js48
-rw-r--r--browser/components/sessionstore/test/browser_464620_b.html58
-rw-r--r--browser/components/sessionstore/test/browser_464620_b.js48
-rw-r--r--browser/components/sessionstore/test/browser_464620_xd.html5
-rw-r--r--browser/components/sessionstore/test/browser_465215.js28
-rw-r--r--browser/components/sessionstore/test/browser_465223.js45
-rw-r--r--browser/components/sessionstore/test/browser_466937.js42
-rw-r--r--browser/components/sessionstore/test/browser_466937_sample.html22
-rw-r--r--browser/components/sessionstore/test/browser_467409-backslashplosion.js74
-rw-r--r--browser/components/sessionstore/test/browser_477657.js60
-rw-r--r--browser/components/sessionstore/test/browser_480893.js47
-rw-r--r--browser/components/sessionstore/test/browser_485482.js37
-rw-r--r--browser/components/sessionstore/test/browser_485482_sample.html12
-rw-r--r--browser/components/sessionstore/test/browser_485563.js26
-rw-r--r--browser/components/sessionstore/test/browser_490040.js65
-rw-r--r--browser/components/sessionstore/test/browser_491168.js42
-rw-r--r--browser/components/sessionstore/test/browser_491577.js120
-rw-r--r--browser/components/sessionstore/test/browser_495495.js46
-rw-r--r--browser/components/sessionstore/test/browser_500328.js120
-rw-r--r--browser/components/sessionstore/test/browser_506482.js73
-rw-r--r--browser/components/sessionstore/test/browser_514751.js38
-rw-r--r--browser/components/sessionstore/test/browser_522375.js21
-rw-r--r--browser/components/sessionstore/test/browser_522545.js269
-rw-r--r--browser/components/sessionstore/test/browser_524745.js42
-rw-r--r--browser/components/sessionstore/test/browser_526613.js72
-rw-r--r--browser/components/sessionstore/test/browser_528776.js21
-rw-r--r--browser/components/sessionstore/test/browser_579868.js30
-rw-r--r--browser/components/sessionstore/test/browser_579879.js20
-rw-r--r--browser/components/sessionstore/test/browser_580512.js81
-rw-r--r--browser/components/sessionstore/test/browser_581937.js19
-rw-r--r--browser/components/sessionstore/test/browser_586068-apptabs.js58
-rw-r--r--browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js53
-rw-r--r--browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js113
-rw-r--r--browser/components/sessionstore/test/browser_586068-cascade.js54
-rw-r--r--browser/components/sessionstore/test/browser_586068-multi_window.js70
-rw-r--r--browser/components/sessionstore/test/browser_586068-reload.js54
-rw-r--r--browser/components/sessionstore/test/browser_586068-select.js69
-rw-r--r--browser/components/sessionstore/test/browser_586068-window_state.js59
-rw-r--r--browser/components/sessionstore/test/browser_586068-window_state_override.js59
-rw-r--r--browser/components/sessionstore/test/browser_586147.js52
-rw-r--r--browser/components/sessionstore/test/browser_588426.js41
-rw-r--r--browser/components/sessionstore/test/browser_589246.js242
-rw-r--r--browser/components/sessionstore/test/browser_590268.js137
-rw-r--r--browser/components/sessionstore/test/browser_590563.js74
-rw-r--r--browser/components/sessionstore/test/browser_595601-restore_hidden.js112
-rw-r--r--browser/components/sessionstore/test/browser_597071.js36
-rw-r--r--browser/components/sessionstore/test/browser_599909.js120
-rw-r--r--browser/components/sessionstore/test/browser_600545.js89
-rw-r--r--browser/components/sessionstore/test/browser_601955.js54
-rw-r--r--browser/components/sessionstore/test/browser_607016.js98
-rw-r--r--browser/components/sessionstore/test/browser_615394-SSWindowState_events.js361
-rw-r--r--browser/components/sessionstore/test/browser_618151.js65
-rw-r--r--browser/components/sessionstore/test/browser_623779.js13
-rw-r--r--browser/components/sessionstore/test/browser_624727.js35
-rw-r--r--browser/components/sessionstore/test/browser_625016.js82
-rw-r--r--browser/components/sessionstore/test/browser_628270.js52
-rw-r--r--browser/components/sessionstore/test/browser_635418.js55
-rw-r--r--browser/components/sessionstore/test/browser_636279.js101
-rw-r--r--browser/components/sessionstore/test/browser_637020.js66
-rw-r--r--browser/components/sessionstore/test/browser_637020_slow.sjs21
-rw-r--r--browser/components/sessionstore/test/browser_644409-scratchpads.js68
-rw-r--r--browser/components/sessionstore/test/browser_645428.js22
-rw-r--r--browser/components/sessionstore/test/browser_659591.js33
-rw-r--r--browser/components/sessionstore/test/browser_662743.js110
-rw-r--r--browser/components/sessionstore/test/browser_662743_sample.html15
-rw-r--r--browser/components/sessionstore/test/browser_662812.js36
-rw-r--r--browser/components/sessionstore/test/browser_665702-state_session.js24
-rw-r--r--browser/components/sessionstore/test/browser_682507.js16
-rw-r--r--browser/components/sessionstore/test/browser_687710.js44
-rw-r--r--browser/components/sessionstore/test/browser_687710_2.js64
-rw-r--r--browser/components/sessionstore/test/browser_694378.js33
-rw-r--r--browser/components/sessionstore/test/browser_701377.js41
-rw-r--r--browser/components/sessionstore/test/browser_705597.js58
-rw-r--r--browser/components/sessionstore/test/browser_707862.js61
-rw-r--r--browser/components/sessionstore/test/browser_739531.js47
-rw-r--r--browser/components/sessionstore/test/browser_739531_sample.html25
-rw-r--r--browser/components/sessionstore/test/browser_739805.js41
-rw-r--r--browser/components/sessionstore/test/browser_819510_perwindowpb.js120
-rw-r--r--browser/components/sessionstore/test/browser_911547.js63
-rw-r--r--browser/components/sessionstore/test/browser_911547_sample.html19
-rw-r--r--browser/components/sessionstore/test/browser_911547_sample.html^headers^1
-rw-r--r--browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js21
-rw-r--r--browser/components/sessionstore/test/browser_aboutSessionRestore.js55
-rw-r--r--browser/components/sessionstore/test/browser_async_duplicate_tab.js78
-rw-r--r--browser/components/sessionstore/test/browser_async_flushes.js113
-rw-r--r--browser/components/sessionstore/test/browser_async_remove_tab.js242
-rw-r--r--browser/components/sessionstore/test/browser_async_window_flushing.js178
-rw-r--r--browser/components/sessionstore/test/browser_attributes.js73
-rw-r--r--browser/components/sessionstore/test/browser_background_tab_crash.js221
-rw-r--r--browser/components/sessionstore/test/browser_backup_recovery.js206
-rw-r--r--browser/components/sessionstore/test/browser_broadcast.js131
-rw-r--r--browser/components/sessionstore/test/browser_capabilities.js76
-rw-r--r--browser/components/sessionstore/test/browser_cleaner.js157
-rw-r--r--browser/components/sessionstore/test/browser_cookies.js173
-rw-r--r--browser/components/sessionstore/test/browser_cookies.sjs21
-rw-r--r--browser/components/sessionstore/test/browser_crashedTabs.js462
-rw-r--r--browser/components/sessionstore/test/browser_dying_cache.js66
-rw-r--r--browser/components/sessionstore/test/browser_dynamic_frames.js87
-rw-r--r--browser/components/sessionstore/test/browser_forget_async_closings.js144
-rw-r--r--browser/components/sessionstore/test/browser_form_restore_events.js63
-rw-r--r--browser/components/sessionstore/test/browser_form_restore_events_sample.html99
-rw-r--r--browser/components/sessionstore/test/browser_formdata.js194
-rw-r--r--browser/components/sessionstore/test/browser_formdata_cc.js79
-rw-r--r--browser/components/sessionstore/test/browser_formdata_format.js113
-rw-r--r--browser/components/sessionstore/test/browser_formdata_format_sample.html7
-rw-r--r--browser/components/sessionstore/test/browser_formdata_sample.html20
-rw-r--r--browser/components/sessionstore/test/browser_formdata_xpath.js151
-rw-r--r--browser/components/sessionstore/test/browser_formdata_xpath_sample.html37
-rw-r--r--browser/components/sessionstore/test/browser_frame_history.js170
-rwxr-xr-xbrowser/components/sessionstore/test/browser_frame_history_a.html5
-rwxr-xr-xbrowser/components/sessionstore/test/browser_frame_history_b.html10
-rwxr-xr-xbrowser/components/sessionstore/test/browser_frame_history_c.html5
-rwxr-xr-xbrowser/components/sessionstore/test/browser_frame_history_c1.html5
-rwxr-xr-xbrowser/components/sessionstore/test/browser_frame_history_c2.html5
-rw-r--r--browser/components/sessionstore/test/browser_frame_history_index.html10
-rw-r--r--browser/components/sessionstore/test/browser_frame_history_index2.html4
-rw-r--r--browser/components/sessionstore/test/browser_frame_history_index_blank.html5
-rw-r--r--browser/components/sessionstore/test/browser_frametree.js131
-rw-r--r--browser/components/sessionstore/test/browser_frametree_sample.html8
-rw-r--r--browser/components/sessionstore/test/browser_frametree_sample_frameset.html11
-rw-r--r--browser/components/sessionstore/test/browser_global_store.js45
-rw-r--r--browser/components/sessionstore/test/browser_history_persist.js93
-rw-r--r--browser/components/sessionstore/test/browser_label_and_icon.js53
-rw-r--r--browser/components/sessionstore/test/browser_merge_closed_tabs.js71
-rw-r--r--browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js36
-rw-r--r--browser/components/sessionstore/test/browser_newtab_userTypedValue.js72
-rw-r--r--browser/components/sessionstore/test/browser_pageStyle.js89
-rw-r--r--browser/components/sessionstore/test/browser_pageStyle_sample.html16
-rw-r--r--browser/components/sessionstore/test/browser_pageStyle_sample_nested.html9
-rw-r--r--browser/components/sessionstore/test/browser_page_title.js45
-rw-r--r--browser/components/sessionstore/test/browser_parentProcessRestoreHash.js95
-rw-r--r--browser/components/sessionstore/test/browser_pending_tabs.js35
-rw-r--r--browser/components/sessionstore/test/browser_privatetabs.js133
-rw-r--r--browser/components/sessionstore/test/browser_purge_shistory.js59
-rw-r--r--browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js342
-rw-r--r--browser/components/sessionstore/test/browser_replace_load.js52
-rw-r--r--browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js171
-rw-r--r--browser/components/sessionstore/test/browser_restore_redirect.js69
-rw-r--r--browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js56
-rw-r--r--browser/components/sessionstore/test/browser_scrollPositions.js153
-rw-r--r--browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js67
-rw-r--r--browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html26
-rw-r--r--browser/components/sessionstore/test/browser_scrollPositions_sample.html8
-rw-r--r--browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html11
-rw-r--r--browser/components/sessionstore/test/browser_send_async_message_oom.js75
-rw-r--r--browser/components/sessionstore/test/browser_sessionHistory.js240
-rw-r--r--browser/components/sessionstore/test/browser_sessionHistory_slow.sjs21
-rw-r--r--browser/components/sessionstore/test/browser_sessionStorage.html27
-rw-r--r--browser/components/sessionstore/test/browser_sessionStorage.js188
-rw-r--r--browser/components/sessionstore/test/browser_sessionStorage_size.js51
-rw-r--r--browser/components/sessionstore/test/browser_sessionStoreContainer.js141
-rw-r--r--browser/components/sessionstore/test/browser_swapDocShells.js35
-rw-r--r--browser/components/sessionstore/test/browser_switch_remoteness.js49
-rw-r--r--browser/components/sessionstore/test/browser_undoCloseById.js118
-rw-r--r--browser/components/sessionstore/test/browser_unrestored_crashedTabs.js69
-rw-r--r--browser/components/sessionstore/test/browser_upgrade_backup.js134
-rw-r--r--browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js26
-rw-r--r--browser/components/sessionstore/test/browser_windowStateContainer.js122
-rw-r--r--browser/components/sessionstore/test/content-forms.js133
-rw-r--r--browser/components/sessionstore/test/content.js222
-rw-r--r--browser/components/sessionstore/test/head.js564
-rw-r--r--browser/components/sessionstore/test/restore_redirect_http.html0
-rw-r--r--browser/components/sessionstore/test/restore_redirect_http.html^headers^2
-rw-r--r--browser/components/sessionstore/test/restore_redirect_js.html10
-rw-r--r--browser/components/sessionstore/test/restore_redirect_target.html8
-rw-r--r--browser/components/sessionstore/test/unit/.eslintrc.js7
-rw-r--r--browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json1
-rw-r--r--browser/components/sessionstore/test/unit/data/sessionstore_invalid.js3
-rw-r--r--browser/components/sessionstore/test/unit/data/sessionstore_valid.js3
-rw-r--r--browser/components/sessionstore/test/unit/head.js32
-rw-r--r--browser/components/sessionstore/test/unit/test_backup_once.js130
-rw-r--r--browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js114
-rw-r--r--browser/components/sessionstore/test/unit/test_shutdown_cleanup.js127
-rw-r--r--browser/components/sessionstore/test/unit/test_startup_invalid_session.js21
-rw-r--r--browser/components/sessionstore/test/unit/test_startup_nosession_async.js22
-rw-r--r--browser/components/sessionstore/test/unit/test_startup_session_async.js27
-rw-r--r--browser/components/sessionstore/test/unit/xpcshell.ini16
-rw-r--r--browser/components/shell/test/.eslintrc.js7
-rw-r--r--browser/components/shell/test/browser.ini6
-rw-r--r--browser/components/shell/test/browser_420786.js88
-rw-r--r--browser/components/shell/test/browser_633221.js7
-rw-r--r--browser/components/shell/test/unit/.eslintrc.js7
-rw-r--r--browser/components/shell/test/unit/test_421977.js123
-rw-r--r--browser/components/shell/test/unit/xpcshell.ini7
-rw-r--r--browser/components/syncedtabs/test/browser/.eslintrc.js7
-rw-r--r--browser/components/syncedtabs/test/browser/browser.ini4
-rw-r--r--browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js410
-rw-r--r--browser/components/syncedtabs/test/browser/head.js19
-rw-r--r--browser/components/syncedtabs/test/xpcshell/.eslintrc.js7
-rw-r--r--browser/components/syncedtabs/test/xpcshell/head.js29
-rw-r--r--browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js35
-rw-r--r--browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js218
-rw-r--r--browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js64
-rw-r--r--browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js266
-rw-r--r--browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js155
-rw-r--r--browser/components/syncedtabs/test/xpcshell/xpcshell.ini10
-rw-r--r--browser/components/tests/browser/.eslintrc.js7
-rw-r--r--browser/components/tests/browser/browser.ini4
-rw-r--r--browser/components/tests/browser/browser_bug538331.js426
-rw-r--r--browser/components/tests/browser/browser_contentpermissionprompt.js166
-rw-r--r--browser/components/tests/unit/.eslintrc.js7
-rw-r--r--browser/components/tests/unit/data/engine-de-DE.xml8
-rw-r--r--browser/components/tests/unit/distribution.ini58
-rw-r--r--browser/components/tests/unit/head.js9
-rw-r--r--browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js32
-rw-r--r--browser/components/tests/unit/test_distribution.js152
-rw-r--r--browser/components/tests/unit/xpcshell.ini10
-rw-r--r--browser/components/translation/test/.eslintrc.js7
-rw-r--r--browser/components/translation/test/bing.sjs234
-rw-r--r--browser/components/translation/test/browser.ini13
-rw-r--r--browser/components/translation/test/browser_translation_bing.js133
-rw-r--r--browser/components/translation/test/browser_translation_exceptions.js327
-rw-r--r--browser/components/translation/test/browser_translation_infobar.js216
-rw-r--r--browser/components/translation/test/browser_translation_telemetry.js300
-rw-r--r--browser/components/translation/test/browser_translation_yandex.js130
-rw-r--r--browser/components/translation/test/fixtures/bug1022725-fr.html15
-rw-r--r--browser/components/translation/test/fixtures/result-da39a3ee5e.txt22
-rw-r--r--browser/components/translation/test/fixtures/result-yandex-d448894848.json1
-rw-r--r--browser/components/translation/test/unit/.eslintrc.js7
-rw-r--r--browser/components/translation/test/unit/test_cld2.js463
-rw-r--r--browser/components/translation/test/unit/xpcshell.ini7
-rw-r--r--browser/components/translation/test/yandex.sjs199
-rw-r--r--browser/components/uitour/test/.eslintrc.js7
-rw-r--r--browser/components/uitour/test/browser.ini49
-rw-r--r--browser/components/uitour/test/browser_UITour.js408
-rw-r--r--browser/components/uitour/test/browser_UITour2.js83
-rw-r--r--browser/components/uitour/test/browser_UITour3.js181
-rw-r--r--browser/components/uitour/test/browser_UITour_annotation_size_attributes.js42
-rw-r--r--browser/components/uitour/test/browser_UITour_availableTargets.js114
-rw-r--r--browser/components/uitour/test/browser_UITour_defaultBrowser.js61
-rw-r--r--browser/components/uitour/test/browser_UITour_detach_tab.js94
-rw-r--r--browser/components/uitour/test/browser_UITour_forceReaderMode.js17
-rw-r--r--browser/components/uitour/test/browser_UITour_heartbeat.js755
-rw-r--r--browser/components/uitour/test/browser_UITour_modalDialog.js104
-rw-r--r--browser/components/uitour/test/browser_UITour_observe.js85
-rw-r--r--browser/components/uitour/test/browser_UITour_panel_close_annotation.js153
-rw-r--r--browser/components/uitour/test/browser_UITour_pocket.js82
-rw-r--r--browser/components/uitour/test/browser_UITour_registerPageID.js108
-rw-r--r--browser/components/uitour/test/browser_UITour_resetProfile.js48
-rw-r--r--browser/components/uitour/test/browser_UITour_showNewTab.js17
-rw-r--r--browser/components/uitour/test/browser_UITour_sync.js105
-rw-r--r--browser/components/uitour/test/browser_UITour_toggleReaderMode.js16
-rw-r--r--browser/components/uitour/test/browser_backgroundTab.js46
-rw-r--r--browser/components/uitour/test/browser_closeTab.js18
-rw-r--r--browser/components/uitour/test/browser_fxa.js68
-rw-r--r--browser/components/uitour/test/browser_no_tabs.js102
-rw-r--r--browser/components/uitour/test/browser_openPreferences.js36
-rw-r--r--browser/components/uitour/test/browser_openSearchPanel.js33
-rw-r--r--browser/components/uitour/test/browser_showMenu_controlCenter.js44
-rw-r--r--browser/components/uitour/test/browser_trackingProtection.js90
-rw-r--r--browser/components/uitour/test/browser_trackingProtection_tour.js77
-rw-r--r--browser/components/uitour/test/head.js449
-rw-r--r--browser/components/uitour/test/image.pngbin56060 -> 0 bytes
-rw-r--r--browser/components/uitour/test/uitour.html42
-rw-r--r--browser/extensions/formautofill/test/browser/.eslintrc.js7
-rw-r--r--browser/extensions/formautofill/test/browser/browser.ini3
-rw-r--r--browser/extensions/formautofill/test/browser/browser_check_installed.js14
-rw-r--r--browser/extensions/formautofill/test/unit/.eslintrc5
-rw-r--r--browser/extensions/formautofill/test/unit/head.js81
-rw-r--r--browser/extensions/formautofill/test/unit/test_autofillFormFields.js200
-rw-r--r--browser/extensions/formautofill/test/unit/test_collectFormFields.js122
-rw-r--r--browser/extensions/formautofill/test/unit/test_populateFieldValues.js106
-rw-r--r--browser/extensions/formautofill/test/unit/test_profileStorage.js222
-rw-r--r--browser/extensions/formautofill/test/unit/xpcshell.ini12
-rw-r--r--browser/extensions/pdfjs/test/.eslintrc.js7
-rw-r--r--browser/extensions/pdfjs/test/browser.ini10
-rw-r--r--browser/extensions/pdfjs/test/browser_pdfjs_main.js67
-rw-r--r--browser/extensions/pdfjs/test/browser_pdfjs_navigation.js283
-rw-r--r--browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js65
-rw-r--r--browser/extensions/pdfjs/test/browser_pdfjs_views.js67
-rw-r--r--browser/extensions/pdfjs/test/browser_pdfjs_zoom.js154
-rw-r--r--browser/extensions/pdfjs/test/file_pdfjs_test.pdfbin150611 -> 0 bytes
-rw-r--r--browser/extensions/pdfjs/test/head.js15
-rw-r--r--browser/extensions/pocket/test/.eslintrc.js7
-rw-r--r--browser/extensions/pocket/test/browser.ini6
-rw-r--r--browser/extensions/pocket/test/browser_pocket_ui_check.js61
-rw-r--r--browser/extensions/pocket/test/head.js67
-rw-r--r--browser/extensions/pocket/test/test.html11
-rw-r--r--browser/extensions/webcompat/test/browser/.eslintrc.js7
-rw-r--r--browser/extensions/webcompat/test/browser/browser.ini3
-rw-r--r--browser/extensions/webcompat/test/browser/browser_check_installed.js13
-rw-r--r--browser/modules/test/.eslintrc.js7
-rw-r--r--browser/modules/test/browser.ini42
-rw-r--r--browser/modules/test/browser_BrowserUITelemetry_buckets.js97
-rw-r--r--browser/modules/test/browser_BrowserUITelemetry_defaults.js37
-rw-r--r--browser/modules/test/browser_BrowserUITelemetry_sidebar.js56
-rw-r--r--browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js114
-rw-r--r--browser/modules/test/browser_ContentSearch.js425
-rw-r--r--browser/modules/test/browser_NetworkPrioritizer.js165
-rw-r--r--browser/modules/test/browser_PermissionUI.js445
-rw-r--r--browser/modules/test/browser_ProcessHangNotifications.js189
-rw-r--r--browser/modules/test/browser_SelfSupportBackend.js214
-rw-r--r--browser/modules/test/browser_UnsubmittedCrashHandler.js680
-rw-r--r--browser/modules/test/browser_UsageTelemetry.js268
-rw-r--r--browser/modules/test/browser_UsageTelemetry_content.js121
-rw-r--r--browser/modules/test/browser_UsageTelemetry_content_aboutHome.js84
-rw-r--r--browser/modules/test/browser_UsageTelemetry_private_and_restore.js90
-rw-r--r--browser/modules/test/browser_UsageTelemetry_searchbar.js195
-rw-r--r--browser/modules/test/browser_UsageTelemetry_urlbar.js220
-rw-r--r--browser/modules/test/browser_taskbar_preview.js100
-rw-r--r--browser/modules/test/browser_urlBar_zoom.js73
-rw-r--r--browser/modules/test/contentSearch.js64
-rw-r--r--browser/modules/test/contentSearchBadImage.xml6
-rw-r--r--browser/modules/test/contentSearchSuggestions.sjs9
-rw-r--r--browser/modules/test/contentSearchSuggestions.xml6
-rw-r--r--browser/modules/test/head.js113
-rw-r--r--browser/modules/test/unit/social/.eslintrc.js7
-rw-r--r--browser/modules/test/unit/social/blocklist.xml6
-rw-r--r--browser/modules/test/unit/social/head.js210
-rw-r--r--browser/modules/test/unit/social/test_SocialService.js166
-rw-r--r--browser/modules/test/unit/social/test_SocialServiceMigration21.js54
-rw-r--r--browser/modules/test/unit/social/test_SocialServiceMigration22.js67
-rw-r--r--browser/modules/test/unit/social/test_SocialServiceMigration29.js61
-rw-r--r--browser/modules/test/unit/social/test_social.js32
-rw-r--r--browser/modules/test/unit/social/test_socialDisabledStartup.js29
-rw-r--r--browser/modules/test/unit/social/xpcshell.ini13
-rw-r--r--browser/modules/test/usageTelemetrySearchSuggestions.sjs9
-rw-r--r--browser/modules/test/usageTelemetrySearchSuggestions.xml6
-rw-r--r--browser/modules/test/xpcshell/.eslintrc.js7
-rw-r--r--browser/modules/test/xpcshell/test_AttributionCode.js110
-rw-r--r--browser/modules/test/xpcshell/test_DirectoryLinksProvider.js1854
-rw-r--r--browser/modules/test/xpcshell/test_LaterRun.js138
-rw-r--r--browser/modules/test/xpcshell/test_SitePermissions.js115
-rw-r--r--browser/modules/test/xpcshell/xpcshell.ini11
-rw-r--r--devtools/client/framework/test/browser.ini2
-rw-r--r--devtools/shared/webconsole/test/chrome.ini2
1697 files changed, 0 insertions, 144364 deletions
diff --git a/browser/base/content/test/alerts/.eslintrc.js b/browser/base/content/test/alerts/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/alerts/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/alerts/browser.ini b/browser/base/content/test/alerts/browser.ini
deleted file mode 100644
index 07fcf5253..000000000
--- a/browser/base/content/test/alerts/browser.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- file_dom_notifications.html
-
-[browser_notification_close.js]
-[browser_notification_do_not_disturb.js]
-[browser_notification_open_settings.js]
-[browser_notification_remove_permission.js]
-[browser_notification_permission_migration.js]
-[browser_notification_replace.js]
-[browser_notification_tab_switching.js]
diff --git a/browser/base/content/test/alerts/browser_notification_close.js b/browser/base/content/test/alerts/browser_notification_close.js
deleted file mode 100644
index bbd444212..000000000
--- a/browser/base/content/test/alerts/browser_notification_close.js
+++ /dev/null
@@ -1,71 +0,0 @@
-"use strict";
-
-const {PlacesTestUtils} =
- Cu.import("resource://testing-common/PlacesTestUtils.jsm", {});
-
-let notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-let oldShowFavicons;
-
-add_task(function* test_notificationClose() {
- let pm = Services.perms;
- let notificationURI = makeURI(notificationURL);
- pm.add(notificationURI, "desktop-notification", pm.ALLOW_ACTION);
-
- oldShowFavicons = Services.prefs.getBoolPref("alerts.showFavicons");
- Services.prefs.setBoolPref("alerts.showFavicons", true);
-
- yield PlacesTestUtils.addVisits(notificationURI);
- let faviconURI = yield new Promise(resolve => {
- let faviconURI = makeURI("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC");
- PlacesUtils.favicons.setAndFetchFaviconForPage(notificationURI, faviconURI,
- true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- (faviconURI, iconSize, iconData, mimeType) => resolve(faviconURI),
- Services.scriptSecurityManager.getSystemPrincipal());
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: notificationURL
- }, function* dummyTabTask(aBrowser) {
- yield openNotification(aBrowser, "showNotification2");
-
- info("Notification alert showing");
-
- let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- if (!alertWindow) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- yield closeNotification(aBrowser);
- return;
- }
-
- let alertTitleLabel = alertWindow.document.getElementById("alertTitleLabel");
- is(alertTitleLabel.value, "Test title", "Title text of notification should be present");
- let alertTextLabel = alertWindow.document.getElementById("alertTextLabel");
- is(alertTextLabel.textContent, "Test body 2", "Body text of notification should be present");
- let alertIcon = alertWindow.document.getElementById("alertIcon");
- is(alertIcon.src, faviconURI.spec, "Icon of notification should be present");
-
- let alertCloseButton = alertWindow.document.querySelector(".alertCloseButton");
- is(alertCloseButton.localName, "toolbarbutton", "close button found");
- let promiseBeforeUnloadEvent =
- BrowserTestUtils.waitForEvent(alertWindow, "beforeunload");
- let closedTime = alertWindow.Date.now();
- alertCloseButton.click();
- info("Clicked on close button");
- yield promiseBeforeUnloadEvent;
-
- ok(true, "Alert should close when the close button is clicked");
- let currentTime = alertWindow.Date.now();
- // The notification will self-close at 12 seconds, so this checks
- // that the notification closed before the timeout.
- ok(currentTime - closedTime < 5000,
- "Close requested at " + closedTime + ", actually closed at " + currentTime);
- });
-});
-
-add_task(function* cleanup() {
- Services.perms.remove(makeURI(notificationURL), "desktop-notification");
- if (typeof oldShowFavicons == "boolean") {
- Services.prefs.setBoolPref("alerts.showFavicons", oldShowFavicons);
- }
-});
diff --git a/browser/base/content/test/alerts/browser_notification_do_not_disturb.js b/browser/base/content/test/alerts/browser_notification_do_not_disturb.js
deleted file mode 100644
index 92c689fd2..000000000
--- a/browser/base/content/test/alerts/browser_notification_do_not_disturb.js
+++ /dev/null
@@ -1,80 +0,0 @@
-"use strict";
-
-var tab;
-var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-
-const ALERT_SERVICE = Cc["@mozilla.org/alerts-service;1"]
- .getService(Ci.nsIAlertsService)
- .QueryInterface(Ci.nsIAlertsDoNotDisturb);
-
-function test () {
- waitForExplicitFinish();
-
- try {
- // Only run the test if the do-not-disturb
- // interface has been implemented.
- ALERT_SERVICE.manualDoNotDisturb;
- ok(true, "Alert service implements do-not-disturb interface");
- } catch (e) {
- ok(true, "Alert service doesn't implement do-not-disturb interface, exiting test");
- finish();
- return;
- }
-
- let pm = Services.perms;
- registerCleanupFunction(function() {
- ALERT_SERVICE.manualDoNotDisturb = false;
- pm.remove(makeURI(notificationURL), "desktop-notification");
- gBrowser.removeTab(tab);
- window.restore();
- });
-
- pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
-
- // Make sure that do-not-disturb is not enabled.
- ok(!ALERT_SERVICE.manualDoNotDisturb, "Alert service should not be disabled when test starts");
- ALERT_SERVICE.manualDoNotDisturb = false;
-
- tab = gBrowser.addTab(notificationURL);
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.addEventListener("load", onLoad, true);
-}
-
-function onLoad() {
- tab.linkedBrowser.removeEventListener("load", onLoad, true);
- openNotification(tab.linkedBrowser, "showNotification2").then(onAlertShowing);
-}
-
-function onAlertShowing() {
- info("Notification alert showing");
-
- let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- if (!alertWindow) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- closeNotification(tab.linkedBrowser).then(finish);
- return;
- }
- let doNotDisturbMenuItem = alertWindow.document.getElementById("doNotDisturbMenuItem");
- is(doNotDisturbMenuItem.localName, "menuitem", "menuitem found");
- alertWindow.addEventListener("beforeunload", onAlertClosing);
- doNotDisturbMenuItem.click();
- info("Clicked on do-not-disturb menuitem");
-}
-
-function onAlertClosing(event) {
- event.target.removeEventListener("beforeunload", onAlertClosing);
-
- ok(ALERT_SERVICE.manualDoNotDisturb, "Alert service should be disabled after clicking menuitem");
-
- // The notification should not appear, but there is
- // no way from the client-side to know that it was
- // blocked, except for waiting some time and realizing
- // that the "onshow" event never fired.
- openNotification(tab.linkedBrowser, "showNotification2", 2000)
- .then(onAlert2Showing, finish);
-}
-
-function onAlert2Showing() {
- ok(false, "the second alert should not have been shown");
- closeNotification(tab.linkedBrowser).then(finish);
-}
diff --git a/browser/base/content/test/alerts/browser_notification_open_settings.js b/browser/base/content/test/alerts/browser_notification_open_settings.js
deleted file mode 100644
index 5306fd90a..000000000
--- a/browser/base/content/test/alerts/browser_notification_open_settings.js
+++ /dev/null
@@ -1,58 +0,0 @@
-"use strict";
-
-var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-
-add_task(function* test_settingsOpen_observer() {
- info("Opening a dummy tab so openPreferences=>switchToTabHavingURI doesn't use the blank tab.");
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:robots"
- }, function* dummyTabTask(aBrowser) {
- let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#content");
- info("simulate a notifications-open-settings notification");
- let uri = NetUtil.newURI("https://example.com");
- let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
- Services.obs.notifyObservers(principal, "notifications-open-settings", null);
- let tab = yield tabPromise;
- ok(tab, "The notification settings tab opened");
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-add_task(function* test_settingsOpen_button() {
- let pm = Services.perms;
- info("Adding notification permission");
- pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
-
- try {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: notificationURL
- }, function* tabTask(aBrowser) {
- info("Waiting for notification");
- yield openNotification(aBrowser, "showNotification2");
-
- let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- if (!alertWindow) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- yield closeNotification(aBrowser);
- return;
- }
-
- let closePromise = promiseWindowClosed(alertWindow);
- let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#content");
- let openSettingsMenuItem = alertWindow.document.getElementById("openSettingsMenuItem");
- openSettingsMenuItem.click();
-
- info("Waiting for notification settings tab");
- let tab = yield tabPromise;
- ok(tab, "The notification settings tab opened");
-
- yield closePromise;
- yield BrowserTestUtils.removeTab(tab);
- });
- } finally {
- info("Removing notification permission");
- pm.remove(makeURI(notificationURL), "desktop-notification");
- }
-});
diff --git a/browser/base/content/test/alerts/browser_notification_permission_migration.js b/browser/base/content/test/alerts/browser_notification_permission_migration.js
deleted file mode 100644
index b015e59a7..000000000
--- a/browser/base/content/test/alerts/browser_notification_permission_migration.js
+++ /dev/null
@@ -1,45 +0,0 @@
-const UI_VERSION = 32;
-
-var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"]
- .getService(Ci.nsIObserver);
-var notificationURI = makeURI("http://example.org");
-var pm = Services.perms;
-var currentUIVersion;
-
-add_task(function* setup() {
- currentUIVersion = Services.prefs.getIntPref("browser.migration.version");
- Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1);
- pm.add(notificationURI, "desktop-notification", pm.ALLOW_ACTION);
-});
-
-add_task(function* test_permissionMigration() {
- if ("@mozilla.org/system-alerts-service;1" in Cc) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- return;
- }
-
- info("Waiting for migration notification");
- let alertWindowPromise = promiseAlertWindow();
- gBrowserGlue.observe(null, "browser-glue-test", "force-ui-migration");
- let alertWindow = yield alertWindowPromise;
-
- info("Clicking on notification");
- let url =
- Services.urlFormatter.formatURLPref("app.support.baseURL") +
- "push#w_upgraded-notifications";
- let closePromise = promiseWindowClosed(alertWindow);
- let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url);
- EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"), {}, alertWindow);
-
- info("Waiting for migration info tab");
- let tab = yield tabPromise;
- ok(tab, "The migration info tab opened");
-
- yield closePromise;
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* cleanup() {
- Services.prefs.setIntPref("browser.migration.version", currentUIVersion);
- pm.remove(notificationURI, "desktop-notification");
-});
diff --git a/browser/base/content/test/alerts/browser_notification_remove_permission.js b/browser/base/content/test/alerts/browser_notification_remove_permission.js
deleted file mode 100644
index bd36faeae..000000000
--- a/browser/base/content/test/alerts/browser_notification_remove_permission.js
+++ /dev/null
@@ -1,72 +0,0 @@
-"use strict";
-
-var tab;
-var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-var alertWindowClosed = false;
-var permRemoved = false;
-
-function test () {
- waitForExplicitFinish();
-
- let pm = Services.perms;
- registerCleanupFunction(function() {
- pm.remove(makeURI(notificationURL), "desktop-notification");
- gBrowser.removeTab(tab);
- window.restore();
- });
-
- pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
-
- tab = gBrowser.addTab(notificationURL);
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.addEventListener("load", onLoad, true);
-}
-
-function onLoad() {
- tab.linkedBrowser.removeEventListener("load", onLoad, true);
- openNotification(tab.linkedBrowser, "showNotification2").then(onAlertShowing);
-}
-
-function onAlertShowing() {
- info("Notification alert showing");
-
- let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- if (!alertWindow) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- closeNotification(tab.linkedBrowser).then(finish);
- return;
- }
- ok(Services.perms.testExactPermission(makeURI(notificationURL), "desktop-notification"),
- "Permission should exist prior to removal");
- let disableForOriginMenuItem = alertWindow.document.getElementById("disableForOriginMenuItem");
- is(disableForOriginMenuItem.localName, "menuitem", "menuitem found");
- Services.obs.addObserver(permObserver, "perm-changed", false);
- alertWindow.addEventListener("beforeunload", onAlertClosing);
- disableForOriginMenuItem.click();
- info("Clicked on disable-for-origin menuitem")
-}
-
-function permObserver(subject, topic, data) {
- if (topic != "perm-changed") {
- return;
- }
-
- let permission = subject.QueryInterface(Ci.nsIPermission);
- is(permission.type, "desktop-notification", "desktop-notification permission changed");
- is(data, "deleted", "desktop-notification permission deleted");
-
- Services.obs.removeObserver(permObserver, "perm-changed");
- permRemoved = true;
- if (alertWindowClosed) {
- finish();
- }
-}
-
-function onAlertClosing(event) {
- event.target.removeEventListener("beforeunload", onAlertClosing);
-
- alertWindowClosed = true;
- if (permRemoved) {
- finish();
- }
-}
diff --git a/browser/base/content/test/alerts/browser_notification_replace.js b/browser/base/content/test/alerts/browser_notification_replace.js
deleted file mode 100644
index e678dc438..000000000
--- a/browser/base/content/test/alerts/browser_notification_replace.js
+++ /dev/null
@@ -1,38 +0,0 @@
-"use strict";
-
-let notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-
-add_task(function* test_notificationReplace() {
- let pm = Services.perms;
- pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: notificationURL
- }, function* dummyTabTask(aBrowser) {
- yield ContentTask.spawn(aBrowser, {}, function* () {
- let win = content.window.wrappedJSObject;
- let notification = win.showNotification1();
- let promiseCloseEvent = ContentTaskUtils.waitForEvent(notification, "close");
-
- let showEvent = yield ContentTaskUtils.waitForEvent(notification, "show");
- Assert.equal(showEvent.target.body, "Test body 1", "Showed tagged notification");
-
- let newNotification = win.showNotification2();
- let newShowEvent = yield ContentTaskUtils.waitForEvent(newNotification, "show");
- Assert.equal(newShowEvent.target.body, "Test body 2", "Showed new notification with same tag");
-
- let closeEvent = yield promiseCloseEvent;
- Assert.equal(closeEvent.target.body, "Test body 1", "Closed previous tagged notification");
-
- let promiseNewCloseEvent = ContentTaskUtils.waitForEvent(newNotification, "close");
- newNotification.close();
- let newCloseEvent = yield promiseNewCloseEvent;
- Assert.equal(newCloseEvent.target.body, "Test body 2", "Closed new notification");
- });
- });
-});
-
-add_task(function* cleanup() {
- Services.perms.remove(makeURI(notificationURL), "desktop-notification");
-});
diff --git a/browser/base/content/test/alerts/browser_notification_tab_switching.js b/browser/base/content/test/alerts/browser_notification_tab_switching.js
deleted file mode 100644
index 7e46c0722..000000000
--- a/browser/base/content/test/alerts/browser_notification_tab_switching.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-"use strict";
-
-var tab;
-var notification;
-var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
-var newWindowOpenedFromTab;
-
-add_task(function* test_notificationPreventDefaultAndSwitchTabs() {
- let pm = Services.perms;
- pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
-
- let originalTab = gBrowser.selectedTab;
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: notificationURL
- }, function* dummyTabTask(aBrowser) {
- // Put new tab in background so it is obvious when it is re-focused.
- yield BrowserTestUtils.switchTab(gBrowser, originalTab);
- isnot(gBrowser.selectedBrowser, aBrowser, "Notification page loaded as a background tab");
-
- // First, show a notification that will be have the tab-switching prevented.
- function promiseNotificationEvent(evt) {
- return ContentTask.spawn(aBrowser, evt, function* (evt) {
- return yield new Promise(resolve => {
- let notification = content.wrappedJSObject._notification;
- notification.addEventListener(evt, function l(event) {
- notification.removeEventListener(evt, l);
- resolve({ defaultPrevented: event.defaultPrevented });
- });
- });
- });
- }
- yield openNotification(aBrowser, "showNotification1");
- info("Notification alert showing");
- let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- if (!alertWindow) {
- ok(true, "Notifications don't use XUL windows on all platforms.");
- yield closeNotification(aBrowser);
- return;
- }
- info("Clicking on notification");
- let promiseClickEvent = promiseNotificationEvent("click");
-
- // NB: This executeSoon is needed to allow the non-e10s runs of this test
- // a chance to set the event listener on the page. Otherwise, we
- // synchronously fire the click event before we listen for the event.
- executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"),
- {}, alertWindow);
- });
- let clickEvent = yield promiseClickEvent;
- ok(clickEvent.defaultPrevented, "The event handler for the first notification cancels the event");
- isnot(gBrowser.selectedBrowser, aBrowser, "Notification page still a background tab");
- let notificationClosed = promiseNotificationEvent("close");
- yield closeNotification(aBrowser);
- yield notificationClosed;
-
- // Second, show a notification that will cause the tab to get switched.
- yield openNotification(aBrowser, "showNotification2");
- alertWindow = Services.wm.getMostRecentWindow("alert:alert");
- let promiseTabSelect = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabSelect");
- EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"),
- {},
- alertWindow);
- yield promiseTabSelect;
- is(gBrowser.selectedBrowser.currentURI.spec, notificationURL,
- "Clicking on the second notification should select its originating tab");
- notificationClosed = promiseNotificationEvent("close");
- yield closeNotification(aBrowser);
- yield notificationClosed;
- });
-});
-
-add_task(function* cleanup() {
- Services.perms.remove(makeURI(notificationURL), "desktop-notification");
-});
diff --git a/browser/base/content/test/alerts/file_dom_notifications.html b/browser/base/content/test/alerts/file_dom_notifications.html
deleted file mode 100644
index 6deede8fc..000000000
--- a/browser/base/content/test/alerts/file_dom_notifications.html
+++ /dev/null
@@ -1,39 +0,0 @@
-<html>
-<head>
-<meta charset="utf-8">
-<script>
-"use strict";
-
-function showNotification1() {
- var options = {
- dir: undefined,
- lang: undefined,
- body: "Test body 1",
- tag: "Test tag",
- icon: undefined,
- };
- var n = new Notification("Test title", options);
- n.addEventListener("click", function(event) {
- event.preventDefault();
- });
- return n;
-}
-
-function showNotification2() {
- var options = {
- dir: undefined,
- lang: undefined,
- body: "Test body 2",
- tag: "Test tag",
- icon: undefined,
- };
- return new Notification("Test title", options);
-}
-</script>
-</head>
-<body>
-<form id="notificationForm" onsubmit="showNotification();">
- <input type="submit" value="Show notification" id="submit"/>
-</form>
-</body>
-</html>
diff --git a/browser/base/content/test/alerts/head.js b/browser/base/content/test/alerts/head.js
deleted file mode 100644
index 21257de31..000000000
--- a/browser/base/content/test/alerts/head.js
+++ /dev/null
@@ -1,71 +0,0 @@
-function promiseAlertWindow() {
- return new Promise(function(resolve) {
- let listener = {
- onOpenWindow(window) {
- let alertWindow = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
- alertWindow.addEventListener("load", function onLoad() {
- alertWindow.removeEventListener("load", onLoad);
- let windowType = alertWindow.document.documentElement.getAttribute("windowtype");
- if (windowType != "alert:alert") {
- return;
- }
- Services.wm.removeListener(listener);
- resolve(alertWindow);
- });
- },
- };
- Services.wm.addListener(listener);
- });
-}
-
-/**
- * Similar to `BrowserTestUtils.closeWindow`, but
- * doesn't call `window.close()`.
- */
-function promiseWindowClosed(window) {
- return new Promise(function(resolve) {
- Services.ww.registerNotification(function observer(subject, topic, data) {
- if (topic == "domwindowclosed" && subject == window) {
- Services.ww.unregisterNotification(observer);
- resolve();
- }
- });
- });
-}
-
-/**
- * These two functions work with file_dom_notifications.html to open the
- * notification and close it.
- *
- * |fn| can be showNotification1 or showNotification2.
- * if |timeout| is passed, then the promise returned from this function is
- * rejected after the requested number of miliseconds.
- */
-function openNotification(aBrowser, fn, timeout) {
- return ContentTask.spawn(aBrowser, { fn, timeout }, function* ({ fn, timeout }) {
- let win = content.wrappedJSObject;
- let notification = win[fn]();
- win._notification = notification;
- yield new Promise((resolve, reject) => {
- function listener() {
- notification.removeEventListener("show", listener);
- resolve();
- }
-
- notification.addEventListener("show", listener);
-
- if (timeout) {
- content.setTimeout(() => {
- notification.removeEventListener("show", listener);
- reject("timed out");
- }, timeout);
- }
- });
- });
-}
-
-function closeNotification(aBrowser) {
- return ContentTask.spawn(aBrowser, null, function() {
- content.wrappedJSObject._notification.close();
- });
-}
diff --git a/browser/base/content/test/captivePortal/browser.ini b/browser/base/content/test/captivePortal/browser.ini
deleted file mode 100644
index cfdbc5c2f..000000000
--- a/browser/base/content/test/captivePortal/browser.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-
-[browser_CaptivePortalWatcher.js]
-skip-if = os == "win" # Bug 1313894
-[browser_CaptivePortalWatcher_1.js]
-skip-if = os == "win" # Bug 1313894
-[browser_captivePortal_certErrorUI.js]
diff --git a/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher.js b/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher.js
deleted file mode 100644
index e9c0fad6d..000000000
--- a/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher.js
+++ /dev/null
@@ -1,119 +0,0 @@
-"use strict";
-
-add_task(setupPrefsAndRecentWindowBehavior);
-
-// Each of the test cases below is run twice: once for login-success and once
-// for login-abort (aSuccess set to true and false respectively).
-let testCasesForBothSuccessAndAbort = [
- /**
- * A portal is detected when there's no browser window, then a browser
- * window is opened, then the portal is freed.
- * The portal tab should be added and focused when the window is
- * opened, and closed automatically when the success event is fired.
- * The captive portal notification should be shown when the window is
- * opened, and closed automatically when the success event is fired.
- */
- function* test_detectedWithNoBrowserWindow_Open(aSuccess) {
- yield portalDetected();
- let win = yield focusWindowAndWaitForPortalUI();
- yield freePortal(aSuccess);
- ensureNoPortalTab(win);
- ensureNoPortalNotification(win);
- yield closeWindowAndWaitForXulWindowVisible(win);
- },
-
- /**
- * A portal is detected when multiple browser windows are open but none
- * have focus. A brower window is focused, then the portal is freed.
- * The portal tab should be added and focused when the window is
- * focused, and closed automatically when the success event is fired.
- * The captive portal notification should be shown in all windows upon
- * detection, and closed automatically when the success event is fired.
- */
- function* test_detectedWithNoBrowserWindow_Focused(aSuccess) {
- let win1 = yield openWindowAndWaitForFocus();
- let win2 = yield openWindowAndWaitForFocus();
- // Defocus both windows.
- yield SimpleTest.promiseFocus(window);
-
- yield portalDetected();
-
- // Notification should be shown in both windows.
- ensurePortalNotification(win1);
- ensureNoPortalTab(win1);
- ensurePortalNotification(win2);
- ensureNoPortalTab(win2);
-
- yield focusWindowAndWaitForPortalUI(false, win2);
-
- yield freePortal(aSuccess);
-
- ensureNoPortalNotification(win1);
- ensureNoPortalTab(win2);
- ensureNoPortalNotification(win2);
-
- yield closeWindowAndWaitForXulWindowVisible(win2);
- // No need to wait for xul-window-visible: after win2 is closed, focus
- // is restored to the default window and win1 remains in the background.
- yield BrowserTestUtils.closeWindow(win1);
- },
-
- /**
- * A portal is detected when there's no browser window, then a browser
- * window is opened, then the portal is freed.
- * The recheck triggered when the browser window is opened takes a
- * long time. No portal tab should be added.
- * The captive portal notification should be shown when the window is
- * opened, and closed automatically when the success event is fired.
- */
- function* test_detectedWithNoBrowserWindow_LongRecheck(aSuccess) {
- yield portalDetected();
- let win = yield focusWindowAndWaitForPortalUI(true);
- yield freePortal(aSuccess);
- ensureNoPortalTab(win);
- ensureNoPortalNotification(win);
- yield closeWindowAndWaitForXulWindowVisible(win);
- },
-
- /**
- * A portal is detected when there's no browser window, and the
- * portal is freed before a browser window is opened. No portal
- * UI should be shown when a browser window is opened.
- */
- function* test_detectedWithNoBrowserWindow_GoneBeforeOpen(aSuccess) {
- yield portalDetected();
- yield freePortal(aSuccess);
- let win = yield openWindowAndWaitForFocus();
- // Wait for a while to make sure no UI is shown.
- yield new Promise(resolve => {
- setTimeout(resolve, 1000);
- });
- ensureNoPortalTab(win);
- ensureNoPortalNotification(win);
- yield closeWindowAndWaitForXulWindowVisible(win);
- },
-
- /**
- * A portal is detected when a browser window has focus. No portal tab should
- * be opened. A notification bar should be displayed in all browser windows.
- */
- function* test_detectedWithFocus(aSuccess) {
- let win1 = yield openWindowAndWaitForFocus();
- let win2 = yield openWindowAndWaitForFocus();
- yield portalDetected();
- ensureNoPortalTab(win1);
- ensureNoPortalTab(win2);
- ensurePortalNotification(win1);
- ensurePortalNotification(win2);
- yield freePortal(aSuccess);
- ensureNoPortalNotification(win1);
- ensureNoPortalNotification(win2);
- yield closeWindowAndWaitForXulWindowVisible(win2);
- yield closeWindowAndWaitForXulWindowVisible(win1);
- },
-];
-
-for (let testcase of testCasesForBothSuccessAndAbort) {
- add_task(testcase.bind(null, true));
- add_task(testcase.bind(null, false));
-}
diff --git a/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher_1.js b/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher_1.js
deleted file mode 100644
index 71b12c32a..000000000
--- a/browser/base/content/test/captivePortal/browser_CaptivePortalWatcher_1.js
+++ /dev/null
@@ -1,91 +0,0 @@
-"use strict";
-
-add_task(setupPrefsAndRecentWindowBehavior);
-
-let testcases = [
- /**
- * A portal is detected when there's no browser window,
- * then a browser window is opened, and the portal is logged into
- * and redirects to a different page. The portal tab should be added
- * and focused when the window is opened, and left open after login
- * since it redirected.
- */
- function* test_detectedWithNoBrowserWindow_Redirect() {
- yield portalDetected();
- let win = yield focusWindowAndWaitForPortalUI();
- let browser = win.gBrowser.selectedTab.linkedBrowser;
- let loadPromise =
- BrowserTestUtils.browserLoaded(browser, false, CANONICAL_URL_REDIRECTED);
- BrowserTestUtils.loadURI(browser, CANONICAL_URL_REDIRECTED);
- yield loadPromise;
- yield freePortal(true);
- ensurePortalTab(win);
- ensureNoPortalNotification(win);
- yield closeWindowAndWaitForXulWindowVisible(win);
- },
-
- /**
- * Test the various expected behaviors of the "Show Login Page" button
- * in the captive portal notification. The button should be visible for
- * all tabs except the captive portal tab, and when clicked, should
- * ensure a captive portal tab is open and select it.
- */
- function* test_showLoginPageButton() {
- let win = yield openWindowAndWaitForFocus();
- yield portalDetected();
- let notification = ensurePortalNotification(win);
- testShowLoginPageButtonVisibility(notification, "visible");
-
- function testPortalTabSelectedAndButtonNotVisible() {
- is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
- testShowLoginPageButtonVisibility(notification, "hidden");
- }
-
- let button = notification.querySelector("button.notification-button");
- function* clickButtonAndExpectNewPortalTab() {
- let p = BrowserTestUtils.waitForNewTab(win.gBrowser, CANONICAL_URL);
- button.click();
- let tab = yield p;
- is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
- return tab;
- }
-
- // Simulate clicking the button. The portal tab should be opened and
- // selected and the button should hide.
- let tab = yield clickButtonAndExpectNewPortalTab();
- testPortalTabSelectedAndButtonNotVisible();
-
- // Close the tab. The button should become visible.
- yield BrowserTestUtils.removeTab(tab);
- ensureNoPortalTab(win);
- testShowLoginPageButtonVisibility(notification, "visible");
-
- // When the button is clicked, a new portal tab should be opened and
- // selected.
- tab = yield clickButtonAndExpectNewPortalTab();
-
- // Open another arbitrary tab. The button should become visible. When it's clicked,
- // the portal tab should be selected.
- let anotherTab = yield BrowserTestUtils.openNewForegroundTab(win.gBrowser);
- testShowLoginPageButtonVisibility(notification, "visible");
- button.click();
- is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
-
- // Close the portal tab and select the arbitrary tab. The button should become
- // visible and when it's clicked, a new portal tab should be opened.
- yield BrowserTestUtils.removeTab(tab);
- win.gBrowser.selectedTab = anotherTab;
- testShowLoginPageButtonVisibility(notification, "visible");
- tab = yield clickButtonAndExpectNewPortalTab();
-
- yield BrowserTestUtils.removeTab(anotherTab);
- yield freePortal(true);
- ensureNoPortalTab(win);
- ensureNoPortalNotification(win);
- yield closeWindowAndWaitForXulWindowVisible(win);
- },
-];
-
-for (let testcase of testcases) {
- add_task(testcase);
-}
diff --git a/browser/base/content/test/captivePortal/browser_captivePortal_certErrorUI.js b/browser/base/content/test/captivePortal/browser_captivePortal_certErrorUI.js
deleted file mode 100644
index 6b97e19a3..000000000
--- a/browser/base/content/test/captivePortal/browser_captivePortal_certErrorUI.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const BAD_CERT_PAGE = "https://expired.example.com/";
-
-// This tests the alternate cert error UI when we are behind a captive portal.
-
-add_task(function* checkCaptivePortalCertErrorUI() {
- yield SpecialPowers.pushPrefEnv({
- set: [["captivedetect.canonicalURL", CANONICAL_URL],
- ["captivedetect.canonicalContent", CANONICAL_CONTENT]],
- });
-
- let captivePortalStatePropagated = TestUtils.topicObserved("ipc:network:captive-portal-set-state");
-
- info("Checking that the alternate about:certerror UI is shown when we are behind a captive portal.");
- Services.obs.notifyObservers(null, "captive-portal-login", null);
-
- info("Waiting for captive portal state to be propagated to the content process.");
- yield captivePortalStatePropagated;
-
- // Open a page with a cert error.
- let browser;
- let certErrorLoaded;
- let errorTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- let tab = gBrowser.addTab(BAD_CERT_PAGE);
- gBrowser.selectedTab = tab;
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- return tab;
- }, false);
-
- info("Waiting for cert error page to load.")
- yield certErrorLoaded;
-
- let portalTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, CANONICAL_URL);
-
- yield ContentTask.spawn(browser, null, () => {
- let doc = content.document;
- ok(doc.body.classList.contains("captiveportal"),
- "Captive portal error page UI is visible.");
-
- info("Clicking the Open Login Page button.");
- let loginButton = doc.getElementById("openPortalLoginPageButton");
- is(loginButton.getAttribute("autofocus"), "true", "openPortalLoginPageButton has autofocus");
- loginButton.click();
- });
-
- let portalTab = yield portalTabPromise;
- is(gBrowser.selectedTab, portalTab, "Login page should be open in a new foreground tab.");
-
- // Make sure clicking the "Open Login Page" button again focuses the existing portal tab.
- yield BrowserTestUtils.switchTab(gBrowser, errorTab);
- // Passing an empty function to BrowserTestUtils.switchTab lets us wait for an arbitrary
- // tab switch.
- portalTabPromise = BrowserTestUtils.switchTab(gBrowser, () => {});
- yield ContentTask.spawn(browser, null, () => {
- info("Clicking the Open Login Page button.");
- content.document.getElementById("openPortalLoginPageButton").click();
- });
-
- let portalTab2 = yield portalTabPromise;
- is(portalTab2, portalTab, "The existing portal tab should be focused.");
-
- let portalTabRemoved = BrowserTestUtils.removeTab(portalTab, {dontRemove: true});
- let errorTabReloaded = waitForCertErrorLoad(browser);
-
- Services.obs.notifyObservers(null, "captive-portal-login-success", null);
- yield portalTabRemoved;
-
- info("Waiting for error tab to be reloaded after the captive portal was freed.");
- yield errorTabReloaded;
- yield ContentTask.spawn(browser, null, () => {
- let doc = content.document;
- ok(!doc.body.classList.contains("captiveportal"),
- "Captive portal error page UI is not visible.");
- });
-
- yield BrowserTestUtils.removeTab(errorTab);
-});
diff --git a/browser/base/content/test/captivePortal/head.js b/browser/base/content/test/captivePortal/head.js
deleted file mode 100644
index e40b5a325..000000000
--- a/browser/base/content/test/captivePortal/head.js
+++ /dev/null
@@ -1,181 +0,0 @@
-Components.utils.import("resource:///modules/RecentWindow.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "CaptivePortalWatcher",
- "resource:///modules/CaptivePortalWatcher.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cps",
- "@mozilla.org/network/captive-portal-service;1",
- "nsICaptivePortalService");
-
-const CANONICAL_CONTENT = "success";
-const CANONICAL_URL = "data:text/plain;charset=utf-8," + CANONICAL_CONTENT;
-const CANONICAL_URL_REDIRECTED = "data:text/plain;charset=utf-8,redirected";
-const PORTAL_NOTIFICATION_VALUE = "captive-portal-detected";
-
-function* setupPrefsAndRecentWindowBehavior() {
- yield SpecialPowers.pushPrefEnv({
- set: [["captivedetect.canonicalURL", CANONICAL_URL],
- ["captivedetect.canonicalContent", CANONICAL_CONTENT]],
- });
- // We need to test behavior when a portal is detected when there is no browser
- // window, but we can't close the default window opened by the test harness.
- // Instead, we deactivate CaptivePortalWatcher in the default window and
- // exclude it from RecentWindow.getMostRecentBrowserWindow in an attempt to
- // mask its presence.
- window.CaptivePortalWatcher.uninit();
- let getMostRecentBrowserWindowCopy = RecentWindow.getMostRecentBrowserWindow;
- let defaultWindow = window;
- RecentWindow.getMostRecentBrowserWindow = () => {
- let win = getMostRecentBrowserWindowCopy();
- if (win == defaultWindow) {
- return null;
- }
- return win;
- };
-
- registerCleanupFunction(function* cleanUp() {
- RecentWindow.getMostRecentBrowserWindow = getMostRecentBrowserWindowCopy;
- window.CaptivePortalWatcher.init();
- });
-}
-
-function* portalDetected() {
- Services.obs.notifyObservers(null, "captive-portal-login", null);
- yield BrowserTestUtils.waitForCondition(() => {
- return cps.state == cps.LOCKED_PORTAL;
- }, "Waiting for Captive Portal Service to update state after portal detected.");
-}
-
-function* freePortal(aSuccess) {
- Services.obs.notifyObservers(null,
- "captive-portal-login-" + (aSuccess ? "success" : "abort"), null);
- yield BrowserTestUtils.waitForCondition(() => {
- return cps.state != cps.LOCKED_PORTAL;
- }, "Waiting for Captive Portal Service to update state after portal freed.");
-}
-
-// If a window is provided, it will be focused. Otherwise, a new window
-// will be opened and focused.
-function* focusWindowAndWaitForPortalUI(aLongRecheck, win) {
- // CaptivePortalWatcher triggers a recheck when a window gains focus. If
- // the time taken for the check to complete is under PORTAL_RECHECK_DELAY_MS,
- // a tab with the login page is opened and selected. If it took longer,
- // no tab is opened. It's not reliable to time things in an async test,
- // so use a delay threshold of -1 to simulate a long recheck (so that any
- // amount of time is considered excessive), and a very large threshold to
- // simulate a short recheck.
- Preferences.set("captivedetect.portalRecheckDelayMS", aLongRecheck ? -1 : 1000000);
-
- if (!win) {
- win = yield BrowserTestUtils.openNewBrowserWindow();
- }
- yield SimpleTest.promiseFocus(win);
-
- // After a new window is opened, CaptivePortalWatcher asks for a recheck, and
- // waits for it to complete. We need to manually tell it a recheck completed.
- yield BrowserTestUtils.waitForCondition(() => {
- return win.CaptivePortalWatcher._waitingForRecheck;
- }, "Waiting for CaptivePortalWatcher to trigger a recheck.");
- Services.obs.notifyObservers(null, "captive-portal-check-complete", null);
-
- let notification = ensurePortalNotification(win);
-
- if (aLongRecheck) {
- ensureNoPortalTab(win);
- testShowLoginPageButtonVisibility(notification, "visible");
- return win;
- }
-
- let tab = win.gBrowser.tabs[1];
- if (tab.linkedBrowser.currentURI.spec != CANONICAL_URL) {
- // The tab should load the canonical URL, wait for it.
- yield BrowserTestUtils.waitForLocationChange(win.gBrowser, CANONICAL_URL);
- }
- is(win.gBrowser.selectedTab, tab,
- "The captive portal tab should be open and selected in the new window.");
- testShowLoginPageButtonVisibility(notification, "hidden");
- return win;
-}
-
-function ensurePortalTab(win) {
- // For the tests that call this function, it's enough to ensure there
- // are two tabs in the window - the default tab and the portal tab.
- is(win.gBrowser.tabs.length, 2,
- "There should be a captive portal tab in the window.");
-}
-
-function ensurePortalNotification(win) {
- let notificationBox =
- win.document.getElementById("high-priority-global-notificationbox");
- let notification = notificationBox.getNotificationWithValue(PORTAL_NOTIFICATION_VALUE)
- isnot(notification, null,
- "There should be a captive portal notification in the window.");
- return notification;
-}
-
-// Helper to test whether the "Show Login Page" is visible in the captive portal
-// notification (it should be hidden when the portal tab is selected).
-function testShowLoginPageButtonVisibility(notification, visibility) {
- let showLoginPageButton = notification.querySelector("button.notification-button");
- // If the visibility property was never changed from default, it will be
- // an empty string, so we pretend it's "visible" (effectively the same).
- is(showLoginPageButton.style.visibility || "visible", visibility,
- "The \"Show Login Page\" button should be " + visibility + ".");
-}
-
-function ensureNoPortalTab(win) {
- is(win.gBrowser.tabs.length, 1,
- "There should be no captive portal tab in the window.");
-}
-
-function ensureNoPortalNotification(win) {
- let notificationBox =
- win.document.getElementById("high-priority-global-notificationbox");
- is(notificationBox.getNotificationWithValue(PORTAL_NOTIFICATION_VALUE), null,
- "There should be no captive portal notification in the window.");
-}
-
-/**
- * Some tests open a new window and close it later. When the window is closed,
- * the original window opened by mochitest gains focus, generating a
- * xul-window-visible notification. If the next test also opens a new window
- * before this notification has a chance to fire, CaptivePortalWatcher picks
- * up the first one instead of the one from the new window. To avoid this
- * unfortunate intermittent timing issue, we wait for the notification from
- * the original window every time we close a window that we opened.
- */
-function waitForXulWindowVisible() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observe() {
- Services.obs.removeObserver(observe, "xul-window-visible");
- resolve();
- }, "xul-window-visible", false);
- });
-}
-
-function* closeWindowAndWaitForXulWindowVisible(win) {
- let p = waitForXulWindowVisible();
- yield BrowserTestUtils.closeWindow(win);
- yield p;
-}
-
-/**
- * BrowserTestUtils.openNewBrowserWindow() does not guarantee the newly
- * opened window has received focus when the promise resolves, so we
- * have to manually wait every time.
- */
-function* openWindowAndWaitForFocus() {
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield SimpleTest.promiseFocus(win);
- return win;
-}
-
-function waitForCertErrorLoad(browser) {
- return new Promise(resolve => {
- info("Waiting for DOMContentLoaded event");
- browser.addEventListener("DOMContentLoaded", function load() {
- browser.removeEventListener("DOMContentLoaded", load, false, true);
- resolve();
- }, false, true);
- });
-}
diff --git a/browser/base/content/test/chrome/.eslintrc.js b/browser/base/content/test/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/browser/base/content/test/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/chrome/chrome.ini b/browser/base/content/test/chrome/chrome.ini
deleted file mode 100644
index 15035fc0c..000000000
--- a/browser/base/content/test/chrome/chrome.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_aboutCrashed.xul]
diff --git a/browser/base/content/test/chrome/test_aboutCrashed.xul b/browser/base/content/test/chrome/test_aboutCrashed.xul
deleted file mode 100644
index 7a68076f1..000000000
--- a/browser/base/content/test/chrome/test_aboutCrashed.xul
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <iframe type="content" id="frame1"/>
- <iframe type="content" id="frame2" onload="doTest()"/>
- <script type="application/javascript"><![CDATA[
- const Ci = Components.interfaces;
- const Cu = Components.utils;
-
- Cu.import("resource://gre/modules/Services.jsm");
- Cu.import("resource://gre/modules/Task.jsm");
- Cu.import("resource://gre/modules/Promise.jsm");
- Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
- SimpleTest.waitForExplicitFinish();
-
- // Load error pages do not fire "load" events, so let's use a progressListener.
- function waitForErrorPage(frame) {
- let errorPageDeferred = Promise.defer();
-
- let progressListener = {
- onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
- if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) {
- frame.docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebProgress)
- .removeProgressListener(progressListener,
- Ci.nsIWebProgress.NOTIFY_LOCATION);
-
- errorPageDeferred.resolve();
- }
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
- Ci.nsISupportsWeakReference])
- };
-
- frame.docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebProgress)
- .addProgressListener(progressListener,
- Ci.nsIWebProgress.NOTIFY_LOCATION);
-
- return errorPageDeferred.promise;
- }
-
- function doTest() {
- Task.spawn(function test_aboutCrashed() {
- let frame1 = document.getElementById("frame1");
- let frame2 = document.getElementById("frame2");
- let uri1 = Services.io.newURI("http://www.example.com/1", null, null);
- let uri2 = Services.io.newURI("http://www.example.com/2", null, null);
-
- let errorPageReady = waitForErrorPage(frame1);
- frame1.docShell.chromeEventHandler.setAttribute("crashedPageTitle", "pageTitle");
- frame1.docShell.displayLoadError(Components.results.NS_ERROR_CONTENT_CRASHED, uri1, null);
-
- yield errorPageReady;
- frame1.docShell.chromeEventHandler.removeAttribute("crashedPageTitle");
-
- SimpleTest.is(frame1.contentDocument.documentURI,
- "about:tabcrashed?e=tabcrashed&u=http%3A//www.example.com/1&c=UTF-8&f=regular&d=pageTitle",
- "Correct about:tabcrashed displayed for page with title.");
-
- errorPageReady = waitForErrorPage(frame2);
- frame2.docShell.displayLoadError(Components.results.NS_ERROR_CONTENT_CRASHED, uri2, null);
-
- yield errorPageReady;
-
- SimpleTest.is(frame2.contentDocument.documentURI,
- "about:tabcrashed?e=tabcrashed&u=http%3A//www.example.com/2&c=UTF-8&f=regular&d=%20",
- "Correct about:tabcrashed displayed for page with no title.");
-
- SimpleTest.finish();
- });
- }
- ]]></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" style="height: 300px; overflow: auto;" />
-</window>
diff --git a/browser/base/content/test/general/.eslintrc.js b/browser/base/content/test/general/.eslintrc.js
deleted file mode 100644
index 11abd6140..000000000
--- a/browser/base/content/test/general/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js",
- "../../../../../testing/mochitest/mochitest.eslintrc.js",
- ]
-};
diff --git a/browser/base/content/test/general/POSTSearchEngine.xml b/browser/base/content/test/general/POSTSearchEngine.xml
deleted file mode 100644
index 30567d92f..000000000
--- a/browser/base/content/test/general/POSTSearchEngine.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
- <ShortName>POST Search</ShortName>
- <Url type="text/html" method="POST" template="http://mochi.test:8888/browser/browser/base/content/test/general/print_postdata.sjs">
- <Param name="searchterms" value="{searchTerms}"/>
- </Url>
-</OpenSearchDescription>
diff --git a/browser/base/content/test/general/aboutHome_content_script.js b/browser/base/content/test/general/aboutHome_content_script.js
deleted file mode 100644
index 28d0e617e..000000000
--- a/browser/base/content/test/general/aboutHome_content_script.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-addMessageListener("AboutHome:SearchTriggered", function (msg) {
- sendAsyncMessage("AboutHomeTest:CheckRecordedSearch", msg.data);
-});
diff --git a/browser/base/content/test/general/accounts_testRemoteCommands.html b/browser/base/content/test/general/accounts_testRemoteCommands.html
deleted file mode 100644
index 517317aff..000000000
--- a/browser/base/content/test/general/accounts_testRemoteCommands.html
+++ /dev/null
@@ -1,83 +0,0 @@
-<html>
- <head>
- <meta charset="utf-8">
-
-<script type="text/javascript;version=1.8">
-
-function init() {
- window.addEventListener("message", function process(e) {doTest(e)}, false);
- // unless we relinquish the eventloop,
- // tests will run before the chrome event handlers are ready
- setTimeout(doTest, 0);
-}
-
-function checkStatusValue(payload, expectedValue) {
- return payload.status == expectedValue;
-}
-
-let tests = [
-{
- info: "Check account log in",
- event: "login",
- data: {
- email: "foo@example.com",
- uid: "1234@lcip.org",
- assertion: "foobar",
- sessionToken: "dead",
- kA: "beef",
- kB: "cafe",
- verified: true
- },
- payloadType: "message",
- validateResponse: function(payload) {
- return checkStatusValue(payload, "login");
- },
-},
-];
-
-let currentTest = -1;
-function doTest(evt) {
- if (evt) {
- if (currentTest < 0 || !evt.data.content)
- return; // not yet testing
-
- let test = tests[currentTest];
- if (evt.data.type != test.payloadType)
- return; // skip unrequested events
-
- let error = JSON.stringify(evt.data.content);
- let pass = false;
- try {
- pass = test.validateResponse(evt.data.content)
- } catch (e) {}
- reportResult(test.info, pass, error);
- }
- // start the next test if there are any left
- if (tests[++currentTest])
- sendToBrowser(tests[currentTest].event, tests[currentTest].data);
- else
- reportFinished();
-}
-
-function reportResult(info, pass, error) {
- let data = {type: "testResult", info: info, pass: pass, error: error};
- let event = new CustomEvent("FirefoxAccountsTestResponse", {detail: {data: data}, bubbles: true});
- document.dispatchEvent(event);
-}
-
-function reportFinished(cmd) {
- let data = {type: "testsComplete", count: tests.length};
- let event = new CustomEvent("FirefoxAccountsTestResponse", {detail: {data: data}, bubbles: true});
- document.dispatchEvent(event);
-}
-
-function sendToBrowser(type, data) {
- let event = new CustomEvent("FirefoxAccountsCommand", {detail: {command: type, data: data}, bubbles: true});
- document.dispatchEvent(event);
-}
-
-</script>
- </head>
- <body onload="init()">
- </body>
-</html>
diff --git a/browser/base/content/test/general/alltabslistener.html b/browser/base/content/test/general/alltabslistener.html
deleted file mode 100644
index 166c31037..000000000
--- a/browser/base/content/test/general/alltabslistener.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
-<head>
-<title>Test page for bug 463387</title>
-</head>
-<body>
-<p>Test page for bug 463387</p>
-</body>
-</html>
diff --git a/browser/base/content/test/general/app_bug575561.html b/browser/base/content/test/general/app_bug575561.html
deleted file mode 100644
index a60c7c87e..000000000
--- a/browser/base/content/test/general/app_bug575561.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=575561
--->
- <head>
- <title>Test for links in app tabs</title>
- </head>
- <body>
- <a href="http://example.com/browser/browser/base/content/test/general/dummy_page.html">same domain</a>
- <a href="http://test1.example.com/browser/browser/base/content/test/general/dummy_page.html">same domain (different subdomain)</a>
- <a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html">different domain</a>
- <a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html" target="foo">different domain (with target)</a>
- <a href="http://www.example.com/browser/browser/base/content/test/general/dummy_page.html">same domain (www prefix)</a>
- <a href="data:text/html,<!DOCTYPE html><html><body>Another Page</body></html>">data: URI</a>
- <iframe src="app_subframe_bug575561.html"></iframe>
- </body>
-</html>
diff --git a/browser/base/content/test/general/app_subframe_bug575561.html b/browser/base/content/test/general/app_subframe_bug575561.html
deleted file mode 100644
index 8690497ff..000000000
--- a/browser/base/content/test/general/app_subframe_bug575561.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=575561
--->
- <head>
- <title>Test for links in app tab subframes</title>
- </head>
- <body>
- <a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html">different domain</a>
- </body>
-</html>
diff --git a/browser/base/content/test/general/audio.ogg b/browser/base/content/test/general/audio.ogg
deleted file mode 100644
index 477544875..000000000
--- a/browser/base/content/test/general/audio.ogg
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/benignPage.html b/browser/base/content/test/general/benignPage.html
deleted file mode 100644
index 8e9429acd..000000000
--- a/browser/base/content/test/general/benignPage.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<!-- 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/. -->
-<html dir="ltr" xml:lang="en-US" lang="en-US">
- <head>
- <meta charset="utf8">
- </head>
- <body>
- <iframe src="http://not-tracking.example.com/"></iframe>
- </body>
-</html>
diff --git a/browser/base/content/test/general/browser.ini b/browser/base/content/test/general/browser.ini
deleted file mode 100644
index 96e591ffe..000000000
--- a/browser/base/content/test/general/browser.ini
+++ /dev/null
@@ -1,494 +0,0 @@
-[DEFAULT]
-support-files =
- POSTSearchEngine.xml
- accounts_testRemoteCommands.html
- alltabslistener.html
- app_bug575561.html
- app_subframe_bug575561.html
- aboutHome_content_script.js
- audio.ogg
- browser_bug479408_sample.html
- browser_bug678392-1.html
- browser_bug678392-2.html
- browser_bug970746.xhtml
- browser_fxa_oauth.html
- browser_fxa_oauth_with_keys.html
- browser_fxa_web_channel.html
- browser_registerProtocolHandler_notification.html
- browser_star_hsts.sjs
- browser_tab_dragdrop2_frame1.xul
- browser_web_channel.html
- browser_web_channel_iframe.html
- bug1262648_string_with_newlines.dtd
- bug592338.html
- bug792517-2.html
- bug792517.html
- bug792517.sjs
- bug839103.css
- clipboard_pastefile.html
- contextmenu_common.js
- ctxmenu-image.png
- discovery.html
- download_page.html
- dummy_page.html
- feed_tab.html
- file_generic_favicon.ico
- file_with_favicon.html
- file_bug822367_1.html
- file_bug822367_1.js
- file_bug822367_2.html
- file_bug822367_3.html
- file_bug822367_4.html
- file_bug822367_4.js
- file_bug822367_4B.html
- file_bug822367_5.html
- file_bug822367_6.html
- file_bug902156.js
- file_bug902156_1.html
- file_bug902156_2.html
- file_bug902156_3.html
- file_bug906190_1.html
- file_bug906190_2.html
- file_bug906190_3_4.html
- file_bug906190_redirected.html
- file_bug906190.js
- file_bug906190.sjs
- file_mediaPlayback.html
- file_mixedContentFromOnunload.html
- file_mixedContentFromOnunload_test1.html
- file_mixedContentFromOnunload_test2.html
- file_mixedContentFramesOnHttp.html
- file_mixedPassiveContent.html
- file_bug970276_popup1.html
- file_bug970276_popup2.html
- file_bug970276_favicon1.ico
- file_bug970276_favicon2.ico
- file_documentnavigation_frameset.html
- file_double_close_tab.html
- file_favicon_change.html
- file_favicon_change_not_in_document.html
- file_fullscreen-window-open.html
- head.js
- healthreport_pingData.js
- healthreport_testRemoteCommands.html
- moz.png
- navigating_window_with_download.html
- offlineQuotaNotification.cacheManifest
- offlineQuotaNotification.html
- page_style_sample.html
- parsingTestHelpers.jsm
- pinning_headers.sjs
- ssl_error_reports.sjs
- print_postdata.sjs
- searchSuggestionEngine.sjs
- searchSuggestionEngine.xml
- searchSuggestionEngine2.xml
- subtst_contextmenu.html
- subtst_contextmenu_input.html
- subtst_contextmenu_xul.xul
- test-mixedcontent-securityerrors.html
- test_bug435035.html
- test_bug462673.html
- test_bug628179.html
- test_bug839103.html
- test_bug959531.html
- test_process_flags_chrome.html
- title_test.svg
- unknownContentType_file.pif
- unknownContentType_file.pif^headers^
- video.ogg
- web_video.html
- web_video1.ogv
- web_video1.ogv^headers^
- zoom_test.html
- test_no_mcb_on_http_site_img.html
- test_no_mcb_on_http_site_img.css
- test_no_mcb_on_http_site_font.html
- test_no_mcb_on_http_site_font.css
- test_no_mcb_on_http_site_font2.html
- test_no_mcb_on_http_site_font2.css
- test_mcb_redirect.html
- test_mcb_redirect_image.html
- test_mcb_double_redirect_image.html
- test_mcb_redirect.js
- test_mcb_redirect.sjs
- file_bug1045809_1.html
- file_bug1045809_2.html
- file_csp_block_all_mixedcontent.html
- file_csp_block_all_mixedcontent.js
- !/image/test/mochitest/blue.png
- !/toolkit/components/passwordmgr/test/browser/form_basic.html
- !/toolkit/components/passwordmgr/test/browser/insecure_test.html
- !/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html
- !/toolkit/content/tests/browser/common/mockTransfer.js
- !/toolkit/modules/tests/browser/metadata_*.html
- !/toolkit/mozapps/extensions/test/xpinstall/amosigned.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/corrupt.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/incompatible.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/installtrigger.html
- !/toolkit/mozapps/extensions/test/xpinstall/redirect.sjs
- !/toolkit/mozapps/extensions/test/xpinstall/restartless-unsigned.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/restartless.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/theme.xpi
- !/toolkit/mozapps/extensions/test/xpinstall/slowinstall.sjs
-
-[browser_aboutAccounts.js]
-skip-if = os == "linux" # Bug 958026
-support-files =
- content_aboutAccounts.js
-[browser_aboutCertError.js]
-[browser_aboutNetError.js]
-[browser_aboutSupport_newtab_security_state.js]
-[browser_aboutHealthReport.js]
-skip-if = os == "linux" # Bug 924307
-[browser_aboutHome.js]
-[browser_aboutHome_wrapsCorrectly.js]
-[browser_addKeywordSearch.js]
-[browser_alltabslistener.js]
-[browser_audioTabIcon.js]
-tags = audiochannel
-[browser_backButtonFitts.js]
-skip-if = os == "mac" # The Fitt's Law back button is not supported on OS X
-[browser_beforeunload_duplicate_dialogs.js]
-[browser_blob-channelname.js]
-[browser_bookmark_popup.js]
-skip-if = (os == "linux" && debug) # mouseover not reliable on linux debug builds
-[browser_bookmark_titles.js]
-skip-if = toolkit == "windows" # Disabled on Windows due to frequent failures (bugs 825739, 841341)
-[browser_bug321000.js]
-subsuite = clipboard
-skip-if = true # browser_bug321000.js is disabled because newline handling is shaky (bug 592528)
-[browser_bug356571.js]
-[browser_bug380960.js]
-[browser_bug386835.js]
-[browser_bug406216.js]
-[browser_bug408415.js]
-[browser_bug409481.js]
-[browser_bug409624.js]
-[browser_bug413915.js]
-[browser_bug416661.js]
-[browser_bug417483.js]
-[browser_bug419612.js]
-[browser_bug422590.js]
-[browser_bug423833.js]
-skip-if = true # bug 428712
-[browser_bug424101.js]
-[browser_bug427559.js]
-[browser_bug431826.js]
-[browser_bug432599.js]
-[browser_bug435035.js]
-[browser_bug435325.js]
-[browser_bug441778.js]
-[browser_bug455852.js]
-[browser_bug460146.js]
-[browser_bug462289.js]
-skip-if = toolkit == "cocoa"
-[browser_bug462673.js]
-[browser_bug477014.js]
-[browser_bug479408.js]
-[browser_bug481560.js]
-[browser_bug484315.js]
-[browser_bug491431.js]
-[browser_bug495058.js]
-[browser_bug517902.js]
-skip-if = (os == 'linux' && e10s) # bug 1161699
-[browser_bug519216.js]
-[browser_bug520538.js]
-[browser_bug521216.js]
-[browser_bug533232.js]
-[browser_bug537013.js]
-subsuite = clipboard
-skip-if = e10s # Bug 1134458 - Find bar doesn't work correctly in a detached tab
-[browser_bug537474.js]
-[browser_bug550565.js]
-[browser_bug553455.js]
-[browser_bug555224.js]
-[browser_bug555767.js]
-[browser_bug559991.js]
-[browser_bug561636.js]
-skip-if = true # bug 1057615
-[browser_bug563588.js]
-[browser_bug565575.js]
-[browser_bug567306.js]
-subsuite = clipboard
-[browser_bug1261299.js]
-subsuite = clipboard
-skip-if = toolkit != "cocoa" # Because of tests for supporting Service Menu of macOS, bug 1261299
-[browser_bug1297539.js]
-skip-if = toolkit != "cocoa" # Because of tests for supporting pasting from Service Menu of macOS, bug 1297539
-[browser_bug575561.js]
-[browser_bug575830.js]
-[browser_bug577121.js]
-[browser_bug578534.js]
-[browser_bug579872.js]
-[browser_bug580638.js]
-[browser_bug580956.js]
-[browser_bug581242.js]
-[browser_bug581253.js]
-[browser_bug585558.js]
-[browser_bug585785.js]
-[browser_bug585830.js]
-[browser_bug590206.js]
-[browser_bug592338.js]
-[browser_bug594131.js]
-[browser_bug595507.js]
-skip-if = true # bug 1057615
-[browser_bug596687.js]
-[browser_bug597218.js]
-[browser_bug609700.js]
-[browser_bug623893.js]
-[browser_bug624734.js]
-[browser_bug633691.js]
-[browser_bug647886.js]
-[browser_bug655584.js]
-[browser_bug664672.js]
-[browser_bug676619.js]
-skip-if = os == "mac" # mac: Intermittent failures, bug 925225
-[browser_bug678392.js]
-skip-if = os == "mac" # Bug 1102331 - does focus things on the content window which break in e10s mode (still causes orange on Mac 10.10)
-[browser_bug710878.js]
-[browser_bug719271.js]
-[browser_bug724239.js]
-[browser_bug734076.js]
-[browser_bug735471.js]
-[browser_bug749738.js]
-[browser_bug763468_perwindowpb.js]
-[browser_bug767836_perwindowpb.js]
-[browser_bug817947.js]
-[browser_bug822367.js]
-tags = mcb
-[browser_bug832435.js]
-[browser_bug839103.js]
-[browser_bug882977.js]
-[browser_bug902156.js]
-tags = mcb
-[browser_bug906190.js]
-tags = mcb
-[browser_mixedContentFromOnunload.js]
-tags = mcb
-[browser_mixedContentFramesOnHttp.js]
-tags = mcb
-[browser_bug970746.js]
-[browser_bug1015721.js]
-skip-if = os == 'win'
-[browser_bug1064280_changeUrlInPinnedTab.js]
-[browser_accesskeys.js]
-[browser_clipboard.js]
-subsuite = clipboard
-[browser_clipboard_pastefile.js]
-skip-if = true # Disabled due to the clipboard not supporting real file types yet (bug 1288773)
-[browser_contentAreaClick.js]
-skip-if = e10s # Clicks in content don't go through contentAreaClick with e10s.
-[browser_contentAltClick.js]
-[browser_contextmenu.js]
-subsuite = clipboard
-tags = fullscreen
-skip-if = toolkit == "gtk2" || toolkit == "gtk3" # disabled on Linux due to bug 513558
-[browser_contextmenu_input.js]
-skip-if = toolkit == "gtk2" || toolkit == "gtk3" # disabled on Linux due to bug 513558
-[browser_ctrlTab.js]
-[browser_datachoices_notification.js]
-skip-if = !datareporting
-[browser_decoderDoctor.js]
-skip-if = os == "mac" # decoder doctor isn't implemented on osx
-[browser_devedition.js]
-[browser_discovery.js]
-[browser_double_close_tab.js]
-[browser_documentnavigation.js]
-[browser_duplicateIDs.js]
-[browser_drag.js]
-skip-if = true # browser_drag.js is disabled, as it needs to be updated for the new behavior from bug 320638.
-[browser_favicon_change.js]
-[browser_favicon_change_not_in_document.js]
-[browser_findbarClose.js]
-[browser_focusonkeydown.js]
-[browser_fullscreen-window-open.js]
-tags = fullscreen
-skip-if = os == "linux" # Linux: Intermittent failures - bug 941575.
-[browser_fxaccounts.js]
-support-files = fxa_profile_handler.sjs
-[browser_fxa_migrate.js]
-[browser_fxa_oauth.js]
-[browser_fxa_web_channel.js]
-[browser_gestureSupport.js]
-skip-if = e10s # Bug 863514 - no gesture support.
-[browser_getshortcutoruri.js]
-[browser_hide_removing.js]
-[browser_homeDrop.js]
-[browser_identity_UI.js]
-[browser_insecureLoginForms.js]
-support-files = insecure_opener.html
-[browser_invalid_uri_back_forward_manipulation.js]
-[browser_keywordBookmarklets.js]
-[browser_keywordSearch.js]
-[browser_keywordSearch_postData.js]
-[browser_lastAccessedTab.js]
-skip-if = toolkit == "windows" # Disabled on Windows due to frequent failures (bug 969405)
-[browser_menuButtonFitts.js]
-skip-if = os != "win" # The Fitts Law menu button is only supported on Windows (bug 969376)
-[browser_middleMouse_noJSPaste.js]
-subsuite = clipboard
-[browser_minimize.js]
-[browser_misused_characters_in_strings.js]
-[browser_mixed_content_cert_override.js]
-[browser_mixedcontent_securityflags.js]
-tags = mcb
-[browser_modifiedclick_inherit_principal.js]
-[browser_offlineQuotaNotification.js]
-skip-if = os == "linux" && !debug # bug 1304273
-[browser_feed_discovery.js]
-support-files = feed_discovery.html
-[browser_gZipOfflineChild.js]
-support-files = test_offline_gzip.html gZipOfflineChild.cacheManifest gZipOfflineChild.cacheManifest^headers^ gZipOfflineChild.html gZipOfflineChild.html^headers^
-[browser_overflowScroll.js]
-[browser_pageInfo.js]
-[browser_pageinfo_svg_image.js]
-support-files =
- svg_image.html
-[browser_page_style_menu.js]
-[browser_page_style_menu_update.js]
-[browser_parsable_css.js]
-skip-if = (debug || asan) # no point in running on both opt and debug, and will likely intermittently timeout on debug
-[browser_parsable_script.js]
-skip-if = asan || (os == 'linux' && !debug && (bits == 32)) # disabled on asan because of timeouts, and bug 1172468 for the linux 32-bit pgo issue.
-[browser_permissions.js]
-support-files =
- permissions.html
-[browser_pinnedTabs.js]
-[browser_plainTextLinks.js]
-[browser_printpreview.js]
-[browser_private_browsing_window.js]
-[browser_private_no_prompt.js]
-[browser_purgehistory_clears_sh.js]
-[browser_PageMetaData_pushstate.js]
-[browser_refreshBlocker.js]
-support-files =
- refresh_header.sjs
- refresh_meta.sjs
-[browser_relatedTabs.js]
-[browser_remoteTroubleshoot.js]
-support-files =
- test_remoteTroubleshoot.html
-[browser_remoteWebNavigation_postdata.js]
-[browser_removeTabsToTheEnd.js]
-[browser_restore_isAppTab.js]
-[browser_sanitize-passwordDisabledHosts.js]
-[browser_sanitize-sitepermissions.js]
-[browser_sanitize-timespans.js]
-[browser_sanitizeDialog.js]
-[browser_save_link-perwindowpb.js]
-skip-if = e10s && debug && os == "win" # Bug 1280505
-[browser_save_private_link_perwindowpb.js]
-[browser_save_link_when_window_navigates.js]
-[browser_save_video.js]
-[browser_save_video_frame.js]
-[browser_scope.js]
-[browser_contentSearchUI.js]
-support-files =
- contentSearchUI.html
- contentSearchUI.js
-[browser_selectpopup.js]
-run-if = e10s
-[browser_selectTabAtIndex.js]
-[browser_ssl_error_reports.js]
-[browser_star_hsts.js]
-[browser_subframe_favicons_not_used.js]
-[browser_syncui.js]
-[browser_tab_close_dependent_window.js]
-[browser_tabDrop.js]
-[browser_tabReorder.js]
-[browser_tab_detach_restore.js]
-[browser_tab_drag_drop_perwindow.js]
-[browser_tab_dragdrop.js]
-skip-if = buildapp == 'mulet' || (e10s && (debug || os == 'linux')) # Bug 1312436
-[browser_tab_dragdrop2.js]
-[browser_tabbar_big_widgets.js]
-skip-if = os == "linux" || os == "mac" # No tabs in titlebar on linux
- # Disabled on OS X because of bug 967917
-[browser_tabfocus.js]
-[browser_tabkeynavigation.js]
-skip-if = (os == "mac" && !e10s) # Bug 1237713 - OSX eats keypresses for some reason
-[browser_tabopen_reflows.js]
-[browser_tabs_close_beforeunload.js]
-support-files =
- close_beforeunload_opens_second_tab.html
- close_beforeunload.html
-[browser_tabs_isActive.js]
-[browser_tabs_owner.js]
-[browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js]
-run-if = e10s
-[browser_trackingUI_1.js]
-tags = trackingprotection
-support-files =
- trackingPage.html
- benignPage.html
-[browser_trackingUI_2.js]
-tags = trackingprotection
-support-files =
- trackingPage.html
- benignPage.html
-[browser_trackingUI_3.js]
-tags = trackingprotection
-[browser_trackingUI_4.js]
-tags = trackingprotection
-support-files =
- trackingPage.html
- benignPage.html
-[browser_trackingUI_5.js]
-tags = trackingprotection
-support-files =
- trackingPage.html
-[browser_trackingUI_6.js]
-tags = trackingprotection
-support-files =
- file_trackingUI_6.html
- file_trackingUI_6.js
- file_trackingUI_6.js^headers^
-[browser_trackingUI_telemetry.js]
-tags = trackingprotection
-support-files =
- trackingPage.html
-[browser_typeAheadFind.js]
-[browser_unknownContentType_title.js]
-[browser_unloaddialogs.js]
-[browser_utilityOverlay.js]
-[browser_viewSourceInTabOnViewSource.js]
-[browser_visibleFindSelection.js]
-[browser_visibleTabs.js]
-[browser_visibleTabs_bookmarkAllPages.js]
-skip-if = true # Bug 1005420 - fails intermittently. also with e10s enabled: bizarre problem with hidden tab having _mouseenter called, via _setPositionalAttributes, and tab not being found resulting in 'candidate is undefined'
-[browser_visibleTabs_bookmarkAllTabs.js]
-[browser_visibleTabs_contextMenu.js]
-[browser_visibleTabs_tabPreview.js]
-skip-if = (os == "win" && !debug)
-[browser_web_channel.js]
-[browser_windowopen_reflows.js]
-[browser_zbug569342.js]
-skip-if = e10s || debug # Bug 1094240 - has findbar-related failures
-[browser_registerProtocolHandler_notification.js]
-[browser_no_mcb_on_http_site.js]
-tags = mcb
-[browser_addCertException.js]
-[browser_bug1045809.js]
-tags = mcb
-[browser_e10s_switchbrowser.js]
-[browser_e10s_about_process.js]
-[browser_e10s_chrome_process.js]
-[browser_e10s_javascript.js]
-[browser_blockHPKP.js]
-tags = psm
-[browser_mcb_redirect.js]
-tags = mcb
-[browser_windowactivation.js]
-[browser_contextmenu_childprocess.js]
-[browser_bug963945.js]
-[browser_domFullscreen_fullscreenMode.js]
-tags = fullscreen
-[browser_menuButtonBadgeManager.js]
-[browser_newTabDrop.js]
-[browser_newWindowDrop.js]
-[browser_csp_block_all_mixedcontent.js]
-tags = mcb
-[browser_newwindow_focus.js]
-skip-if = (os == "linux" && !e10s) # Bug 1263254 - Perma fails on Linux without e10s for some reason.
-[browser_bug1299667.js]
diff --git a/browser/base/content/test/general/browser_PageMetaData_pushstate.js b/browser/base/content/test/general/browser_PageMetaData_pushstate.js
deleted file mode 100644
index 6f71c57a3..000000000
--- a/browser/base/content/test/general/browser_PageMetaData_pushstate.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-add_task(function* () {
- let rooturi = "https://example.com/browser/toolkit/modules/tests/browser/";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, rooturi + "metadata_simple.html");
- yield ContentTask.spawn(gBrowser.selectedBrowser, { rooturi }, function* (args) {
- let result = PageMetadata.getData(content.document);
- // Result should have description.
- Assert.equal(result.url, args.rooturi + "metadata_simple.html", "metadata url is correct");
- Assert.equal(result.title, "Test Title", "metadata title is correct");
- Assert.equal(result.description, "A very simple test page", "description is correct");
-
- content.history.pushState({}, "2", "2.html");
- result = PageMetadata.getData(content.document);
- // Result should not have description.
- Assert.equal(result.url, args.rooturi + "2.html", "metadata url is correct");
- Assert.equal(result.title, "Test Title", "metadata title is correct");
- Assert.ok(!result.description, "description is undefined");
-
- Assert.equal(content.document.documentURI, args.rooturi + "2.html",
- "content.document has correct url");
- });
-
- is(gBrowser.currentURI.spec, rooturi + "2.html", "gBrowser has correct url");
-
- gBrowser.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_aboutAccounts.js b/browser/base/content/test/general/browser_aboutAccounts.js
deleted file mode 100644
index fd72a1608..000000000
--- a/browser/base/content/test/general/browser_aboutAccounts.js
+++ /dev/null
@@ -1,499 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: window.location is null");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
- "resource://gre/modules/FxAccounts.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-const CHROME_BASE = "chrome://mochitests/content/browser/browser/base/content/test/general/";
-// Preference helpers.
-var changedPrefs = new Set();
-
-function setPref(name, value) {
- changedPrefs.add(name);
- Services.prefs.setCharPref(name, value);
-}
-
-registerCleanupFunction(function() {
- // Ensure we don't pollute prefs for next tests.
- for (let name of changedPrefs) {
- Services.prefs.clearUserPref(name);
- }
-});
-
-var gTests = [
-{
- desc: "Test the remote commands",
- teardown: function* () {
- gBrowser.removeCurrentTab();
- yield signOut();
- },
- run: function* ()
- {
- setPref("identity.fxaccounts.remote.signup.uri",
- "https://example.com/browser/browser/base/content/test/general/accounts_testRemoteCommands.html");
- let tab = yield promiseNewTabLoadEvent("about:accounts");
- let mm = tab.linkedBrowser.messageManager;
-
- let deferred = Promise.defer();
-
- // We'll get a message when openPrefs() is called, which this test should
- // arrange.
- let promisePrefsOpened = promiseOneMessage(tab, "test:openPrefsCalled");
- let results = 0;
- try {
- mm.addMessageListener("test:response", function responseHandler(msg) {
- let data = msg.data.data;
- if (data.type == "testResult") {
- ok(data.pass, data.info);
- results++;
- } else if (data.type == "testsComplete") {
- is(results, data.count, "Checking number of results received matches the number of tests that should have run");
- mm.removeMessageListener("test:response", responseHandler);
- deferred.resolve();
- }
- });
- } catch (e) {
- ok(false, "Failed to get all commands");
- deferred.reject();
- }
- yield deferred.promise;
- yield promisePrefsOpened;
- }
-},
-{
- desc: "Test action=signin - no user logged in",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* ()
- {
- // When this loads with no user logged-in, we expect the "normal" URL
- const expected_url = "https://example.com/?is_sign_in";
- setPref("identity.fxaccounts.remote.signin.uri", expected_url);
- let [tab, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
- is(url, expected_url, "action=signin got the expected URL");
- // we expect the remote iframe to be shown.
- yield checkVisibilities(tab, {
- stage: false, // parent of 'manage' and 'intro'
- manage: false,
- intro: false, // this is "get started"
- remote: true,
- networkError: false
- });
- }
-},
-{
- desc: "Test action=signin - user logged in",
- teardown: function* () {
- gBrowser.removeCurrentTab();
- yield signOut();
- },
- run: function* ()
- {
- // When this loads with a user logged-in, we expect the normal URL to
- // have been ignored and the "manage" page to be shown.
- const expected_url = "https://example.com/?is_sign_in";
- setPref("identity.fxaccounts.remote.signin.uri", expected_url);
- yield setSignedInUser();
- let tab = yield promiseNewTabLoadEvent("about:accounts?action=signin");
- // about:accounts initializes after fetching the current user from Fxa -
- // so we also request it - by the time we get it we know it should have
- // done its thing.
- yield fxAccounts.getSignedInUser();
- // we expect "manage" to be shown.
- yield checkVisibilities(tab, {
- stage: true, // parent of 'manage' and 'intro'
- manage: true,
- intro: false, // this is "get started"
- remote: false,
- networkError: false
- });
- }
-},
-{
- desc: "Test action=signin - captive portal",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* ()
- {
- const signinUrl = "https://redirproxy.example.com/test";
- setPref("identity.fxaccounts.remote.signin.uri", signinUrl);
- let [tab, ] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
- yield checkVisibilities(tab, {
- stage: true, // parent of 'manage' and 'intro'
- manage: false,
- intro: false, // this is "get started"
- remote: false,
- networkError: true
- });
- }
-},
-{
- desc: "Test action=signin - offline",
- teardown: () => {
- gBrowser.removeCurrentTab();
- BrowserOffline.toggleOfflineStatus();
- },
- run: function* ()
- {
- BrowserOffline.toggleOfflineStatus();
- Services.cache2.clear();
-
- const signinUrl = "https://unknowndomain.cow";
- setPref("identity.fxaccounts.remote.signin.uri", signinUrl);
- let [tab, ] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
- yield checkVisibilities(tab, {
- stage: true, // parent of 'manage' and 'intro'
- manage: false,
- intro: false, // this is "get started"
- remote: false,
- networkError: true
- });
- }
-},
-{
- desc: "Test action=signup - no user logged in",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* ()
- {
- const expected_url = "https://example.com/?is_sign_up";
- setPref("identity.fxaccounts.remote.signup.uri", expected_url);
- let [tab, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signup");
- is(url, expected_url, "action=signup got the expected URL");
- // we expect the remote iframe to be shown.
- yield checkVisibilities(tab, {
- stage: false, // parent of 'manage' and 'intro'
- manage: false,
- intro: false, // this is "get started"
- remote: true,
- networkError: false
- });
- },
-},
-{
- desc: "Test action=signup - user logged in",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* ()
- {
- const expected_url = "https://example.com/?is_sign_up";
- setPref("identity.fxaccounts.remote.signup.uri", expected_url);
- yield setSignedInUser();
- let tab = yield promiseNewTabLoadEvent("about:accounts?action=signup");
- yield fxAccounts.getSignedInUser();
- // we expect "manage" to be shown.
- yield checkVisibilities(tab, {
- stage: true, // parent of 'manage' and 'intro'
- manage: true,
- intro: false, // this is "get started"
- remote: false,
- networkError: false
- });
- },
-},
-{
- desc: "Test action=reauth",
- teardown: function* () {
- gBrowser.removeCurrentTab();
- yield signOut();
- },
- run: function* ()
- {
- const expected_url = "https://example.com/?is_force_auth";
- setPref("identity.fxaccounts.remote.force_auth.uri", expected_url);
-
- yield setSignedInUser();
- let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=reauth");
- // The current user will be appended to the url
- let expected = expected_url + "&email=foo%40example.com";
- is(url, expected, "action=reauth got the expected URL");
- },
-},
-{
- desc: "Test with migrateToDevEdition enabled (success)",
- teardown: function* () {
- gBrowser.removeCurrentTab();
- yield signOut();
- },
- run: function* ()
- {
- let fxAccountsCommon = {};
- Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon);
- const pref = "identity.fxaccounts.migrateToDevEdition";
- changedPrefs.add(pref);
- Services.prefs.setBoolPref(pref, true);
-
- // Create the signedInUser.json file that will be used as the source of
- // migrated user data.
- let signedInUser = {
- version: 1,
- accountData: {
- email: "foo@example.com",
- uid: "1234@lcip.org",
- sessionToken: "dead",
- verified: true
- }
- };
- // We use a sub-dir of the real profile dir as the "pretend" profile dir
- // for this test.
- let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let mockDir = profD.clone();
- mockDir.append("about-accounts-mock-profd");
- mockDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- let fxAccountsStorage = OS.Path.join(mockDir.path, fxAccountsCommon.DEFAULT_STORAGE_FILENAME);
- yield OS.File.writeAtomic(fxAccountsStorage, JSON.stringify(signedInUser));
- info("Wrote file " + fxAccountsStorage);
-
- // this is a little subtle - we load about:robots so we get a non-remote
- // tab, then we send a message which does both (a) load the URL we want and
- // (b) mocks the default profile path used by about:accounts.
- let tab = yield promiseNewTabLoadEvent("about:robots");
- let readyPromise = promiseOneMessage(tab, "test:load-with-mocked-profile-path-response");
-
- let mm = tab.linkedBrowser.messageManager;
- mm.sendAsyncMessage("test:load-with-mocked-profile-path", {
- url: "about:accounts",
- profilePath: mockDir.path,
- });
-
- let response = yield readyPromise;
- // We are expecting the iframe to be on the "force reauth" URL
- let expected = yield fxAccounts.promiseAccountsForceSigninURI();
- is(response.data.url, expected);
-
- let userData = yield fxAccounts.getSignedInUser();
- SimpleTest.isDeeply(userData, signedInUser.accountData, "All account data were migrated");
- // The migration pref will have been switched off by now.
- is(Services.prefs.getBoolPref(pref), false, pref + " got the expected value");
-
- yield OS.File.remove(fxAccountsStorage);
- yield OS.File.removeEmptyDir(mockDir.path);
- },
-},
-{
- desc: "Test with migrateToDevEdition enabled (no user to migrate)",
- teardown: function* () {
- gBrowser.removeCurrentTab();
- yield signOut();
- },
- run: function* ()
- {
- const pref = "identity.fxaccounts.migrateToDevEdition";
- changedPrefs.add(pref);
- Services.prefs.setBoolPref(pref, true);
-
- let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let mockDir = profD.clone();
- mockDir.append("about-accounts-mock-profd");
- mockDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- // but leave it empty, so we don't think a user is logged in.
-
- let tab = yield promiseNewTabLoadEvent("about:robots");
- let readyPromise = promiseOneMessage(tab, "test:load-with-mocked-profile-path-response");
-
- let mm = tab.linkedBrowser.messageManager;
- mm.sendAsyncMessage("test:load-with-mocked-profile-path", {
- url: "about:accounts",
- profilePath: mockDir.path,
- });
-
- let response = yield readyPromise;
- // We are expecting the iframe to be on the "signup" URL
- let expected = yield fxAccounts.promiseAccountsSignUpURI();
- is(response.data.url, expected);
-
- // and expect no signed in user.
- let userData = yield fxAccounts.getSignedInUser();
- is(userData, null);
- // The migration pref should have still been switched off.
- is(Services.prefs.getBoolPref(pref), false, pref + " got the expected value");
- yield OS.File.removeEmptyDir(mockDir.path);
- },
-},
-{
- desc: "Test observers about:accounts",
- teardown: function() {
- gBrowser.removeCurrentTab();
- },
- run: function* () {
- setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/");
- yield setSignedInUser();
- let tab = yield promiseNewTabLoadEvent("about:accounts");
- // sign the user out - the tab should have action=signin
- yield signOut();
- // wait for the new load.
- yield promiseOneMessage(tab, "test:document:load");
- is(tab.linkedBrowser.contentDocument.location.href, "about:accounts?action=signin");
- }
-},
-{
- desc: "Test entrypoint query string, no action, no user logged in",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* () {
- // When this loads with no user logged-in, we expect the "normal" URL
- setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/");
- let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome");
- is(url, "https://example.com/?entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
- },
-},
-{
- desc: "Test entrypoint query string for signin",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* () {
- // When this loads with no user logged-in, we expect the "normal" URL
- const expected_url = "https://example.com/?is_sign_in";
- setPref("identity.fxaccounts.remote.signin.uri", expected_url);
- let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin&entrypoint=abouthome");
- is(url, expected_url + "&entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
- },
-},
-{
- desc: "Test entrypoint query string for signup",
- teardown: () => gBrowser.removeCurrentTab(),
- run: function* () {
- // When this loads with no user logged-in, we expect the "normal" URL
- const sign_up_url = "https://example.com/?is_sign_up";
- setPref("identity.fxaccounts.remote.signup.uri", sign_up_url);
- let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome&action=signup");
- is(url, sign_up_url + "&entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
- },
-},
-{
- desc: "about:accounts URL params should be copied to remote URL params " +
- "when remote URL has no URL params, except for 'action'",
- teardown() {
- gBrowser.removeCurrentTab();
- },
- run: function* () {
- let signupURL = "https://example.com/";
- setPref("identity.fxaccounts.remote.signup.uri", signupURL);
- let queryStr = "email=foo%40example.com&foo=bar&baz=quux";
- let [, url] =
- yield promiseNewTabWithIframeLoadEvent("about:accounts?" + queryStr +
- "&action=action");
- is(url, signupURL + "?" + queryStr, "URL params are copied to signup URL");
- },
-},
-{
- desc: "about:accounts URL params should be copied to remote URL params " +
- "when remote URL already has some URL params, except for 'action'",
- teardown() {
- gBrowser.removeCurrentTab();
- },
- run: function* () {
- let signupURL = "https://example.com/?param";
- setPref("identity.fxaccounts.remote.signup.uri", signupURL);
- let queryStr = "email=foo%40example.com&foo=bar&baz=quux";
- let [, url] =
- yield promiseNewTabWithIframeLoadEvent("about:accounts?" + queryStr +
- "&action=action");
- is(url, signupURL + "&" + queryStr, "URL params are copied to signup URL");
- },
-},
-]; // gTests
-
-function test()
-{
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- for (let testCase of gTests) {
- info(testCase.desc);
- try {
- yield testCase.run();
- } finally {
- yield testCase.teardown();
- }
- }
-
- finish();
- });
-}
-
-function promiseOneMessage(tab, messageName) {
- let mm = tab.linkedBrowser.messageManager;
- let deferred = Promise.defer();
- mm.addMessageListener(messageName, function onmessage(message) {
- mm.removeMessageListener(messageName, onmessage);
- deferred.resolve(message);
- });
- return deferred.promise;
-}
-
-function promiseNewTabLoadEvent(aUrl)
-{
- let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
- let browser = tab.linkedBrowser;
- let mm = browser.messageManager;
-
- // give it an e10s-friendly content script to help with our tests.
- mm.loadFrameScript(CHROME_BASE + "content_aboutAccounts.js", true);
- // and wait for it to tell us about the load.
- return promiseOneMessage(tab, "test:document:load").then(
- () => tab
- );
-}
-
-// Returns a promise which is resolved with the iframe's URL after a new
-// tab is created and the iframe in that tab loads.
-function promiseNewTabWithIframeLoadEvent(aUrl) {
- let deferred = Promise.defer();
- let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
- let browser = tab.linkedBrowser;
- let mm = browser.messageManager;
-
- // give it an e10s-friendly content script to help with our tests.
- mm.loadFrameScript(CHROME_BASE + "content_aboutAccounts.js", true);
- // and wait for it to tell us about the iframe load.
- mm.addMessageListener("test:iframe:load", function onFrameLoad(message) {
- mm.removeMessageListener("test:iframe:load", onFrameLoad);
- deferred.resolve([tab, message.data.url]);
- });
- return deferred.promise;
-}
-
-function checkVisibilities(tab, data) {
- let ids = Object.keys(data);
- let mm = tab.linkedBrowser.messageManager;
- let deferred = Promise.defer();
- mm.addMessageListener("test:check-visibilities-response", function onResponse(message) {
- mm.removeMessageListener("test:check-visibilities-response", onResponse);
- for (let id of ids) {
- is(message.data[id], data[id], "Element '" + id + "' has correct visibility");
- }
- deferred.resolve();
- });
- mm.sendAsyncMessage("test:check-visibilities", {ids: ids});
- return deferred.promise;
-}
-
-// watch out - these will fire observers which if you aren't careful, may
-// interfere with the tests.
-function setSignedInUser(data) {
- if (!data) {
- data = {
- email: "foo@example.com",
- uid: "1234@lcip.org",
- assertion: "foobar",
- sessionToken: "dead",
- kA: "beef",
- kB: "cafe",
- verified: true
- }
- }
- return fxAccounts.setSignedInUser(data);
-}
-
-function signOut() {
- // we always want a "localOnly" signout here...
- return fxAccounts.signOut(true);
-}
diff --git a/browser/base/content/test/general/browser_aboutCertError.js b/browser/base/content/test/general/browser_aboutCertError.js
deleted file mode 100644
index 0e335066c..000000000
--- a/browser/base/content/test/general/browser_aboutCertError.js
+++ /dev/null
@@ -1,409 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// This is testing the aboutCertError page (Bug 1207107).
-
-const GOOD_PAGE = "https://example.com/";
-const BAD_CERT = "https://expired.example.com/";
-const UNKNOWN_ISSUER = "https://self-signed.example.com ";
-const BAD_STS_CERT = "https://badchain.include-subdomains.pinning.example.com:443";
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
-
-add_task(function* checkReturnToAboutHome() {
- info("Loading a bad cert page directly and making sure 'return to previous page' goes to about:home");
- let browser;
- let certErrorLoaded;
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- }, false);
-
- info("Loading and waiting for the cert error");
- yield certErrorLoaded;
-
- is(browser.webNavigation.canGoBack, false, "!webNavigation.canGoBack");
- is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
-
- // Populate the shistory entries manually, since it happens asynchronously
- // and the following tests will be too soon otherwise.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is one shistory entry");
-
- info("Clicking the go back button on about:certerror");
- yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let returnButton = doc.getElementById("returnButton");
- is(returnButton.getAttribute("autofocus"), "true", "returnButton has autofocus");
- returnButton.click();
-
- yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
- });
-
- is(browser.webNavigation.canGoBack, true, "webNavigation.canGoBack");
- is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
- is(gBrowser.currentURI.spec, "about:home", "Went back");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* checkReturnToPreviousPage() {
- info("Loading a bad cert page and making sure 'return to previous page' goes back");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, GOOD_PAGE);
- let browser = gBrowser.selectedBrowser;
-
- info("Loading and waiting for the cert error");
- let certErrorLoaded = waitForCertErrorLoad(browser);
- BrowserTestUtils.loadURI(browser, BAD_CERT);
- yield certErrorLoaded;
-
- is(browser.webNavigation.canGoBack, true, "webNavigation.canGoBack");
- is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
-
- // Populate the shistory entries manually, since it happens asynchronously
- // and the following tests will be too soon otherwise.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 2, "there are two shistory entries");
-
- info("Clicking the go back button on about:certerror");
- yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let returnButton = doc.getElementById("returnButton");
- returnButton.click();
-
- yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
- });
-
- is(browser.webNavigation.canGoBack, false, "!webNavigation.canGoBack");
- is(browser.webNavigation.canGoForward, true, "webNavigation.canGoForward");
- is(gBrowser.currentURI.spec, GOOD_PAGE, "Went back");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* checkBadStsCert() {
- info("Loading a badStsCert and making sure exception button doesn't show up");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, GOOD_PAGE);
- let browser = gBrowser.selectedBrowser;
-
- info("Loading and waiting for the cert error");
- let certErrorLoaded = waitForCertErrorLoad(browser);
- BrowserTestUtils.loadURI(browser, BAD_STS_CERT);
- yield certErrorLoaded;
-
- let exceptionButtonHidden = yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let exceptionButton = doc.getElementById("exceptionDialogButton");
- return exceptionButton.hidden;
- });
- ok(exceptionButtonHidden, "Exception button is hidden");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-const PREF_BLOCKLIST_CLOCK_SKEW_SECONDS = "services.blocklist.clock_skew_seconds";
-
-add_task(function* checkWrongSystemTimeWarning() {
- function* setUpPage() {
- let browser;
- let certErrorLoaded;
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- }, false);
-
- info("Loading and waiting for the cert error");
- yield certErrorLoaded;
-
- return yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let div = doc.getElementById("wrongSystemTimePanel");
- let systemDateDiv = doc.getElementById("wrongSystemTime_systemDate");
- let actualDateDiv = doc.getElementById("wrongSystemTime_actualDate");
- let learnMoreLink = doc.getElementById("learnMoreLink");
-
- return {
- divDisplay: content.getComputedStyle(div).display,
- text: div.textContent,
- systemDate: systemDateDiv.textContent,
- actualDate: actualDateDiv.textContent,
- learnMoreLink: learnMoreLink.href
- };
- });
- }
-
- let formatter = new Intl.DateTimeFormat();
-
- // pretend we have a positively skewed (ahead) system time
- let serverDate = new Date("2015/10/27");
- let serverDateFmt = formatter.format(serverDate);
- let localDateFmt = formatter.format(new Date());
-
- let skew = Math.floor((Date.now() - serverDate.getTime()) / 1000);
- yield new Promise(r => SpecialPowers.pushPrefEnv({set:
- [[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
-
- info("Loading a bad cert page with a skewed clock");
- let message = yield Task.spawn(setUpPage);
-
- isnot(message.divDisplay, "none", "Wrong time message information is visible");
- ok(message.text.includes("because your clock appears to show the wrong time"),
- "Correct error message found");
- ok(message.text.includes("expired.example.com"), "URL found in error message");
- ok(message.systemDate.includes(localDateFmt), "correct local date displayed");
- ok(message.actualDate.includes(serverDateFmt), "correct server date displayed");
- ok(message.learnMoreLink.includes("time-errors"), "time-errors in the Learn More URL");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- // pretend we have a negatively skewed (behind) system time
- serverDate = new Date();
- serverDate.setYear(serverDate.getFullYear() + 1);
- serverDateFmt = formatter.format(serverDate);
-
- skew = Math.floor((Date.now() - serverDate.getTime()) / 1000);
- yield new Promise(r => SpecialPowers.pushPrefEnv({set:
- [[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
-
- info("Loading a bad cert page with a skewed clock");
- message = yield Task.spawn(setUpPage);
-
- isnot(message.divDisplay, "none", "Wrong time message information is visible");
- ok(message.text.includes("because your clock appears to show the wrong time"),
- "Correct error message found");
- ok(message.text.includes("expired.example.com"), "URL found in error message");
- ok(message.systemDate.includes(localDateFmt), "correct local date displayed");
- ok(message.actualDate.includes(serverDateFmt), "correct server date displayed");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- // pretend we only have a slightly skewed system time, four hours
- skew = 60 * 60 * 4;
- yield new Promise(r => SpecialPowers.pushPrefEnv({set:
- [[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
-
- info("Loading a bad cert page with an only slightly skewed clock");
- message = yield Task.spawn(setUpPage);
-
- is(message.divDisplay, "none", "Wrong time message information is not visible");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- // now pretend we have no skewed system time
- skew = 0;
- yield new Promise(r => SpecialPowers.pushPrefEnv({set:
- [[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
-
- info("Loading a bad cert page with no skewed clock");
- message = yield Task.spawn(setUpPage);
-
- is(message.divDisplay, "none", "Wrong time message information is not visible");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* checkAdvancedDetails() {
- info("Loading a bad cert page and verifying the main error and advanced details section");
- let browser;
- let certErrorLoaded;
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- }, false);
-
- info("Loading and waiting for the cert error");
- yield certErrorLoaded;
-
- let message = yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let shortDescText = doc.getElementById("errorShortDescText");
- info("Main error text: " + shortDescText.textContent);
- ok(shortDescText.textContent.includes("expired.example.com"),
- "Should list hostname in error message.");
-
- let advancedButton = doc.getElementById("advancedButton");
- advancedButton.click();
- let el = doc.getElementById("errorCode");
- return { textContent: el.textContent, tagName: el.tagName };
- });
- is(message.textContent, "SEC_ERROR_EXPIRED_CERTIFICATE",
- "Correct error message found");
- is(message.tagName, "a", "Error message is a link");
-
- message = yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let errorCode = doc.getElementById("errorCode");
- errorCode.click();
- let div = doc.getElementById("certificateErrorDebugInformation");
- let text = doc.getElementById("certificateErrorText");
-
- let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
- .getService(Ci.nsISerializationHelper);
- let serializable = docShell.failedChannel.securityInfo
- .QueryInterface(Ci.nsITransportSecurityInfo)
- .QueryInterface(Ci.nsISerializable);
- let serializedSecurityInfo = serhelper.serializeToString(serializable);
- return {
- divDisplay: content.getComputedStyle(div).display,
- text: text.textContent,
- securityInfoAsString: serializedSecurityInfo
- };
- });
- isnot(message.divDisplay, "none", "Debug information is visible");
- ok(message.text.includes(BAD_CERT), "Correct URL found");
- ok(message.text.includes("Certificate has expired"),
- "Correct error message found");
- ok(message.text.includes("HTTP Strict Transport Security: false"),
- "Correct HSTS value found");
- ok(message.text.includes("HTTP Public Key Pinning: false"),
- "Correct HPKP value found");
- let certChain = getCertChain(message.securityInfoAsString);
- ok(message.text.includes(certChain), "Found certificate chain");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* checkAdvancedDetailsForHSTS() {
- info("Loading a bad STS cert page and verifying the advanced details section");
- let browser;
- let certErrorLoaded;
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(BAD_STS_CERT);
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- }, false);
-
- info("Loading and waiting for the cert error");
- yield certErrorLoaded;
-
- let message = yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let advancedButton = doc.getElementById("advancedButton");
- advancedButton.click();
- let ec = doc.getElementById("errorCode");
- let cdl = doc.getElementById("cert_domain_link");
- return {
- ecTextContent: ec.textContent,
- ecTagName: ec.tagName,
- cdlTextContent: cdl.textContent,
- cdlTagName: cdl.tagName
- };
- });
-
- const badStsUri = Services.io.newURI(BAD_STS_CERT, null, null);
- is(message.ecTextContent, "SSL_ERROR_BAD_CERT_DOMAIN",
- "Correct error message found");
- is(message.ecTagName, "a", "Error message is a link");
- const url = badStsUri.prePath.slice(badStsUri.prePath.indexOf(".") + 1);
- is(message.cdlTextContent, url,
- "Correct cert_domain_link contents found");
- is(message.cdlTagName, "a", "cert_domain_link is a link");
-
- message = yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let errorCode = doc.getElementById("errorCode");
- errorCode.click();
- let div = doc.getElementById("certificateErrorDebugInformation");
- let text = doc.getElementById("certificateErrorText");
-
- let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
- .getService(Ci.nsISerializationHelper);
- let serializable = docShell.failedChannel.securityInfo
- .QueryInterface(Ci.nsITransportSecurityInfo)
- .QueryInterface(Ci.nsISerializable);
- let serializedSecurityInfo = serhelper.serializeToString(serializable);
- return {
- divDisplay: content.getComputedStyle(div).display,
- text: text.textContent,
- securityInfoAsString: serializedSecurityInfo
- };
- });
- isnot(message.divDisplay, "none", "Debug information is visible");
- ok(message.text.includes(badStsUri.spec), "Correct URL found");
- ok(message.text.includes("requested domain name does not match the server\u2019s certificate"),
- "Correct error message found");
- ok(message.text.includes("HTTP Strict Transport Security: false"),
- "Correct HSTS value found");
- ok(message.text.includes("HTTP Public Key Pinning: true"),
- "Correct HPKP value found");
- let certChain = getCertChain(message.securityInfoAsString);
- ok(message.text.includes(certChain), "Found certificate chain");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* checkUnknownIssuerLearnMoreLink() {
- info("Loading a cert error for self-signed pages and checking the correct link is shown");
- let browser;
- let certErrorLoaded;
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(UNKNOWN_ISSUER);
- browser = gBrowser.selectedBrowser;
- certErrorLoaded = waitForCertErrorLoad(browser);
- }, false);
-
- info("Loading and waiting for the cert error");
- yield certErrorLoaded;
-
- let href = yield ContentTask.spawn(browser, null, function* () {
- let learnMoreLink = content.document.getElementById("learnMoreLink");
- return learnMoreLink.href;
- });
- ok(href.endsWith("security-error"), "security-error in the Learn More URL");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-function waitForCertErrorLoad(browser) {
- return new Promise(resolve => {
- info("Waiting for DOMContentLoaded event");
- browser.addEventListener("DOMContentLoaded", function load() {
- browser.removeEventListener("DOMContentLoaded", load, false, true);
- resolve();
- }, false, true);
- });
-}
-
-function getCertChain(securityInfoAsString) {
- let certChain = "";
- const serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
- .getService(Ci.nsISerializationHelper);
- let securityInfo = serhelper.deserializeObject(securityInfoAsString);
- securityInfo.QueryInterface(Ci.nsITransportSecurityInfo);
- let certs = securityInfo.failedCertChain.getEnumerator();
- while (certs.hasMoreElements()) {
- let cert = certs.getNext();
- cert.QueryInterface(Ci.nsIX509Cert);
- certChain += getPEMString(cert);
- }
- return certChain;
-}
-
-function getDERString(cert)
-{
- var length = {};
- var derArray = cert.getRawDER(length);
- var derString = '';
- for (var i = 0; i < derArray.length; i++) {
- derString += String.fromCharCode(derArray[i]);
- }
- return derString;
-}
-
-function getPEMString(cert)
-{
- var derb64 = btoa(getDERString(cert));
- // Wrap the Base64 string into lines of 64 characters,
- // with CRLF line breaks (as specified in RFC 1421).
- var wrapped = derb64.replace(/(\S{64}(?!$))/g, "$1\r\n");
- return "-----BEGIN CERTIFICATE-----\r\n"
- + wrapped
- + "\r\n-----END CERTIFICATE-----\r\n";
-}
diff --git a/browser/base/content/test/general/browser_aboutHealthReport.js b/browser/base/content/test/general/browser_aboutHealthReport.js
deleted file mode 100644
index 0be184fb8..000000000
--- a/browser/base/content/test/general/browser_aboutHealthReport.js
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-const CHROME_BASE = "chrome://mochitests/content/browser/browser/base/content/test/general/";
-const HTTPS_BASE = "https://example.com/browser/browser/base/content/test/general/";
-
-const TELEMETRY_LOG_PREF = "toolkit.telemetry.log.level";
-const telemetryOriginalLogPref = Preferences.get(TELEMETRY_LOG_PREF, null);
-
-const originalReportUrl = Services.prefs.getCharPref("datareporting.healthreport.about.reportUrl");
-
-registerCleanupFunction(function() {
- // Ensure we don't pollute prefs for next tests.
- if (telemetryOriginalLogPref) {
- Preferences.set(TELEMETRY_LOG_PREF, telemetryOriginalLogPref);
- } else {
- Preferences.reset(TELEMETRY_LOG_PREF);
- }
-
- try {
- Services.prefs.setCharPref("datareporting.healthreport.about.reportUrl", originalReportUrl);
- Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
- } catch (ex) {}
-});
-
-function fakeTelemetryNow(...args) {
- let date = new Date(...args);
- let scope = {};
- const modules = [
- Cu.import("resource://gre/modules/TelemetrySession.jsm", scope),
- Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", scope),
- Cu.import("resource://gre/modules/TelemetryController.jsm", scope),
- ];
-
- for (let m of modules) {
- m.Policy.now = () => new Date(date);
- }
-
- return date;
-}
-
-function* setupPingArchive() {
- let scope = {};
- Cu.import("resource://gre/modules/TelemetryController.jsm", scope);
- Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript(CHROME_BASE + "healthreport_pingData.js", scope);
-
- for (let p of scope.TEST_PINGS) {
- fakeTelemetryNow(p.date);
- p.id = yield scope.TelemetryController.submitExternalPing(p.type, p.payload);
- }
-}
-
-var gTests = [
-
-{
- desc: "Test the remote commands",
- setup: Task.async(function*()
- {
- Preferences.set(TELEMETRY_LOG_PREF, "Trace");
- yield setupPingArchive();
- Preferences.set("datareporting.healthreport.about.reportUrl",
- HTTPS_BASE + "healthreport_testRemoteCommands.html");
- }),
- run: function (iframe)
- {
- let deferred = Promise.defer();
- let results = 0;
- try {
- iframe.contentWindow.addEventListener("FirefoxHealthReportTestResponse", function evtHandler(event) {
- let data = event.detail.data;
- if (data.type == "testResult") {
- ok(data.pass, data.info);
- results++;
- }
- else if (data.type == "testsComplete") {
- is(results, data.count, "Checking number of results received matches the number of tests that should have run");
- iframe.contentWindow.removeEventListener("FirefoxHealthReportTestResponse", evtHandler, true);
- deferred.resolve();
- }
- }, true);
-
- } catch (e) {
- ok(false, "Failed to get all commands");
- deferred.reject();
- }
- return deferred.promise;
- }
-},
-
-]; // gTests
-
-function test()
-{
- waitForExplicitFinish();
-
- // xxxmpc leaving this here until we resolve bug 854038 and bug 854060
- requestLongerTimeout(10);
-
- Task.spawn(function* () {
- for (let testCase of gTests) {
- info(testCase.desc);
- yield testCase.setup();
-
- let iframe = yield promiseNewTabLoadEvent("about:healthreport");
-
- yield testCase.run(iframe);
-
- gBrowser.removeCurrentTab();
- }
-
- finish();
- });
-}
-
-function promiseNewTabLoadEvent(aUrl, aEventType="load")
-{
- let deferred = Promise.defer();
- let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
- tab.linkedBrowser.addEventListener(aEventType, function load(event) {
- tab.linkedBrowser.removeEventListener(aEventType, load, true);
- let iframe = tab.linkedBrowser.contentDocument.getElementById("remote-report");
- iframe.addEventListener("load", function frameLoad(e) {
- if (iframe.contentWindow.location.href == "about:blank" ||
- e.target != iframe) {
- return;
- }
- iframe.removeEventListener("load", frameLoad, false);
- deferred.resolve(iframe);
- }, false);
- }, true);
- return deferred.promise;
-}
diff --git a/browser/base/content/test/general/browser_aboutHome.js b/browser/base/content/test/general/browser_aboutHome.js
deleted file mode 100644
index f0e19e852..000000000
--- a/browser/base/content/test/general/browser_aboutHome.js
+++ /dev/null
@@ -1,668 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-// This test needs to be split up. See bug 1258717.
-requestLongerTimeout(4);
-ignoreAllUncaughtExceptions();
-
-XPCOMUtils.defineLazyModuleGetter(this, "AboutHomeUtils",
- "resource:///modules/AboutHome.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
- "resource://gre/modules/AppConstants.jsm");
-
-const TEST_CONTENT_HELPER = "chrome://mochitests/content/browser/browser/base/" +
- "content/test/general/aboutHome_content_script.js";
-var gRightsVersion = Services.prefs.getIntPref("browser.rights.version");
-
-registerCleanupFunction(function() {
- // Ensure we don't pollute prefs for next tests.
- Services.prefs.clearUserPref("network.cookies.cookieBehavior");
- Services.prefs.clearUserPref("network.cookie.lifetimePolicy");
- Services.prefs.clearUserPref("browser.rights.override");
- Services.prefs.clearUserPref("browser.rights." + gRightsVersion + ".shown");
-});
-
-add_task(function* () {
- info("Check that clearing cookies does not clear storage");
-
- yield withSnippetsMap(
- () => {
- Cc["@mozilla.org/observer-service;1"]
- .getService(Ci.nsIObserverService)
- .notifyObservers(null, "cookie-changed", "cleared");
- },
- function* () {
- isnot(content.gSnippetsMap.get("snippets-last-update"), null,
- "snippets-last-update should have a value");
- });
-});
-
-add_task(function* () {
- info("Check default snippets are shown");
-
- yield withSnippetsMap(null, function* () {
- let doc = content.document;
- let snippetsElt = doc.getElementById("snippets");
- ok(snippetsElt, "Found snippets element")
- is(snippetsElt.getElementsByTagName("span").length, 1,
- "A default snippet is present.");
- });
-});
-
-add_task(function* () {
- info("Check default snippets are shown if snippets are invalid xml");
-
- yield withSnippetsMap(
- // This must set some incorrect xhtml code.
- snippetsMap => snippetsMap.set("snippets", "<p><b></p></b>"),
- function* () {
- let doc = content.document;
- let snippetsElt = doc.getElementById("snippets");
- ok(snippetsElt, "Found snippets element");
- is(snippetsElt.getElementsByTagName("span").length, 1,
- "A default snippet is present.");
-
- content.gSnippetsMap.delete("snippets");
- });
-});
-
-add_task(function* () {
- info("Check that performing a search fires a search event and records to Telemetry.");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- let currEngine = Services.search.currentEngine;
- let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
- // Make this actually work in healthreport by giving it an ID:
- Object.defineProperty(engine.wrappedJSObject, "identifier",
- { value: "org.mozilla.testsearchsuggestions" });
-
- let p = promiseContentSearchChange(browser, engine.name);
- Services.search.currentEngine = engine;
- yield p;
-
- yield ContentTask.spawn(browser, { expectedName: engine.name }, function* (args) {
- let engineName = content.wrappedJSObject.gContentSearchController.defaultEngine.name;
- is(engineName, args.expectedName, "Engine name in DOM should match engine we just added");
- });
-
- let numSearchesBefore = 0;
- // Get the current number of recorded searches.
- let histogramKey = engine.identifier + ".abouthome";
- try {
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- if (histogramKey in hs) {
- numSearchesBefore = hs[histogramKey].sum;
- }
- } catch (ex) {
- // No searches performed yet, not a problem, |numSearchesBefore| is 0.
- }
-
- let searchStr = "a search";
-
- let expectedURL = Services.search.currentEngine
- .getSubmission(searchStr, null, "homepage").uri.spec;
- let promise = waitForDocLoadAndStopIt(expectedURL, browser);
-
- // Perform a search to increase the SEARCH_COUNT histogram.
- yield ContentTask.spawn(browser, { searchStr }, function* (args) {
- let doc = content.document;
- info("Perform a search.");
- doc.getElementById("searchText").value = args.searchStr;
- doc.getElementById("searchSubmit").click();
- });
-
- yield promise;
-
- // Make sure the SEARCH_COUNTS histogram has the right key and count.
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- Assert.ok(histogramKey in hs, "histogram with key should be recorded");
- Assert.equal(hs[histogramKey].sum, numSearchesBefore + 1,
- "histogram sum should be incremented");
-
- Services.search.currentEngine = currEngine;
- try {
- Services.search.removeEngine(engine);
- } catch (ex) {}
- });
-});
-
-add_task(function* () {
- info("Check snippets map is cleared if cached version is old");
-
- yield withSnippetsMap(
- snippetsMap => {
- snippetsMap.set("snippets", "test");
- snippetsMap.set("snippets-cached-version", 0);
- },
- function* () {
- let snippetsMap = content.gSnippetsMap;
- ok(!snippetsMap.has("snippets"), "snippets have been properly cleared");
- ok(!snippetsMap.has("snippets-cached-version"),
- "cached-version has been properly cleared");
- });
-});
-
-add_task(function* () {
- info("Check cached snippets are shown if cached version is current");
-
- yield withSnippetsMap(
- snippetsMap => snippetsMap.set("snippets", "test"),
- function* (args) {
- let doc = content.document;
- let snippetsMap = content.gSnippetsMap
-
- let snippetsElt = doc.getElementById("snippets");
- ok(snippetsElt, "Found snippets element");
- is(snippetsElt.innerHTML, "test", "Cached snippet is present.");
-
- is(snippetsMap.get("snippets"), "test", "snippets still cached");
- is(snippetsMap.get("snippets-cached-version"),
- args.expectedVersion,
- "cached-version is correct");
- ok(snippetsMap.has("snippets-last-update"), "last-update still exists");
- }, { expectedVersion: AboutHomeUtils.snippetsVersion });
-});
-
-add_task(function* () {
- info("Check if the 'Know Your Rights' default snippet is shown when " +
- "'browser.rights.override' pref is set and that its link works");
-
- Services.prefs.setBoolPref("browser.rights.override", false);
-
- ok(AboutHomeUtils.showKnowYourRights, "AboutHomeUtils.showKnowYourRights should be TRUE");
-
- yield withSnippetsMap(null, function* () {
- let doc = content.document;
- let snippetsElt = doc.getElementById("snippets");
- ok(snippetsElt, "Found snippets element");
- let linkEl = snippetsElt.querySelector("a");
- is(linkEl.href, "about:rights", "Snippet link is present.");
- }, null, function* () {
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:rights");
- yield BrowserTestUtils.synthesizeMouseAtCenter("a[href='about:rights']", {
- button: 0
- }, gBrowser.selectedBrowser);
- yield loadPromise;
- is(gBrowser.currentURI.spec, "about:rights", "about:rights should have opened.");
- });
-
-
- Services.prefs.clearUserPref("browser.rights.override");
-});
-
-add_task(function* () {
- info("Check if the 'Know Your Rights' default snippet is NOT shown when " +
- "'browser.rights.override' pref is NOT set");
-
- Services.prefs.setBoolPref("browser.rights.override", true);
-
- let rightsData = AboutHomeUtils.knowYourRightsData;
- ok(!rightsData, "AboutHomeUtils.knowYourRightsData should be FALSE");
-
- yield withSnippetsMap(null, function*() {
- let doc = content.document;
- let snippetsElt = doc.getElementById("snippets");
- ok(snippetsElt, "Found snippets element");
- ok(snippetsElt.getElementsByTagName("a")[0].href != "about:rights",
- "Snippet link should not point to about:rights.");
- });
-
- Services.prefs.clearUserPref("browser.rights.override");
-});
-
-add_task(function* () {
- info("Check POST search engine support");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- return new Promise(resolve => {
- let searchObserver = Task.async(function* search_observer(subject, topic, data) {
- let currEngine = Services.search.defaultEngine;
- let engine = subject.QueryInterface(Ci.nsISearchEngine);
- info("Observer: " + data + " for " + engine.name);
-
- if (data != "engine-added")
- return;
-
- if (engine.name != "POST Search")
- return;
-
- Services.obs.removeObserver(searchObserver, "browser-search-engine-modified");
-
- // Ready to execute the tests!
- let needle = "Search for something awesome.";
-
- let p = promiseContentSearchChange(browser, engine.name);
- Services.search.defaultEngine = engine;
- yield p;
-
- let promise = BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, { needle }, function* (args) {
- let doc = content.document;
- doc.getElementById("searchText").value = args.needle;
- doc.getElementById("searchSubmit").click();
- });
-
- yield promise;
-
- // When the search results load, check them for correctness.
- yield ContentTask.spawn(browser, { needle }, function* (args) {
- let loadedText = content.document.body.textContent;
- ok(loadedText, "search page loaded");
- is(loadedText, "searchterms=" + escape(args.needle.replace(/\s/g, "+")),
- "Search text should arrive correctly");
- });
-
- Services.search.defaultEngine = currEngine;
- try {
- Services.search.removeEngine(engine);
- } catch (ex) {}
- resolve();
- });
- Services.obs.addObserver(searchObserver, "browser-search-engine-modified", false);
- Services.search.addEngine("http://test:80/browser/browser/base/content/test/general/POSTSearchEngine.xml",
- null, null, false);
- });
- });
-});
-
-add_task(function* () {
- info("Make sure that a page can't imitate about:home");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- let promise = BrowserTestUtils.browserLoaded(browser);
- browser.loadURI("https://example.com/browser/browser/base/content/test/general/test_bug959531.html");
- yield promise;
-
- yield ContentTask.spawn(browser, null, function* () {
- let button = content.document.getElementById("settings");
- ok(button, "Found settings button in test page");
- button.click();
- });
-
- yield new Promise(resolve => {
- // It may take a few turns of the event loop before the window
- // is displayed, so we wait.
- function check(n) {
- let win = Services.wm.getMostRecentWindow("Browser:Preferences");
- ok(!win, "Preferences window not showing");
- if (win) {
- win.close();
- }
-
- if (n > 0) {
- executeSoon(() => check(n-1));
- } else {
- resolve();
- }
- }
-
- check(5);
- });
- });
-});
-
-add_task(function* () {
- // See browser_contentSearchUI.js for comprehensive content search UI tests.
- info("Search suggestion smoke test");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- // Add a test engine that provides suggestions and switch to it.
- let currEngine = Services.search.currentEngine;
- let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
- let p = promiseContentSearchChange(browser, engine.name);
- Services.search.currentEngine = engine;
- yield p;
-
- yield ContentTask.spawn(browser, null, function* () {
- // Avoid intermittent failures.
- content.wrappedJSObject.gContentSearchController.remoteTimeout = 5000;
-
- // Type an X in the search input.
- let input = content.document.getElementById("searchText");
- input.focus();
- });
-
- yield BrowserTestUtils.synthesizeKey("x", {}, browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- // Wait for the search suggestions to become visible.
- let table = content.document.getElementById("searchSuggestionTable");
- let input = content.document.getElementById("searchText");
-
- yield new Promise(resolve => {
- let observer = new content.MutationObserver(() => {
- if (input.getAttribute("aria-expanded") == "true") {
- observer.disconnect();
- ok(!table.hidden, "Search suggestion table unhidden");
- resolve();
- }
- });
- observer.observe(input, {
- attributes: true,
- attributeFilter: ["aria-expanded"],
- });
- });
- });
-
- // Empty the search input, causing the suggestions to be hidden.
- yield BrowserTestUtils.synthesizeKey("a", { accelKey: true }, browser);
- yield BrowserTestUtils.synthesizeKey("VK_DELETE", {}, browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- let table = content.document.getElementById("searchSuggestionTable");
- yield ContentTaskUtils.waitForCondition(() => table.hidden,
- "Search suggestion table hidden");
- });
-
- Services.search.currentEngine = currEngine;
- try {
- Services.search.removeEngine(engine);
- } catch (ex) { }
- });
-});
-
-add_task(function* () {
- info("Clicking suggestion list while composing");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- // Add a test engine that provides suggestions and switch to it.
- let currEngine = Services.search.currentEngine;
- let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
- let p = promiseContentSearchChange(browser, engine.name);
- Services.search.currentEngine = engine;
- yield p;
-
- yield ContentTask.spawn(browser, null, function* () {
- // Start composition and type "x"
- let input = content.document.getElementById("searchText");
- input.focus();
- });
-
- yield BrowserTestUtils.synthesizeComposition({
- type: "compositionstart",
- data: ""
- }, browser);
- yield BrowserTestUtils.synthesizeCompositionChange({
- composition: {
- string: "x",
- clauses: [
- { length: 1, attr: Ci.nsITextInputProcessor.ATTR_RAW_CLAUSE }
- ]
- },
- caret: { start: 1, length: 0 }
- }, browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- let searchController = content.wrappedJSObject.gContentSearchController;
-
- // Wait for the search suggestions to become visible.
- let table = searchController._suggestionsList;
- let input = content.document.getElementById("searchText");
-
- yield new Promise(resolve => {
- let observer = new content.MutationObserver(() => {
- if (input.getAttribute("aria-expanded") == "true") {
- observer.disconnect();
- ok(!table.hidden, "Search suggestion table unhidden");
- resolve();
- }
- });
- observer.observe(input, {
- attributes: true,
- attributeFilter: ["aria-expanded"],
- });
- });
-
- let row = table.children[1];
- row.setAttribute("id", "TEMPID");
-
- // ContentSearchUIController looks at the current selectedIndex when
- // performing a search. Synthesizing the mouse event on the suggestion
- // doesn't actually mouseover the suggestion and trigger it to be flagged
- // as selected, so we manually select it first.
- searchController.selectedIndex = 1;
- });
-
- // Click the second suggestion.
- let expectedURL = Services.search.currentEngine
- .getSubmission("xbar", null, "homepage").uri.spec;
- let loadPromise = waitForDocLoadAndStopIt(expectedURL);
- yield BrowserTestUtils.synthesizeMouseAtCenter("#TEMPID", {
- button: 0
- }, browser);
- yield loadPromise;
-
- yield ContentTask.spawn(browser, null, function* () {
- let input = content.document.getElementById("searchText");
- ok(input.value == "x", "Input value did not change");
-
- let row = content.document.getElementById("TEMPID");
- if (row) {
- row.removeAttribute("id");
- }
- });
-
- Services.search.currentEngine = currEngine;
- try {
- Services.search.removeEngine(engine);
- } catch (ex) { }
- });
-});
-
-add_task(function* () {
- info("Pressing any key should focus the search box in the page, and send the key to it");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- yield BrowserTestUtils.synthesizeMouseAtCenter("#brandLogo", {}, browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- isnot(doc.getElementById("searchText"), doc.activeElement,
- "Search input should not be the active element.");
- });
-
- yield BrowserTestUtils.synthesizeKey("a", {}, browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- let searchInput = doc.getElementById("searchText");
- yield ContentTaskUtils.waitForCondition(() => doc.activeElement === searchInput,
- "Search input should be the active element.");
- is(searchInput.value, "a", "Search input should be 'a'.");
- });
- });
-});
-
-add_task(function* () {
- info("Cmd+k should focus the search box in the toolbar when it's present");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- yield BrowserTestUtils.synthesizeMouseAtCenter("#brandLogo", {}, browser);
-
- let doc = window.document;
- let searchInput = doc.getElementById("searchbar").textbox.inputField;
- isnot(searchInput, doc.activeElement, "Search bar should not be the active element.");
-
- EventUtils.synthesizeKey("k", { accelKey: true });
- yield promiseWaitForCondition(() => doc.activeElement === searchInput);
- is(searchInput, doc.activeElement, "Search bar should be the active element.");
- });
-});
-
-add_task(function* () {
- info("Sync button should open about:preferences#sync");
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- let oldOpenPrefs = window.openPreferences;
- let openPrefsPromise = new Promise(resolve => {
- window.openPreferences = function (pane, params) {
- resolve({ pane: pane, params: params });
- };
- });
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#sync", {}, browser);
-
- let result = yield openPrefsPromise;
- window.openPreferences = oldOpenPrefs;
-
- is(result.pane, "paneSync", "openPreferences should be called with paneSync");
- is(result.params.urlParams.entrypoint, "abouthome",
- "openPreferences should be called with abouthome entrypoint");
- });
-});
-
-add_task(function* () {
- info("Pressing Space while the Addons button is focused should activate it");
-
- // Skip this test on Mac, because Space doesn't activate the button there.
- if (AppConstants.platform == "macosx") {
- return;
- }
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
- info("Waiting for about:addons tab to open...");
- let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:addons");
-
- yield ContentTask.spawn(browser, null, function* () {
- let addOnsButton = content.document.getElementById("addons");
- addOnsButton.focus();
- });
- yield BrowserTestUtils.synthesizeKey(" ", {}, browser);
-
- let tab = yield promiseTabOpened;
- is(tab.linkedBrowser.currentURI.spec, "about:addons",
- "Should have seen the about:addons tab");
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-/**
- * Cleans up snippets and ensures that by default we don't try to check for
- * remote snippets since that may cause network bustage or slowness.
- *
- * @param aSetupFn
- * The setup function to be run.
- * @param testFn
- * the content task to run
- * @param testArgs (optional)
- * the parameters to pass to the content task
- * @param parentFn (optional)
- * the function to run in the parent after the content task has completed.
- * @return {Promise} resolved when the snippets are ready. Gets the snippets map.
- */
-function* withSnippetsMap(setupFn, testFn, testArgs = null, parentFn = null) {
- let setupFnSource;
- if (setupFn) {
- setupFnSource = setupFn.toSource();
- }
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
- let promiseAfterLocationChange = () => {
- return ContentTask.spawn(browser, {
- setupFnSource,
- version: AboutHomeUtils.snippetsVersion,
- }, function* (args) {
- return new Promise(resolve => {
- let document = content.document;
- // We're not using Promise-based listeners, because they resolve asynchronously.
- // The snippets test setup code relies on synchronous behaviour here.
- document.addEventListener("AboutHomeLoadSnippets", function loadSnippets() {
- document.removeEventListener("AboutHomeLoadSnippets", loadSnippets);
-
- let updateSnippets;
- if (args.setupFnSource) {
- updateSnippets = eval(`(() => (${args.setupFnSource}))()`);
- }
-
- content.wrappedJSObject.ensureSnippetsMapThen(snippetsMap => {
- snippetsMap = Cu.waiveXrays(snippetsMap);
- info("Got snippets map: " +
- "{ last-update: " + snippetsMap.get("snippets-last-update") +
- ", cached-version: " + snippetsMap.get("snippets-cached-version") +
- " }");
- // Don't try to update.
- snippetsMap.set("snippets-last-update", Date.now());
- snippetsMap.set("snippets-cached-version", args.version);
- // Clear snippets.
- snippetsMap.delete("snippets");
-
- if (updateSnippets) {
- updateSnippets(snippetsMap);
- }
-
- // Tack it to the global object
- content.gSnippetsMap = snippetsMap;
-
- resolve();
- });
- });
- });
- });
- };
-
- // We'd like to listen to the 'AboutHomeLoadSnippets' event on a fresh
- // document as soon as technically possible, so we use webProgress.
- let promise = new Promise(resolve => {
- let wpl = {
- onLocationChange() {
- gBrowser.removeProgressListener(wpl);
- // Phase 2: retrieving the snippets map is the next promise on our agenda.
- promiseAfterLocationChange().then(resolve);
- },
- onProgressChange() {},
- onStatusChange() {},
- onSecurityChange() {}
- };
- gBrowser.addProgressListener(wpl);
- });
-
- // Set the URL to 'about:home' here to allow capturing the 'AboutHomeLoadSnippets'
- // event.
- browser.loadURI("about:home");
- // Wait for LocationChange.
- yield promise;
-
- yield ContentTask.spawn(browser, testArgs, testFn);
- if (parentFn) {
- yield parentFn();
- }
- });
-}
-
-function promiseContentSearchChange(browser, newEngineName) {
- return ContentTask.spawn(browser, { newEngineName }, function* (args) {
- return new Promise(resolve => {
- content.addEventListener("ContentSearchService", function listener(aEvent) {
- if (aEvent.detail.type == "CurrentState" &&
- content.wrappedJSObject.gContentSearchController.defaultEngine.name == args.newEngineName) {
- content.removeEventListener("ContentSearchService", listener);
- resolve();
- }
- });
- });
- });
-}
-
-function promiseNewEngine(basename) {
- info("Waiting for engine to be added: " + basename);
- return new Promise((resolve, reject) => {
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- registerCleanupFunction(() => {
- try {
- Services.search.removeEngine(engine);
- } catch (ex) { /* Can't remove the engine more than once */ }
- });
- resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- reject();
- },
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_aboutHome_wrapsCorrectly.js b/browser/base/content/test/general/browser_aboutHome_wrapsCorrectly.js
deleted file mode 100644
index bfe0fe9c8..000000000
--- a/browser/base/content/test/general/browser_aboutHome_wrapsCorrectly.js
+++ /dev/null
@@ -1,28 +0,0 @@
-add_task(function* () {
- let newWindow = yield BrowserTestUtils.openNewBrowserWindow();
-
- let resizedPromise = BrowserTestUtils.waitForEvent(newWindow, "resize");
- newWindow.resizeTo(300, 300);
- yield resizedPromise;
-
- yield BrowserTestUtils.openNewForegroundTab(newWindow.gBrowser, "about:home");
-
- yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
- Assert.equal(content.document.body.getAttribute("narrow"), "true", "narrow mode");
- });
-
- resizedPromise = BrowserTestUtils.waitForContentEvent(newWindow.gBrowser.selectedBrowser, "resize");
-
-
- yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
- content.window.resizeTo(800, 800);
- });
-
- yield resizedPromise;
-
- yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
- Assert.equal(content.document.body.hasAttribute("narrow"), false, "non-narrow mode");
- });
-
- yield BrowserTestUtils.closeWindow(newWindow);
-});
diff --git a/browser/base/content/test/general/browser_aboutNetError.js b/browser/base/content/test/general/browser_aboutNetError.js
deleted file mode 100644
index 5185cbcaa..000000000
--- a/browser/base/content/test/general/browser_aboutNetError.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Set ourselves up for TLS error
-Services.prefs.setIntPref("security.tls.version.max", 3);
-Services.prefs.setIntPref("security.tls.version.min", 3);
-
-const LOW_TLS_VERSION = "https://tls1.example.com/";
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
-
-add_task(function* checkReturnToPreviousPage() {
- info("Loading a TLS page that isn't supported, ensure we have a fix button and clicking it then loads the page");
- let browser;
- let pageLoaded;
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- gBrowser.selectedTab = gBrowser.addTab(LOW_TLS_VERSION);
- browser = gBrowser.selectedBrowser;
- pageLoaded = BrowserTestUtils.waitForErrorPage(browser);
- }, false);
-
- info("Loading and waiting for the net error");
- yield pageLoaded;
-
- // NB: This code assumes that the error page and the test page load in the
- // same process. If this test starts to fail, it could be because they load
- // in different processes.
- yield ContentTask.spawn(browser, LOW_TLS_VERSION, function* (LOW_TLS_VERSION_) {
- ok(content.document.getElementById("prefResetButton").getBoundingClientRect().left >= 0,
- "Should have a visible button");
-
- ok(content.document.documentURI.startsWith("about:neterror"), "Should be showing error page");
-
- let doc = content.document;
- let prefResetButton = doc.getElementById("prefResetButton");
- is(prefResetButton.getAttribute("autofocus"), "true", "prefResetButton has autofocus");
- prefResetButton.click();
-
- yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
-
- is(content.document.documentURI, LOW_TLS_VERSION_, "Should not be showing page");
- });
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_aboutSupport_newtab_security_state.js b/browser/base/content/test/general/browser_aboutSupport_newtab_security_state.js
deleted file mode 100644
index e574ba978..000000000
--- a/browser/base/content/test/general/browser_aboutSupport_newtab_security_state.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: window.location is null");
-
-
-add_task(function* checkIdentityOfAboutSupport() {
- let tab = gBrowser.loadOneTab("about:support", {
- referrerURI: null,
- inBackground: false,
- allowThirdPartyFixup: false,
- relatedToCurrent: false,
- skipAnimation: true,
- allowMixedContent: false
- });
-
- yield promiseTabLoaded(tab);
- let identityBox = document.getElementById("identity-box");
- is(identityBox.className, "chromeUI", "Should know that we're chrome.");
- gBrowser.removeTab(tab);
-});
-
diff --git a/browser/base/content/test/general/browser_accesskeys.js b/browser/base/content/test/general/browser_accesskeys.js
deleted file mode 100644
index 56fe3995f..000000000
--- a/browser/base/content/test/general/browser_accesskeys.js
+++ /dev/null
@@ -1,82 +0,0 @@
-add_task(function *() {
- yield pushPrefs(["ui.key.contentAccess", 5], ["ui.key.chromeAccess", 5]);
-
- const gPageURL1 = "data:text/html,<body><p>" +
- "<button id='button' accesskey='y'>Button</button>" +
- "<input id='checkbox' type='checkbox' accesskey='z'>Checkbox" +
- "</p></body>";
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gPageURL1);
- tab1.linkedBrowser.messageManager.loadFrameScript("data:,(" + childHandleFocus.toString() + ")();", false);
-
- Services.focus.clearFocus(window);
-
- // Press an accesskey in the child document while the chrome is focused.
- let focusedId = yield performAccessKey("y");
- is(focusedId, "button", "button accesskey");
-
- // Press an accesskey in the child document while the content document is focused.
- focusedId = yield performAccessKey("z");
- is(focusedId, "checkbox", "checkbox accesskey");
-
- // Add an element with an accesskey to the chrome and press its accesskey while the chrome is focused.
- let newButton = document.createElement("button");
- newButton.id = "chromebutton";
- newButton.setAttribute("accesskey", "z");
- document.documentElement.appendChild(newButton);
-
- Services.focus.clearFocus(window);
-
- focusedId = yield performAccessKeyForChrome("z");
- is(focusedId, "chromebutton", "chromebutton accesskey");
-
- // Add a second tab and ensure that accesskey from the first tab is not used.
- const gPageURL2 = "data:text/html,<body>" +
- "<button id='tab2button' accesskey='y'>Button in Tab 2</button>" +
- "</body>";
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gPageURL2);
- tab2.linkedBrowser.messageManager.loadFrameScript("data:,(" + childHandleFocus.toString() + ")();", false);
-
- Services.focus.clearFocus(window);
-
- focusedId = yield performAccessKey("y");
- is(focusedId, "tab2button", "button accesskey in tab2");
-
- // Press the accesskey for the chrome element while the content document is focused.
- focusedId = yield performAccessKeyForChrome("z");
- is(focusedId, "chromebutton", "chromebutton accesskey");
-
- newButton.parentNode.removeChild(newButton);
-
- gBrowser.removeTab(tab1);
- gBrowser.removeTab(tab2);
-});
-
-function childHandleFocus() {
- content.document.body.firstChild.addEventListener("focus", function focused(event) {
- let focusedElement = content.document.activeElement;
- focusedElement.blur();
- sendAsyncMessage("Test:FocusFromAccessKey", { focus: focusedElement.id })
- }, true);
-}
-
-function performAccessKey(key)
-{
- return new Promise(resolve => {
- let mm = gBrowser.selectedBrowser.messageManager;
- mm.addMessageListener("Test:FocusFromAccessKey", function listenForFocus(msg) {
- mm.removeMessageListener("Test:FocusFromAccessKey", listenForFocus);
- resolve(msg.data.focus);
- });
-
- EventUtils.synthesizeKey(key, { altKey: true, shiftKey: true });
- });
-}
-
-// This version is used when a chrome elemnt is expected to be found for an accesskey.
-function* performAccessKeyForChrome(key, inChild)
-{
- let waitFocusChangePromise = BrowserTestUtils.waitForEvent(document, "focus", true);
- EventUtils.synthesizeKey(key, { altKey: true, shiftKey: true });
- yield waitFocusChangePromise;
- return document.activeElement.id;
-}
diff --git a/browser/base/content/test/general/browser_addCertException.js b/browser/base/content/test/general/browser_addCertException.js
deleted file mode 100644
index e2cf34b47..000000000
--- a/browser/base/content/test/general/browser_addCertException.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-// Test adding a certificate exception by attempting to browse to a site with
-// a bad certificate, being redirected to the internal about:certerror page,
-// using the button contained therein to load the certificate exception
-// dialog, using that to add an exception, and finally successfully visiting
-// the site, including showing the right identity box and control center icons.
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- yield loadBadCertPage("https://expired.example.com");
- checkControlPanelIcons();
- let certOverrideService = Cc["@mozilla.org/security/certoverride;1"]
- .getService(Ci.nsICertOverrideService);
- certOverrideService.clearValidityOverride("expired.example.com", -1);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-// Check for the correct icons in the identity box and control center.
-function checkControlPanelIcons() {
- let { gIdentityHandler } = gBrowser.ownerGlobal;
- gIdentityHandler._identityBox.click();
- document.getElementById("identity-popup-security-expander").click();
-
- is_element_visible(document.getElementById("connection-icon"), "Should see connection icon");
- let connectionIconImage = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("connection-icon"), "")
- .getPropertyValue("list-style-image");
- let securityViewBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-securityView"), "")
- .getPropertyValue("background-image");
- let securityContentBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-security-content"), "")
- .getPropertyValue("background-image");
- is(connectionIconImage,
- "url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
- "Using expected icon image in the identity block");
- is(securityViewBG,
- "url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
- "Using expected icon image in the Control Center main view");
- is(securityContentBG,
- "url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
- "Using expected icon image in the Control Center subview");
-
- gIdentityHandler._identityPopup.hidden = true;
-}
-
diff --git a/browser/base/content/test/general/browser_addKeywordSearch.js b/browser/base/content/test/general/browser_addKeywordSearch.js
deleted file mode 100644
index f38050b43..000000000
--- a/browser/base/content/test/general/browser_addKeywordSearch.js
+++ /dev/null
@@ -1,81 +0,0 @@
-var testData = [
- { desc: "No path",
- action: "http://example.com/",
- param: "q",
- },
- { desc: "With path",
- action: "http://example.com/new-path-here/",
- param: "q",
- },
- { desc: "No action",
- action: "",
- param: "q",
- },
- { desc: "With Query String",
- action: "http://example.com/search?oe=utf-8",
- param: "q",
- },
-];
-
-add_task(function*() {
- const TEST_URL = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
-
- let count = 0;
- for (let method of ["GET", "POST"]) {
- for (let {desc, action, param } of testData) {
- info(`Running ${method} keyword test '${desc}'`);
- let id = `keyword-form-${count++}`;
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let contextMenuPromise =
- BrowserTestUtils.waitForEvent(contextMenu, "popupshown")
- .then(() => gContextMenuContentData.popupNode);
-
- yield ContentTask.spawn(tab.linkedBrowser,
- { action, param, method, id }, function* (args) {
- let doc = content.document;
- let form = doc.createElement("form");
- form.id = args.id;
- form.method = args.method;
- form.action = args.action;
- let element = doc.createElement("input");
- element.setAttribute("type", "text");
- element.setAttribute("name", args.param);
- form.appendChild(element);
- doc.body.appendChild(form);
- });
-
- yield BrowserTestUtils.synthesizeMouseAtCenter(`#${id} > input`,
- { type : "contextmenu", button : 2 },
- tab.linkedBrowser);
- let target = yield contextMenuPromise;
-
- yield new Promise(resolve => {
- let url = action || tab.linkedBrowser.currentURI.spec;
- let mm = tab.linkedBrowser.messageManager;
- let onMessage = (message) => {
- mm.removeMessageListener("ContextMenu:SearchFieldBookmarkData:Result", onMessage);
- if (method == "GET") {
- ok(message.data.spec.endsWith(`${param}=%s`),
- `Check expected url for field named ${param} and action ${action}`);
- } else {
- is(message.data.spec, url,
- `Check expected url for field named ${param} and action ${action}`);
- is(message.data.postData, `${param}%3D%25s`,
- `Check expected POST data for field named ${param} and action ${action}`);
- }
- resolve();
- };
- mm.addMessageListener("ContextMenu:SearchFieldBookmarkData:Result", onMessage);
-
- mm.sendAsyncMessage("ContextMenu:SearchFieldBookmarkData", null, { target });
- });
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- contextMenu.hidePopup();
- yield popupHiddenPromise;
- }
- }
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_alltabslistener.js b/browser/base/content/test/general/browser_alltabslistener.js
deleted file mode 100644
index a56473ec9..000000000
--- a/browser/base/content/test/general/browser_alltabslistener.js
+++ /dev/null
@@ -1,206 +0,0 @@
-var Ci = Components.interfaces;
-
-const gCompleteState = Ci.nsIWebProgressListener.STATE_STOP +
- Ci.nsIWebProgressListener.STATE_IS_NETWORK;
-
-var gFrontProgressListener = {
- onProgressChange: function (aWebProgress, aRequest,
- aCurSelfProgress, aMaxSelfProgress,
- aCurTotalProgress, aMaxTotalProgress) {
- },
-
- onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
- var state = "onStateChange";
- info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16));
- ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
- is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
- gFrontNotificationsPos++;
- },
-
- onLocationChange: function (aWebProgress, aRequest, aLocationURI, aFlags) {
- var state = "onLocationChange";
- info("FrontProgress: " + state + " " + aLocationURI.spec);
- ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
- is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
- gFrontNotificationsPos++;
- },
-
- onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
- },
-
- onSecurityChange: function (aWebProgress, aRequest, aState) {
- var state = "onSecurityChange";
- info("FrontProgress: " + state + " 0x" + aState.toString(16));
- ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
- is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
- gFrontNotificationsPos++;
- }
-}
-
-var gAllProgressListener = {
- onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
- var state = "onStateChange";
- info("AllProgress: " + state + " 0x" + aStateFlags.toString(16));
- ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
- ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
- is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
- gAllNotificationsPos++;
-
- if ((aStateFlags & gCompleteState) == gCompleteState) {
- ok(gAllNotificationsPos == gAllNotifications.length, "Saw the expected number of notifications");
- ok(gFrontNotificationsPos == gFrontNotifications.length, "Saw the expected number of frontnotifications");
- executeSoon(gNextTest);
- }
- },
-
- onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI,
- aFlags) {
- var state = "onLocationChange";
- info("AllProgress: " + state + " " + aLocationURI.spec);
- ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
- ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
- is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
- gAllNotificationsPos++;
- },
-
- onStatusChange: function (aBrowser, aWebProgress, aRequest, aStatus, aMessage) {
- var state = "onStatusChange";
- ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
- },
-
- onSecurityChange: function (aBrowser, aWebProgress, aRequest, aState) {
- var state = "onSecurityChange";
- info("AllProgress: " + state + " 0x" + aState.toString(16));
- ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
- ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
- is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
- gAllNotificationsPos++;
- }
-}
-
-var gFrontNotifications, gAllNotifications, gFrontNotificationsPos, gAllNotificationsPos;
-var gBackgroundTab, gForegroundTab, gBackgroundBrowser, gForegroundBrowser, gTestBrowser;
-var gTestPage = "/browser/browser/base/content/test/general/alltabslistener.html";
-const kBasePage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-var gNextTest;
-
-function test() {
- waitForExplicitFinish();
-
- gBackgroundTab = gBrowser.addTab();
- gForegroundTab = gBrowser.addTab();
- gBackgroundBrowser = gBrowser.getBrowserForTab(gBackgroundTab);
- gForegroundBrowser = gBrowser.getBrowserForTab(gForegroundTab);
- gBrowser.selectedTab = gForegroundTab;
-
- // We must wait until a page has completed loading before
- // starting tests or we get notifications from that
- let promises = [
- waitForDocLoadComplete(gBackgroundBrowser),
- waitForDocLoadComplete(gForegroundBrowser)
- ];
- gBackgroundBrowser.loadURI(kBasePage);
- gForegroundBrowser.loadURI(kBasePage);
- Promise.all(promises).then(startTest1);
-}
-
-function runTest(browser, url, next) {
- gFrontNotificationsPos = 0;
- gAllNotificationsPos = 0;
- gNextTest = next;
- gTestBrowser = browser;
- browser.loadURI(url);
-}
-
-function startTest1() {
- info("\nTest 1");
- gBrowser.addProgressListener(gFrontProgressListener);
- gBrowser.addTabsProgressListener(gAllProgressListener);
-
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = gAllNotifications;
- runTest(gForegroundBrowser, "http://example.org" + gTestPage, startTest2);
-}
-
-function startTest2() {
- info("\nTest 2");
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = gAllNotifications;
- runTest(gForegroundBrowser, "https://example.com" + gTestPage, startTest3);
-}
-
-function startTest3() {
- info("\nTest 3");
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = [];
- runTest(gBackgroundBrowser, "http://example.org" + gTestPage, startTest4);
-}
-
-function startTest4() {
- info("\nTest 4");
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = [];
- runTest(gBackgroundBrowser, "https://example.com" + gTestPage, startTest5);
-}
-
-function startTest5() {
- info("\nTest 5");
- // Switch the foreground browser
- [gForegroundBrowser, gBackgroundBrowser] = [gBackgroundBrowser, gForegroundBrowser];
- [gForegroundTab, gBackgroundTab] = [gBackgroundTab, gForegroundTab];
- // Avoid the onLocationChange this will fire
- gBrowser.removeProgressListener(gFrontProgressListener);
- gBrowser.selectedTab = gForegroundTab;
- gBrowser.addProgressListener(gFrontProgressListener);
-
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = gAllNotifications;
- runTest(gForegroundBrowser, "http://example.org" + gTestPage, startTest6);
-}
-
-function startTest6() {
- info("\nTest 6");
- gAllNotifications = [
- "onStateChange",
- "onLocationChange",
- "onSecurityChange",
- "onStateChange"
- ];
- gFrontNotifications = [];
- runTest(gBackgroundBrowser, "http://example.org" + gTestPage, finishTest);
-}
-
-function finishTest() {
- gBrowser.removeProgressListener(gFrontProgressListener);
- gBrowser.removeTabsProgressListener(gAllProgressListener);
- gBrowser.removeTab(gBackgroundTab);
- gBrowser.removeTab(gForegroundTab);
- finish();
-}
diff --git a/browser/base/content/test/general/browser_audioTabIcon.js b/browser/base/content/test/general/browser_audioTabIcon.js
deleted file mode 100644
index 4d7a7bbd8..000000000
--- a/browser/base/content/test/general/browser_audioTabIcon.js
+++ /dev/null
@@ -1,504 +0,0 @@
-const PAGE = "https://example.com/browser/browser/base/content/test/general/file_mediaPlayback.html";
-const TABATTR_REMOVAL_PREFNAME = "browser.tabs.delayHidingAudioPlayingIconMS";
-const INITIAL_TABATTR_REMOVAL_DELAY_MS = Services.prefs.getIntPref(TABATTR_REMOVAL_PREFNAME);
-
-function* wait_for_tab_playing_event(tab, expectPlaying) {
- if (tab.soundPlaying == expectPlaying) {
- ok(true, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
- return true;
- }
- return yield BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false, (event) => {
- if (event.detail.changed.includes("soundplaying")) {
- is(tab.hasAttribute("soundplaying"), expectPlaying, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
- is(tab.soundPlaying, expectPlaying, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
- return true;
- }
- return false;
- });
-}
-
-function* play(tab) {
- let browser = tab.linkedBrowser;
- yield ContentTask.spawn(browser, {}, function* () {
- let audio = content.document.querySelector("audio");
- audio.play();
- });
-
- yield wait_for_tab_playing_event(tab, true);
-}
-
-function* pause(tab, options) {
- ok(tab.hasAttribute("soundplaying"), "The tab should have the soundplaying attribute when pause() is called");
-
- let extendedDelay = options && options.extendedDelay;
- if (extendedDelay) {
- // Use 10s to remove possibility of race condition with attr removal.
- Services.prefs.setIntPref(TABATTR_REMOVAL_PREFNAME, 10000);
- }
-
- try {
- let browser = tab.linkedBrowser;
- let awaitDOMAudioPlaybackStopped =
- BrowserTestUtils.waitForEvent(browser, "DOMAudioPlaybackStopped", "DOMAudioPlaybackStopped event should get fired after pause");
- let awaitTabPausedAttrModified =
- wait_for_tab_playing_event(tab, false);
- yield ContentTask.spawn(browser, {}, function* () {
- let audio = content.document.querySelector("audio");
- audio.pause();
- });
-
- if (extendedDelay) {
- ok(tab.hasAttribute("soundplaying"), "The tab should still have the soundplaying attribute immediately after pausing");
-
- yield awaitDOMAudioPlaybackStopped;
- ok(tab.hasAttribute("soundplaying"), "The tab should still have the soundplaying attribute immediately after DOMAudioPlaybackStopped");
- }
-
- yield awaitTabPausedAttrModified;
- ok(!tab.hasAttribute("soundplaying"), "The tab should not have the soundplaying attribute after the timeout has resolved");
- } finally {
- // Make sure other tests don't timeout if an exception gets thrown above.
- // Need to use setIntPref instead of clearUserPref because prefs_general.js
- // overrides the default value to help this and other tests run faster.
- Services.prefs.setIntPref(TABATTR_REMOVAL_PREFNAME, INITIAL_TABATTR_REMOVAL_DELAY_MS);
- }
-}
-
-function disable_non_test_mouse(disable) {
- let utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
- utils.disableNonTestMouseEvents(disable);
-}
-
-function* hover_icon(icon, tooltip) {
- disable_non_test_mouse(true);
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(tooltip, "popupshown");
- EventUtils.synthesizeMouse(icon, 1, 1, {type: "mouseover"});
- EventUtils.synthesizeMouse(icon, 2, 2, {type: "mousemove"});
- EventUtils.synthesizeMouse(icon, 3, 3, {type: "mousemove"});
- EventUtils.synthesizeMouse(icon, 4, 4, {type: "mousemove"});
- return popupShownPromise;
-}
-
-function leave_icon(icon) {
- EventUtils.synthesizeMouse(icon, 0, 0, {type: "mouseout"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
-
- disable_non_test_mouse(false);
-}
-
-function* test_tooltip(icon, expectedTooltip, isActiveTab) {
- let tooltip = document.getElementById("tabbrowser-tab-tooltip");
-
- yield hover_icon(icon, tooltip);
- if (isActiveTab) {
- // The active tab should have the keybinding shortcut in the tooltip.
- // We check this by ensuring that the strings are not equal but the expected
- // message appears in the beginning.
- isnot(tooltip.getAttribute("label"), expectedTooltip, "Tooltips should not be equal");
- is(tooltip.getAttribute("label").indexOf(expectedTooltip), 0, "Correct tooltip expected");
- } else {
- is(tooltip.getAttribute("label"), expectedTooltip, "Tooltips should not be equal");
- }
- leave_icon(icon);
-}
-
-// The set of tabs which have ever had their mute state changed.
-// Used to determine whether the tab should have a muteReason value.
-let everMutedTabs = new WeakSet();
-
-function get_wait_for_mute_promise(tab, expectMuted) {
- return BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false, event => {
- if (event.detail.changed.includes("muted")) {
- is(tab.hasAttribute("muted"), expectMuted, "The tab should " + (expectMuted ? "" : "not ") + "be muted");
- is(tab.muted, expectMuted, "The tab muted property " + (expectMuted ? "" : "not ") + "be true");
-
- if (expectMuted || everMutedTabs.has(tab)) {
- everMutedTabs.add(tab);
- is(tab.muteReason, null, "The tab should have a null muteReason value");
- } else {
- is(tab.muteReason, undefined, "The tab should have an undefined muteReason value");
- }
- return true;
- }
- return false;
- });
-}
-
-function* test_mute_tab(tab, icon, expectMuted) {
- let mutedPromise = test_mute_keybinding(tab, expectMuted);
-
- let activeTab = gBrowser.selectedTab;
-
- let tooltip = document.getElementById("tabbrowser-tab-tooltip");
-
- yield hover_icon(icon, tooltip);
- EventUtils.synthesizeMouseAtCenter(icon, {button: 0});
- leave_icon(icon);
-
- is(gBrowser.selectedTab, activeTab, "Clicking on mute should not change the currently selected tab");
-
- return mutedPromise;
-}
-
-function get_tab_state(tab) {
- const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
- return JSON.parse(ss.getTabState(tab));
-}
-
-function* test_muting_using_menu(tab, expectMuted) {
- // Show the popup menu
- let contextMenu = document.getElementById("tabContextMenu");
- let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(tab, {type: "contextmenu", button: 2});
- yield popupShownPromise;
-
- // Check the menu
- let expectedLabel = expectMuted ? "Unmute Tab" : "Mute Tab";
- let toggleMute = document.getElementById("context_toggleMuteTab");
- is(toggleMute.label, expectedLabel, "Correct label expected");
- is(toggleMute.accessKey, "M", "Correct accessKey expected");
-
- is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
- ok(!toggleMute.hasAttribute("soundplaying"), "Should not have the soundplaying attribute");
-
- yield play(tab);
-
- is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
- ok(toggleMute.hasAttribute("soundplaying"), "Should have the soundplaying attribute");
-
- yield pause(tab);
-
- is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
- ok(!toggleMute.hasAttribute("soundplaying"), "Should not have the soundplaying attribute");
-
- // Click on the menu and wait for the tab to be muted.
- let mutedPromise = get_wait_for_mute_promise(tab, !expectMuted);
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- EventUtils.synthesizeMouseAtCenter(toggleMute, {});
- yield popupHiddenPromise;
- yield mutedPromise;
-}
-
-function* test_playing_icon_on_tab(tab, browser, isPinned) {
- let icon = document.getAnonymousElementByAttribute(tab, "anonid",
- isPinned ? "overlay-icon" : "soundplaying-icon");
- let isActiveTab = tab === gBrowser.selectedTab;
-
- yield play(tab);
-
- yield test_tooltip(icon, "Mute tab", isActiveTab);
-
- ok(!("muted" in get_tab_state(tab)), "No muted attribute should be persisted");
- ok(!("muteReason" in get_tab_state(tab)), "No muteReason property should be persisted");
-
- yield test_mute_tab(tab, icon, true);
-
- ok("muted" in get_tab_state(tab), "Muted attribute should be persisted");
- ok("muteReason" in get_tab_state(tab), "muteReason property should be persisted");
-
- yield test_tooltip(icon, "Unmute tab", isActiveTab);
-
- yield test_mute_tab(tab, icon, false);
-
- ok(!("muted" in get_tab_state(tab)), "No muted attribute should be persisted");
- ok(!("muteReason" in get_tab_state(tab)), "No muteReason property should be persisted");
-
- yield test_tooltip(icon, "Mute tab", isActiveTab);
-
- yield test_mute_tab(tab, icon, true);
-
- yield pause(tab);
-
- ok(tab.hasAttribute("muted") &&
- !tab.hasAttribute("soundplaying"), "Tab should still be muted but not playing");
- ok(tab.muted && !tab.soundPlaying, "Tab should still be muted but not playing");
-
- yield test_tooltip(icon, "Unmute tab", isActiveTab);
-
- yield test_mute_tab(tab, icon, false);
-
- ok(!tab.hasAttribute("muted") &&
- !tab.hasAttribute("soundplaying"), "Tab should not be be muted or playing");
- ok(!tab.muted && !tab.soundPlaying, "Tab should not be be muted or playing");
-
- // Make sure it's possible to mute using the context menu.
- yield test_muting_using_menu(tab, false);
-
- // Make sure it's possible to unmute using the context menu.
- yield test_muting_using_menu(tab, true);
-}
-
-function* test_swapped_browser_while_playing(oldTab, newBrowser) {
- ok(oldTab.hasAttribute("muted"), "Expected the correct muted attribute on the old tab");
- is(oldTab.muteReason, null, "Expected the correct muteReason attribute on the old tab");
- ok(oldTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the old tab");
-
- let newTab = gBrowser.getTabForBrowser(newBrowser);
- let AttrChangePromise = BrowserTestUtils.waitForEvent(newTab, "TabAttrModified", false, event => {
- return event.detail.changed.includes("soundplaying") &&
- event.detail.changed.includes("muted");
- });
-
- gBrowser.swapBrowsersAndCloseOther(newTab, oldTab);
- yield AttrChangePromise;
-
- ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
- is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
- ok(newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
-
- let icon = document.getAnonymousElementByAttribute(newTab, "anonid",
- "soundplaying-icon");
- yield test_tooltip(icon, "Unmute tab", true);
-}
-
-function* test_swapped_browser_while_not_playing(oldTab, newBrowser) {
- ok(oldTab.hasAttribute("muted"), "Expected the correct muted attribute on the old tab");
- is(oldTab.muteReason, null, "Expected the correct muteReason property on the old tab");
- ok(!oldTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the old tab");
-
- let newTab = gBrowser.getTabForBrowser(newBrowser);
- let AttrChangePromise = BrowserTestUtils.waitForEvent(newTab, "TabAttrModified", false, event => {
- return event.detail.changed.includes("muted");
- });
-
- let AudioPlaybackPromise = new Promise(resolve => {
- let observer = (subject, topic, data) => {
- ok(false, "Should not see an audio-playback notification");
- };
- Services.obs.addObserver(observer, "audiochannel-activity-normal", false);
- setTimeout(() => {
- Services.obs.removeObserver(observer, "audiochannel-activity-normal");
- resolve();
- }, 100);
- });
-
- gBrowser.swapBrowsersAndCloseOther(newTab, oldTab);
- yield AttrChangePromise;
-
- ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
- is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
- ok(!newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
-
- // Wait to see if an audio-playback event is dispatched.
- yield AudioPlaybackPromise;
-
- ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
- is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
- ok(!newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
-
- let icon = document.getAnonymousElementByAttribute(newTab, "anonid",
- "soundplaying-icon");
- yield test_tooltip(icon, "Unmute tab", true);
-}
-
-function* test_browser_swapping(tab, browser) {
- // First, test swapping with a playing but muted tab.
- yield play(tab);
-
- let icon = document.getAnonymousElementByAttribute(tab, "anonid",
- "soundplaying-icon");
- yield test_mute_tab(tab, icon, true);
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank",
- }, function*(newBrowser) {
- yield test_swapped_browser_while_playing(tab, newBrowser)
-
- // Now, test swapping with a muted but not playing tab.
- // Note that the tab remains muted, so we only need to pause playback.
- tab = gBrowser.getTabForBrowser(newBrowser);
- yield pause(tab);
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank",
- }, secondAboutBlankBrowser => test_swapped_browser_while_not_playing(tab, secondAboutBlankBrowser));
- });
-}
-
-function* test_click_on_pinned_tab_after_mute() {
- function* taskFn(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
-
- gBrowser.selectedTab = originallySelectedTab;
- isnot(tab, gBrowser.selectedTab, "Sanity check, the tab should not be selected!");
-
- // Steps to reproduce the bug:
- // Pin the tab.
- gBrowser.pinTab(tab);
-
- // Start playback and wait for it to finish.
- yield play(tab);
-
- // Mute the tab.
- let icon = document.getAnonymousElementByAttribute(tab, "anonid", "overlay-icon");
- yield test_mute_tab(tab, icon, true);
-
- // Pause playback and wait for it to finish.
- yield pause(tab);
-
- // Unmute tab.
- yield test_mute_tab(tab, icon, false);
-
- // Now click on the tab.
- let image = document.getAnonymousElementByAttribute(tab, "anonid", "tab-icon-image");
- EventUtils.synthesizeMouseAtCenter(image, {button: 0});
-
- is(tab, gBrowser.selectedTab, "Tab switch should be successful");
-
- // Cleanup.
- gBrowser.unpinTab(tab);
- gBrowser.selectedTab = originallySelectedTab;
- }
-
- let originallySelectedTab = gBrowser.selectedTab;
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE
- }, taskFn);
-}
-
-// This test only does something useful in e10s!
-function* test_cross_process_load() {
- function* taskFn(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
-
- // Start playback and wait for it to finish.
- yield play(tab);
-
- let soundPlayingStoppedPromise = BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false,
- event => event.detail.changed.includes("soundplaying")
- );
-
- // Go to a different process.
- browser.loadURI("about:");
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield soundPlayingStoppedPromise;
-
- ok(!tab.hasAttribute("soundplaying"), "Tab should not be playing sound any more");
- ok(!tab.soundPlaying, "Tab should not be playing sound any more");
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE
- }, taskFn);
-}
-
-function* test_mute_keybinding() {
- function* test_muting_using_keyboard(tab) {
- let mutedPromise = get_wait_for_mute_promise(tab, true);
- EventUtils.synthesizeKey("m", {ctrlKey: true});
- yield mutedPromise;
- mutedPromise = get_wait_for_mute_promise(tab, false);
- EventUtils.synthesizeKey("m", {ctrlKey: true});
- yield mutedPromise;
- }
- function* taskFn(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
-
- // Make sure it's possible to mute before the tab is playing.
- yield test_muting_using_keyboard(tab);
-
- // Start playback and wait for it to finish.
- yield play(tab);
-
- // Make sure it's possible to mute after the tab is playing.
- yield test_muting_using_keyboard(tab);
-
- // Pause playback and wait for it to finish.
- yield pause(tab);
-
- // Make sure things work if the tab is pinned.
- gBrowser.pinTab(tab);
-
- // Make sure it's possible to mute before the tab is playing.
- yield test_muting_using_keyboard(tab);
-
- // Start playback and wait for it to finish.
- yield play(tab);
-
- // Make sure it's possible to mute after the tab is playing.
- yield test_muting_using_keyboard(tab);
-
- gBrowser.unpinTab(tab);
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE
- }, taskFn);
-}
-
-function* test_on_browser(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
-
- // Test the icon in a normal tab.
- yield test_playing_icon_on_tab(tab, browser, false);
-
- gBrowser.pinTab(tab);
-
- // Test the icon in a pinned tab.
- yield test_playing_icon_on_tab(tab, browser, true);
-
- gBrowser.unpinTab(tab);
-
- // Retest with another browser in the foreground tab
- if (gBrowser.selectedBrowser.currentURI.spec == PAGE) {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "data:text/html,test"
- }, () => test_on_browser(browser));
- } else {
- yield test_browser_swapping(tab, browser);
- }
-}
-
-function* test_delayed_tabattr_removal() {
- function* taskFn(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
- yield play(tab);
-
- // Extend the delay to guarantee the soundplaying attribute
- // is not removed from the tab when audio is stopped. Without
- // the extended delay the attribute could be removed in the
- // same tick and the test wouldn't catch that this broke.
- yield pause(tab, {extendedDelay: true});
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE
- }, taskFn);
-}
-
-add_task(function*() {
- yield new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": [
- ["browser.tabs.showAudioPlayingIcon", true],
- ]}, resolve);
- });
-});
-
-requestLongerTimeout(2);
-add_task(function* test_page() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE
- }, test_on_browser);
-});
-
-add_task(test_click_on_pinned_tab_after_mute);
-
-add_task(test_cross_process_load);
-
-add_task(test_mute_keybinding);
-
-add_task(test_delayed_tabattr_removal);
diff --git a/browser/base/content/test/general/browser_backButtonFitts.js b/browser/base/content/test/general/browser_backButtonFitts.js
deleted file mode 100644
index 0e8aeeaee..000000000
--- a/browser/base/content/test/general/browser_backButtonFitts.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-add_task(function* () {
- let firstLocation = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, firstLocation);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- // Push the state before maximizing the window and clicking below.
- content.history.pushState("page2", "page2", "page2");
-
- // While in the child process, add a listener for the popstate event here. This
- // event will fire when the mouse click happens.
- content.addEventListener("popstate", function onPopState() {
- content.removeEventListener("popstate", onPopState, false);
- sendAsyncMessage("Test:PopStateOccurred", { location: content.document.location.href });
- }, false);
- });
-
- window.maximize();
-
- // Find where the nav-bar is vertically.
- var navBar = document.getElementById("nav-bar");
- var boundingRect = navBar.getBoundingClientRect();
- var yPixel = boundingRect.top + Math.floor(boundingRect.height / 2);
- var xPixel = 0; // Use the first pixel of the screen since it is maximized.
-
- let resultLocation = yield new Promise(resolve => {
- messageManager.addMessageListener("Test:PopStateOccurred", function statePopped(message) {
- messageManager.removeMessageListener("Test:PopStateOccurred", statePopped);
- resolve(message.data.location);
- });
-
- EventUtils.synthesizeMouseAtPoint(xPixel, yPixel, {}, window);
- });
-
- is(resultLocation, firstLocation, "Clicking the first pixel should have navigated back.");
- window.restore();
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_beforeunload_duplicate_dialogs.js b/browser/base/content/test/general/browser_beforeunload_duplicate_dialogs.js
deleted file mode 100644
index 91a4a7e9c..000000000
--- a/browser/base/content/test/general/browser_beforeunload_duplicate_dialogs.js
+++ /dev/null
@@ -1,76 +0,0 @@
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/base/content/test/general/file_double_close_tab.html";
-
-var expectingDialog = false;
-var wantToClose = true;
-var resolveDialogPromise;
-function onTabModalDialogLoaded(node) {
- ok(expectingDialog, "Should be expecting this dialog.");
- expectingDialog = false;
- if (wantToClose) {
- // This accepts the dialog, closing it
- node.Dialog.ui.button0.click();
- } else {
- // This keeps the page open
- node.Dialog.ui.button1.click();
- }
- if (resolveDialogPromise) {
- resolveDialogPromise();
- }
-}
-
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
-
-// Listen for the dialog being created
-Services.obs.addObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded", false);
-registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.tabs.warnOnClose");
- Services.obs.removeObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded");
-});
-
-add_task(function* closeLastTabInWindow() {
- let newWin = yield promiseOpenAndLoadWindow({}, true);
- let firstTab = newWin.gBrowser.selectedTab;
- yield promiseTabLoadEvent(firstTab, TEST_PAGE);
- let windowClosedPromise = promiseWindowWillBeClosed(newWin);
- expectingDialog = true;
- // close tab:
- document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
- yield windowClosedPromise;
- ok(!expectingDialog, "There should have been a dialog.");
- ok(newWin.closed, "Window should be closed.");
-});
-
-add_task(function* closeWindowWithMultipleTabsIncludingOneBeforeUnload() {
- Services.prefs.setBoolPref("browser.tabs.warnOnClose", false);
- let newWin = yield promiseOpenAndLoadWindow({}, true);
- let firstTab = newWin.gBrowser.selectedTab;
- yield promiseTabLoadEvent(firstTab, TEST_PAGE);
- yield promiseTabLoadEvent(newWin.gBrowser.addTab(), "http://example.com/");
- let windowClosedPromise = promiseWindowWillBeClosed(newWin);
- expectingDialog = true;
- newWin.BrowserTryToCloseWindow();
- yield windowClosedPromise;
- ok(!expectingDialog, "There should have been a dialog.");
- ok(newWin.closed, "Window should be closed.");
- Services.prefs.clearUserPref("browser.tabs.warnOnClose");
-});
-
-add_task(function* closeWindoWithSingleTabTwice() {
- let newWin = yield promiseOpenAndLoadWindow({}, true);
- let firstTab = newWin.gBrowser.selectedTab;
- yield promiseTabLoadEvent(firstTab, TEST_PAGE);
- let windowClosedPromise = promiseWindowWillBeClosed(newWin);
- expectingDialog = true;
- wantToClose = false;
- let firstDialogShownPromise = new Promise((resolve, reject) => { resolveDialogPromise = resolve; });
- document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
- yield firstDialogShownPromise;
- info("Got initial dialog, now trying again");
- expectingDialog = true;
- wantToClose = true;
- resolveDialogPromise = null;
- document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
- yield windowClosedPromise;
- ok(!expectingDialog, "There should have been a dialog.");
- ok(newWin.closed, "Window should be closed.");
-});
diff --git a/browser/base/content/test/general/browser_blob-channelname.js b/browser/base/content/test/general/browser_blob-channelname.js
deleted file mode 100644
index d87e4a896..000000000
--- a/browser/base/content/test/general/browser_blob-channelname.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-function test() {
- var file = new File([new Blob(['test'], {type: 'text/plain'})], "test-name");
- var url = URL.createObjectURL(file);
- var channel = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true});
-
- is(channel.contentDispositionFilename, 'test-name', "filename matches");
-}
diff --git a/browser/base/content/test/general/browser_blockHPKP.js b/browser/base/content/test/general/browser_blockHPKP.js
deleted file mode 100644
index c0d1233ab..000000000
--- a/browser/base/content/test/general/browser_blockHPKP.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* 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/. */
-
-// Test that visiting a site pinned with HPKP headers does not succeed when it
-// uses a certificate with a key not in the pinset. This should result in an
-// about:neterror page
-// Also verify that removal of the HPKP headers succeeds (via HPKP headers)
-// and that after removal the visit to the site with the previously
-// unauthorized pins succeeds.
-//
-// This test required three certs to be created in build/pgo/certs:
-// 1. A new trusted root:
-// a. certutil -S -s "Alternate trusted authority" -s "CN=Alternate Trusted Authority" -t "C,," -x -m 1 -v 120 -n "alternateTrustedAuthority" -Z SHA256 -g 2048 -2 -d .
-// b. (export) certutil -L -d . -n "alternateTrustedAuthority" -a -o alternateroot.ca
-// (files ended in .ca are added as trusted roots by the mochitest harness)
-// 2. A good pinning server cert (signed by the pgo root):
-// certutil -S -n "dynamicPinningGood" -s "CN=dynamic-pinning.example.com" -c "pgo temporary ca" -t "P,," -k rsa -g 2048 -Z SHA256 -m 8939454 -v 120 -8 "*.include-subdomains.pinning-dynamic.example.com,*.pinning-dynamic.example.com" -d .
-// 3. A certificate with a different issuer, so as to cause a key pinning violation."
-// certutil -S -n "dynamicPinningBad" -s "CN=bad.include-subdomains.pinning-dynamic.example.com" -c "alternateTrustedAuthority" -t "P,," -k rsa -g 2048 -Z SHA256 -m 893945439 -v 120 -8 "bad.include-subdomains.pinning-dynamic.example.com" -d .
-
-const gSSService = Cc["@mozilla.org/ssservice;1"]
- .getService(Ci.nsISiteSecurityService);
-const gIOService = Cc["@mozilla.org/network/io-service;1"]
- .getService(Ci.nsIIOService);
-
-const kPinningDomain = "include-subdomains.pinning-dynamic.example.com";
-const khpkpPinninEnablePref = "security.cert_pinning.process_headers_from_non_builtin_roots";
-const kpkpEnforcementPref = "security.cert_pinning.enforcement_level";
-const kBadPinningDomain = "bad.include-subdomains.pinning-dynamic.example.com";
-const kURLPath = "/browser/browser/base/content/test/general/pinning_headers.sjs?";
-
-function test() {
- waitForExplicitFinish();
- // Enable enforcing strict pinning and processing headers from
- // non-builtin roots.
- Services.prefs.setIntPref(kpkpEnforcementPref, 2);
- Services.prefs.setBoolPref(khpkpPinninEnablePref, true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(kpkpEnforcementPref);
- Services.prefs.clearUserPref(khpkpPinninEnablePref);
- let uri = gIOService.newURI("https://" + kPinningDomain, null, null);
- gSSService.removeState(Ci.nsISiteSecurityService.HEADER_HPKP, uri, 0);
- });
- whenNewTabLoaded(window, loadPinningPage);
-}
-
-// Start by making a successful connection to a domain that will pin a site
-function loadPinningPage() {
-
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kPinningDomain + kURLPath + "valid").then(function() {
- gBrowser.selectedBrowser.addEventListener("load",
- successfulPinningPageListener,
- true);
- });
-}
-
-// After the site is pinned try to load with a subdomain site that should
-// fail to validate
-var successfulPinningPageListener = {
- handleEvent: function() {
- gBrowser.selectedBrowser.removeEventListener("load", this, true);
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() {
- return promiseErrorPageLoaded(gBrowser.selectedBrowser);
- }).then(errorPageLoaded);
- }
-};
-
-// The browser should load about:neterror, when this happens, proceed
-// to load the pinning domain again, this time removing the pinning information
-function errorPageLoaded() {
- ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let textElement = content.document.getElementById("errorShortDescText");
- let text = textElement.innerHTML;
- ok(text.indexOf("MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE") > 0,
- "Got a pinning error page");
- }).then(function() {
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kPinningDomain + kURLPath + "zeromaxagevalid").then(function() {
- return BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- }).then(pinningRemovalLoaded);
- });
-}
-
-// After the pinning information has been removed (successful load) proceed
-// to load again with the invalid pin domain.
-function pinningRemovalLoaded() {
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() {
- return BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- }).then(badPinningPageLoaded);
-}
-
-// Finally, we should successfully load
-// https://bad.include-subdomains.pinning-dynamic.example.com.
-function badPinningPageLoaded() {
- BrowserTestUtils.removeTab(gBrowser.selectedTab).then(function() {
- ok(true, "load complete");
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_bookmark_popup.js b/browser/base/content/test/general/browser_bookmark_popup.js
deleted file mode 100644
index c1ddd725e..000000000
--- a/browser/base/content/test/general/browser_bookmark_popup.js
+++ /dev/null
@@ -1,431 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-/**
- * Test opening and closing the bookmarks panel.
- */
-
-let bookmarkPanel = document.getElementById("editBookmarkPanel");
-let bookmarkStar = document.getElementById("bookmarks-menu-button");
-let bookmarkPanelTitle = document.getElementById("editBookmarkPanelTitle");
-let editBookmarkPanelRemoveButtonRect;
-
-StarUI._closePanelQuickForTesting = true;
-
-function* test_bookmarks_popup({isNewBookmark, popupShowFn, popupEditFn,
- shouldAutoClose, popupHideFn, isBookmarkRemoved}) {
- yield BrowserTestUtils.withNewTab({gBrowser, url: "about:home"}, function*(browser) {
- try {
- if (!isNewBookmark) {
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "about:home",
- title: "Home Page"
- });
- }
-
- info(`BookmarkingUI.status is ${BookmarkingUI.status}`);
- yield BrowserTestUtils.waitForCondition(
- () => BookmarkingUI.status != BookmarkingUI.STATUS_UPDATING,
- "BookmarkingUI should not be updating");
-
- is(bookmarkStar.hasAttribute("starred"), !isNewBookmark,
- "Page should only be starred prior to popupshown if editing bookmark");
- is(bookmarkPanel.state, "closed", "Panel should be 'closed' to start test");
- let shownPromise = promisePopupShown(bookmarkPanel);
- yield popupShowFn(browser);
- yield shownPromise;
- is(bookmarkPanel.state, "open", "Panel should be 'open' after shownPromise is resolved");
-
- editBookmarkPanelRemoveButtonRect =
- document.getElementById("editBookmarkPanelRemoveButton").getBoundingClientRect();
-
- if (popupEditFn) {
- yield popupEditFn();
- }
- let bookmarks = [];
- yield PlacesUtils.bookmarks.fetch({url: "about:home"}, bm => bookmarks.push(bm));
- is(bookmarks.length, 1, "Only one bookmark should exist");
- is(bookmarkStar.getAttribute("starred"), "true", "Page is starred");
- is(bookmarkPanelTitle.value,
- isNewBookmark ?
- gNavigatorBundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
- gNavigatorBundle.getString("editBookmarkPanel.editBookmarkTitle"),
- "title should match isEditingBookmark state");
-
- if (!shouldAutoClose) {
- yield new Promise(resolve => setTimeout(resolve, 400));
- is(bookmarkPanel.state, "open", "Panel should still be 'open' for non-autoclose");
- }
-
- let hiddenPromise = promisePopupHidden(bookmarkPanel);
- if (popupHideFn) {
- yield popupHideFn();
- }
- yield hiddenPromise;
- is(bookmarkStar.hasAttribute("starred"), !isBookmarkRemoved,
- "Page is starred after closing");
- } finally {
- let bookmark = yield PlacesUtils.bookmarks.fetch({url: "about:home"});
- is(!!bookmark, !isBookmarkRemoved,
- "bookmark should not be present if a panel action should've removed it");
- if (bookmark) {
- yield PlacesUtils.bookmarks.remove(bookmark);
- }
- }
- });
-}
-
-add_task(function* panel_shown_for_new_bookmarks_and_autocloses() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- shouldAutoClose: true,
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_once_for_doubleclick_on_new_bookmark_star_and_autocloses() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- EventUtils.synthesizeMouse(bookmarkStar, 10, 10, { clickCount: 2 },
- window);
- },
- shouldAutoClose: true,
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_once_for_slow_doubleclick_on_new_bookmark_star_and_autocloses() {
- todo(false, "bug 1250267, may need to add some tracking state to " +
- "browser-places.js for this.");
- return;
-
- /*
- yield test_bookmarks_popup({
- isNewBookmark: true,
- *popupShowFn() {
- EventUtils.synthesizeMouse(bookmarkStar, 10, 10, window);
- yield new Promise(resolve => setTimeout(resolve, 300));
- EventUtils.synthesizeMouse(bookmarkStar, 10, 10, window);
- },
- shouldAutoClose: true,
- isBookmarkRemoved: false,
- });
- */
-});
-
-add_task(function* panel_shown_for_keyboardshortcut_on_new_bookmark_star_and_autocloses() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- EventUtils.synthesizeKey("D", {accelKey: true}, window);
- },
- shouldAutoClose: true,
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_new_bookmarks_mousemove_mouseout() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- *popupEditFn() {
- let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
- EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
- info("Waiting for mousemove event");
- yield mouseMovePromise;
- info("Got mousemove event");
-
- yield new Promise(resolve => setTimeout(resolve, 400));
- is(bookmarkPanel.state, "open", "Panel should still be open on mousemove");
- },
- *popupHideFn() {
- let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
- EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
- info("Waiting for mouseout event");
- yield mouseOutPromise;
- info("Got mouseout event, should autoclose now");
- },
- shouldAutoClose: false,
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_new_bookmark_no_autoclose_close_with_ESC() {
- yield test_bookmarks_popup({
- isNewBookmark: false,
- popupShowFn() {
- bookmarkStar.click();
- },
- shouldAutoClose: false,
- popupHideFn() {
- EventUtils.synthesizeKey("VK_ESCAPE", {accelKey: true}, window);
- },
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_editing_no_autoclose_close_with_ESC() {
- yield test_bookmarks_popup({
- isNewBookmark: false,
- popupShowFn() {
- bookmarkStar.click();
- },
- shouldAutoClose: false,
- popupHideFn() {
- EventUtils.synthesizeKey("VK_ESCAPE", {accelKey: true}, window);
- },
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_new_bookmark_keypress_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- popupEditFn() {
- EventUtils.sendChar("VK_TAB", window);
- },
- shouldAutoClose: false,
- popupHideFn() {
- bookmarkPanel.hidePopup();
- },
- isBookmarkRemoved: false,
- });
-});
-
-
-add_task(function* panel_shown_for_new_bookmark_compositionstart_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- *popupEditFn() {
- let compositionStartPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "compositionstart");
- EventUtils.synthesizeComposition({ type: "compositionstart" }, window);
- info("Waiting for compositionstart event");
- yield compositionStartPromise;
- info("Got compositionstart event");
- },
- shouldAutoClose: false,
- popupHideFn() {
- EventUtils.synthesizeComposition({ type: "compositioncommitasis" });
- bookmarkPanel.hidePopup();
- },
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_new_bookmark_compositionstart_mouseout_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- *popupEditFn() {
- let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
- EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
- info("Waiting for mousemove event");
- yield mouseMovePromise;
- info("Got mousemove event");
-
- let compositionStartPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "compositionstart");
- EventUtils.synthesizeComposition({ type: "compositionstart" }, window);
- info("Waiting for compositionstart event");
- yield compositionStartPromise;
- info("Got compositionstart event");
-
- let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
- EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
- info("Waiting for mouseout event");
- yield mouseOutPromise;
- info("Got mouseout event, but shouldn't run autoclose");
- },
- shouldAutoClose: false,
- popupHideFn() {
- EventUtils.synthesizeComposition({ type: "compositioncommitasis" });
- bookmarkPanel.hidePopup();
- },
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* panel_shown_for_new_bookmark_compositionend_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn() {
- bookmarkStar.click();
- },
- *popupEditFn() {
- let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
- EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
- info("Waiting for mousemove event");
- yield mouseMovePromise;
- info("Got mousemove event");
-
- EventUtils.synthesizeComposition({ type: "compositioncommit", data: "committed text" });
- },
- popupHideFn() {
- bookmarkPanel.hidePopup();
- },
- shouldAutoClose: false,
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* contextmenu_new_bookmark_keypress_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- *popupShowFn(browser) {
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu,
- "popupshown");
- let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu,
- "popuphidden");
- yield BrowserTestUtils.synthesizeMouseAtCenter("body", {
- type: "contextmenu",
- button: 2
- }, browser);
- yield awaitPopupShown;
- document.getElementById("context-bookmarkpage").click();
- contextMenu.hidePopup();
- yield awaitPopupHidden;
- },
- popupEditFn() {
- EventUtils.sendChar("VK_TAB", window);
- },
- shouldAutoClose: false,
- popupHideFn() {
- bookmarkPanel.hidePopup();
- },
- isBookmarkRemoved: false,
- });
-});
-
-add_task(function* bookmarks_menu_new_bookmark_remove_bookmark() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn(browser) {
- document.getElementById("menu_bookmarkThisPage").doCommand();
- },
- shouldAutoClose: true,
- popupHideFn() {
- document.getElementById("editBookmarkPanelRemoveButton").click();
- },
- isBookmarkRemoved: true,
- });
-});
-
-add_task(function* ctrl_d_edit_bookmark_remove_bookmark() {
- yield test_bookmarks_popup({
- isNewBookmark: false,
- popupShowFn(browser) {
- EventUtils.synthesizeKey("D", {accelKey: true}, window);
- },
- shouldAutoClose: true,
- popupHideFn() {
- document.getElementById("editBookmarkPanelRemoveButton").click();
- },
- isBookmarkRemoved: true,
- });
-});
-
-add_task(function* enter_on_remove_bookmark_should_remove_bookmark() {
- if (AppConstants.platform == "macosx") {
- // "Full Keyboard Access" is disabled by default, and thus doesn't allow
- // keyboard navigation to the "Remove Bookmarks" button by default.
- return;
- }
-
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn(browser) {
- EventUtils.synthesizeKey("D", {accelKey: true}, window);
- },
- shouldAutoClose: true,
- popupHideFn() {
- while (!document.activeElement ||
- document.activeElement.id != "editBookmarkPanelRemoveButton") {
- EventUtils.sendChar("VK_TAB", window);
- }
- EventUtils.sendChar("VK_RETURN", window);
- },
- isBookmarkRemoved: true,
- });
-});
-
-add_task(function* ctrl_d_new_bookmark_mousedown_mouseout_no_autoclose() {
- yield test_bookmarks_popup({
- isNewBookmark: true,
- popupShowFn(browser) {
- EventUtils.synthesizeKey("D", {accelKey: true}, window);
- },
- *popupEditFn() {
- let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
- EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
- info("Waiting for mousemove event");
- yield mouseMovePromise;
- info("Got mousemove event");
-
- yield new Promise(resolve => setTimeout(resolve, 400));
- is(bookmarkPanel.state, "open", "Panel should still be open on mousemove");
-
- EventUtils.synthesizeMouseAtCenter(bookmarkPanelTitle, {button: 1, type: "mousedown"});
-
- let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
- EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
- info("Waiting for mouseout event");
- yield mouseOutPromise;
- },
- shouldAutoClose: false,
- popupHideFn() {
- document.getElementById("editBookmarkPanelRemoveButton").click();
- },
- isBookmarkRemoved: true,
- });
-});
-
-add_task(function* mouse_hovering_panel_should_prevent_autoclose() {
- if (AppConstants.platform != "win") {
- // This test requires synthesizing native mouse movement which is
- // best supported on Windows.
- return;
- }
- yield test_bookmarks_popup({
- isNewBookmark: true,
- *popupShowFn(browser) {
- yield new Promise(resolve => {
- EventUtils.synthesizeNativeMouseMove(
- document.documentElement,
- editBookmarkPanelRemoveButtonRect.left,
- editBookmarkPanelRemoveButtonRect.top,
- resolve);
- });
- EventUtils.synthesizeKey("D", {accelKey: true}, window);
- },
- shouldAutoClose: false,
- popupHideFn() {
- document.getElementById("editBookmarkPanelRemoveButton").click();
- },
- isBookmarkRemoved: true,
- });
-});
-
-registerCleanupFunction(function() {
- delete StarUI._closePanelQuickForTesting;
-});
diff --git a/browser/base/content/test/general/browser_bookmark_titles.js b/browser/base/content/test/general/browser_bookmark_titles.js
deleted file mode 100644
index 1f7082396..000000000
--- a/browser/base/content/test/general/browser_bookmark_titles.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* 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/. */
-
-// This file is tests for the default titles that new bookmarks get.
-
-var tests = [
- // Common page.
- ['http://example.com/browser/browser/base/content/test/general/dummy_page.html',
- 'Dummy test page'],
- // Data URI.
- ['data:text/html;charset=utf-8,<title>test%20data:%20url</title>',
- 'test data: url'],
- // about:neterror
- ['data:application/vnd.mozilla.xul+xml,',
- 'data:application/vnd.mozilla.xul+xml,'],
- // about:certerror
- ['https://untrusted.example.com/somepage.html',
- 'https://untrusted.example.com/somepage.html']
-];
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
- browser.stop(); // stop the about:blank load.
-
- // Test that a bookmark of each URI gets the corresponding default title.
- for (let i = 0; i < tests.length; ++i) {
- let [uri, title] = tests[i];
-
- let promiseLoaded = promisePageLoaded(browser);
- BrowserTestUtils.loadURI(browser, uri);
- yield promiseLoaded;
- yield checkBookmark(uri, title);
- }
-
- // Network failure test: now that dummy_page.html is in history, bookmarking
- // it should give the last known page title as the default bookmark title.
-
- // Simulate a network outage with offline mode. (Localhost is still
- // accessible in offline mode, so disable the test proxy as well.)
- BrowserOffline.toggleOfflineStatus();
- let proxy = Services.prefs.getIntPref('network.proxy.type');
- Services.prefs.setIntPref('network.proxy.type', 0);
- registerCleanupFunction(function () {
- BrowserOffline.toggleOfflineStatus();
- Services.prefs.setIntPref('network.proxy.type', proxy);
- });
-
- // LOAD_FLAGS_BYPASS_CACHE isn't good enough. So clear the cache.
- Services.cache2.clear();
-
- let [uri, title] = tests[0];
-
- let promiseLoaded = promisePageLoaded(browser);
- BrowserTestUtils.loadURI(browser, uri);
- yield promiseLoaded;
-
- // The offline mode test is only good if the page failed to load.
- yield ContentTask.spawn(browser, null, function() {
- is(content.document.documentURI.substring(0, 14), 'about:neterror',
- "Offline mode successfully simulated network outage.");
- });
- yield checkBookmark(uri, title);
-
- gBrowser.removeCurrentTab();
-});
-
-// Bookmark the current page and confirm that the new bookmark has the expected
-// title. (Then delete the bookmark.)
-function* checkBookmark(uri, expected_title) {
- is(gBrowser.selectedBrowser.currentURI.spec, uri,
- "Trying to bookmark the expected uri");
-
- let promiseBookmark = promiseOnBookmarkItemAdded(gBrowser.selectedBrowser.currentURI);
- PlacesCommandHook.bookmarkCurrentPage(false);
- yield promiseBookmark;
-
- let id = PlacesUtils.getMostRecentBookmarkForURI(PlacesUtils._uri(uri));
- ok(id > 0, "Found the expected bookmark");
- let title = PlacesUtils.bookmarks.getItemTitle(id);
- is(title, expected_title, "Bookmark got a good default title.");
-
- PlacesUtils.bookmarks.removeItem(id);
-}
-
-// BrowserTestUtils.browserLoaded doesn't work for the about pages, so use a
-// custom page load listener.
-function promisePageLoaded(browser)
-{
- return ContentTask.spawn(browser, null, function* () {
- yield ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true,
- (event) => {
- return event.originalTarget === content.document &&
- event.target.location.href !== "about:blank"
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_bug1015721.js b/browser/base/content/test/general/browser_bug1015721.js
deleted file mode 100644
index e3e715396..000000000
--- a/browser/base/content/test/general/browser_bug1015721.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-"use strict";
-
-const TEST_PAGE = "http://example.org/browser/browser/base/content/test/general/zoom_test.html";
-
-var gTab1, gTab2, gLevel1;
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- gTab1 = gBrowser.addTab();
- gTab2 = gBrowser.addTab();
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoomHelper.load(gTab1, TEST_PAGE);
- yield FullZoomHelper.load(gTab2, TEST_PAGE);
- }).then(zoomTab1, FullZoomHelper.failAndContinue(finish));
-}
-
-function zoomTab1() {
- Task.spawn(function* () {
- is(gBrowser.selectedTab, gTab1, "Tab 1 is selected");
- FullZoomHelper.zoomTest(gTab1, 1, "Initial zoom of tab 1 should be 1");
- FullZoomHelper.zoomTest(gTab2, 1, "Initial zoom of tab 2 should be 1");
-
- let browser1 = gBrowser.getBrowserForTab(gTab1);
- yield BrowserTestUtils.synthesizeMouse(null, 10, 10, {
- wheel: true, ctrlKey: true, deltaY: -1, deltaMode: WheelEvent.DOM_DELTA_LINE
- }, browser1);
-
- info("Waiting for tab 1 to be zoomed");
- yield promiseWaitForCondition(() => {
- gLevel1 = ZoomManager.getZoomForBrowser(browser1);
- return gLevel1 > 1;
- });
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- FullZoomHelper.zoomTest(gTab2, gLevel1, "Tab 2 should have zoomed along with tab 1");
- }).then(finishTest, FullZoomHelper.failAndContinue(finish));
-}
-
-function finishTest() {
- Task.spawn(function* () {
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab1);
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab2);
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug1045809.js b/browser/base/content/test/general/browser_bug1045809.js
deleted file mode 100644
index 63b6b06d5..000000000
--- a/browser/base/content/test/general/browser_bug1045809.js
+++ /dev/null
@@ -1,68 +0,0 @@
-// Test that the Mixed Content Doorhanger Action to re-enable protection works
-
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-
-var origBlockActive;
-
-add_task(function* () {
- registerCleanupFunction(function() {
- Services.prefs.setBoolPref(PREF_ACTIVE, origBlockActive);
- gBrowser.removeCurrentTab();
- });
-
- // Store original preferences so we can restore settings after testing
- origBlockActive = Services.prefs.getBoolPref(PREF_ACTIVE);
-
- // Make sure mixed content blocking is on
- Services.prefs.setBoolPref(PREF_ACTIVE, true);
-
- var url =
- "https://test1.example.com/browser/browser/base/content/test/general/" +
- "file_bug1045809_1.html";
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- // Test 1: mixed content must be blocked
- yield promiseTabLoadEvent(tab, url);
- yield* test1(gBrowser.getBrowserForTab(tab));
-
- yield promiseTabLoadEvent(tab);
- // Test 2: mixed content must NOT be blocked
- yield* test2(gBrowser.getBrowserForTab(tab));
-
- // Test 3: mixed content must be blocked again
- yield promiseTabLoadEvent(tab);
- yield* test3(gBrowser.getBrowserForTab(tab));
-});
-
-function* test1(gTestBrowser) {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
- is(x, null, "Mixed Content is NOT to be found in Test1");
- });
-
- // Disable Mixed Content Protection for the page (and reload)
- gIdentityHandler.disableMixedContentProtection();
-}
-
-function* test2(gTestBrowser) {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
- isnot(x, null, "Mixed Content is to be found in Test2");
- });
-
- // Re-enable Mixed Content Protection for the page (and reload)
- gIdentityHandler.enableMixedContentProtection();
-}
-
-function* test3(gTestBrowser) {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
- is(x, null, "Mixed Content is NOT to be found in Test3");
- });
-}
diff --git a/browser/base/content/test/general/browser_bug1064280_changeUrlInPinnedTab.js b/browser/base/content/test/general/browser_bug1064280_changeUrlInPinnedTab.js
deleted file mode 100644
index 98e0e74db..000000000
--- a/browser/base/content/test/general/browser_bug1064280_changeUrlInPinnedTab.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-add_task(function* () {
- // Test that changing the URL in a pinned tab works correctly
-
- let TEST_LINK_INITIAL = "about:";
- let TEST_LINK_CHANGED = "about:support";
-
- let appTab = gBrowser.addTab(TEST_LINK_INITIAL);
- let browser = appTab.linkedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- gBrowser.pinTab(appTab);
- is(appTab.pinned, true, "Tab was successfully pinned");
-
- let initialTabsNo = gBrowser.tabs.length;
-
- let goButton = document.getElementById("urlbar-go-button");
- gBrowser.selectedTab = appTab;
- gURLBar.focus();
- gURLBar.value = TEST_LINK_CHANGED;
-
- goButton.click();
- yield BrowserTestUtils.browserLoaded(browser);
-
- is(appTab.linkedBrowser.currentURI.spec, TEST_LINK_CHANGED,
- "New page loaded in the app tab");
- is(gBrowser.tabs.length, initialTabsNo, "No additional tabs were opened");
-});
-
-registerCleanupFunction(function () {
- gBrowser.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_bug1261299.js b/browser/base/content/test/general/browser_bug1261299.js
deleted file mode 100644
index 673ef2a0a..000000000
--- a/browser/base/content/test/general/browser_bug1261299.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* -*- 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/. */
-
-/**
- * Tests for Bug 1261299
- * Test that the service menu code path is called properly and the
- * current selection (transferable) is cached properly on the parent process.
- */
-
-add_task(function* test_content_and_chrome_selection()
-{
- let testPage =
- 'data:text/html,' +
- '<textarea id="textarea">Write something here</textarea>';
- let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
- let selectedText;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
- yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
- yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
- {shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
- selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
- is(selectedText, "Write something here", "The macOS services got the selected content text");
-
- gURLBar.value = "test.mozilla.org";
- yield gURLBar.focus();
- yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
- {shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
- selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
- is(selectedText, "test.mozilla.org", "The macOS services got the selected chrome text");
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-// Test switching active selection.
-// Each tab has a content selection and when you switch to that tab, its selection becomes
-// active aka the current selection.
-// Expect: The active selection is what is being sent to OSX service menu.
-
-add_task(function* test_active_selection_switches_properly()
-{
- let testPage1 =
- 'data:text/html,' +
- '<textarea id="textarea">Write something here</textarea>';
- let testPage2 =
- 'data:text/html,' +
- '<textarea id="textarea">Nothing available</textarea>';
- let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
- let selectedText;
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage1);
- yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
- yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
- {shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
-
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage2);
- yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
- yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
- {shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
-
- yield BrowserTestUtils.switchTab(gBrowser, tab1);
- selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
- is(selectedText, "Write something here", "The macOS services got the selected content text");
-
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
- is(selectedText, "Nothing available", "The macOS services got the selected content text");
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/base/content/test/general/browser_bug1297539.js b/browser/base/content/test/general/browser_bug1297539.js
deleted file mode 100644
index d7e675437..000000000
--- a/browser/base/content/test/general/browser_bug1297539.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* -*- 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/. */
-
-/**
- * Test for Bug 1297539
- * Test that the content event "pasteTransferable"
- * (mozilla::EventMessage::eContentCommandPasteTransferable)
- * is handled correctly for plain text and html in the remote case.
- *
- * Original test test_bug525389.html for command content event
- * "pasteTransferable" runs only in the content process.
- * This doesn't test the remote case.
- *
- */
-
-"use strict";
-
-function getLoadContext() {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsILoadContext);
-}
-
-function getTransferableFromClipboard(asHTML) {
- let trans = Cc["@mozilla.org/widget/transferable;1"].
- createInstance(Ci.nsITransferable);
- trans.init(getLoadContext());
- if (asHTML) {
- trans.addDataFlavor("text/html");
- } else {
- trans.addDataFlavor("text/unicode");
- }
- let clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
- clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard);
- return trans;
-}
-
-function* cutCurrentSelection(elementQueryString, property, browser) {
- // Cut the current selection.
- yield BrowserTestUtils.synthesizeKey("x", {accelKey: true}, browser);
-
- // The editor should be empty after cut.
- yield ContentTask.spawn(browser, [elementQueryString, property],
- function* ([contentElementQueryString, contentProperty]) {
- let element = content.document.querySelector(contentElementQueryString);
- is(element[contentProperty], "",
- `${contentElementQueryString} should be empty after cut (superkey + x)`);
- });
-}
-
-// Test that you are able to pasteTransferable for plain text
-// which is handled by TextEditor::PasteTransferable to paste into the editor.
-add_task(function* test_paste_transferable_plain_text()
-{
- let testPage =
- 'data:text/html,' +
- '<textarea id="textarea">Write something here</textarea>';
-
- yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
- // Select all the content in your editor element.
- yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, browser);
- yield BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
-
- yield* cutCurrentSelection("#textarea", "value", browser);
-
- let trans = getTransferableFromClipboard(false);
- let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
- DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
-
- yield ContentTask.spawn(browser, null, function* () {
- let textArea = content.document.querySelector('#textarea');
- is(textArea.value, "Write something here",
- "Send content command pasteTransferable successful");
- });
- });
-});
-
-// Test that you are able to pasteTransferable for html
-// which is handled by HTMLEditor::PasteTransferable to paste into the editor.
-//
-// On Linux,
-// BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
-// doesn't seem to trigger for contenteditable which is why we use
-// Selection to select the contenteditable contents.
-add_task(function* test_paste_transferable_html()
-{
- let testPage =
- 'data:text/html,' +
- '<div contenteditable="true"><b>Bold Text</b><i>italics</i></div>';
-
- yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
- // Select all the content in your editor element.
- yield BrowserTestUtils.synthesizeMouse("div", 0, 0, {}, browser);
- yield ContentTask.spawn(browser, {}, function* () {
- let element = content.document.querySelector("div");
- let selection = content.window.getSelection();
- selection.selectAllChildren(element);
- });
-
- yield* cutCurrentSelection("div", "textContent", browser);
-
- let trans = getTransferableFromClipboard(true);
- let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
- DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
-
- yield ContentTask.spawn(browser, null, function* () {
- let textArea = content.document.querySelector('div');
- is(textArea.innerHTML, "<b>Bold Text</b><i>italics</i>",
- "Send content command pasteTransferable successful");
- });
- });
-});
diff --git a/browser/base/content/test/general/browser_bug1299667.js b/browser/base/content/test/general/browser_bug1299667.js
deleted file mode 100644
index 084c8d49f..000000000
--- a/browser/base/content/test/general/browser_bug1299667.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const { addObserver, removeObserver } = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
-
-function receive(topic) {
- return new Promise((resolve, reject) => {
- let timeout = setTimeout(() => {
- reject(new Error("Timeout"));
- }, 90000);
-
- const observer = {
- observe: subject => {
- removeObserver(observer, topic);
- clearTimeout(timeout);
- resolve(subject);
- }
- };
- addObserver(observer, topic, false);
- });
-}
-
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- content.history.pushState({}, "2", "2.html");
- });
-
- yield receive("sessionstore-state-write-complete");
-
- // Wait for the session data to be flushed before continuing the test
- yield new Promise(resolve => SessionStore.getSessionHistory(gBrowser.selectedTab, resolve));
-
- let backButton = document.getElementById("back-button");
- let contextMenu = document.getElementById("backForwardMenu");
-
- info("waiting for the history menu to open");
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(backButton, {type: "contextmenu", button: 2});
- let event = yield popupShownPromise;
-
- ok(true, "history menu opened");
-
- // Wait for the session data to be flushed before continuing the test
- yield new Promise(resolve => SessionStore.getSessionHistory(gBrowser.selectedTab, resolve));
-
- is(event.target.children.length, 2, "Two history items");
-
- let node = event.target.firstChild;
- is(node.getAttribute("uri"), "http://example.com/2.html", "first item uri");
- is(node.getAttribute("index"), "1", "first item index");
- is(node.getAttribute("historyindex"), "0", "first item historyindex");
-
- node = event.target.lastChild;
- is(node.getAttribute("uri"), "http://example.com/", "second item uri");
- is(node.getAttribute("index"), "0", "second item index");
- is(node.getAttribute("historyindex"), "-1", "second item historyindex");
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- event.target.hidePopup();
- yield popupHiddenPromise;
- info("Hidden popup");
-
- let onClose = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabClose");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield onClose;
- info("Tab closed");
-});
diff --git a/browser/base/content/test/general/browser_bug321000.js b/browser/base/content/test/general/browser_bug321000.js
deleted file mode 100644
index b30b7101d..000000000
--- a/browser/base/content/test/general/browser_bug321000.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * 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/. */
-
-const kTestString = " hello hello \n world\nworld ";
-
-var gTests = [
-
- { desc: "Urlbar strips newlines and surrounding whitespace",
- element: gURLBar,
- expected: kTestString.replace(/\s*\n\s*/g, '')
- },
-
- { desc: "Searchbar replaces newlines with spaces",
- element: document.getElementById('searchbar'),
- expected: kTestString.replace(/\n/g, ' ')
- },
-
-];
-
-// Test for bug 23485 and bug 321000.
-// Urlbar should strip newlines,
-// search bar should replace newlines with spaces.
-function test() {
- waitForExplicitFinish();
-
- let cbHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].
- getService(Ci.nsIClipboardHelper);
-
- // Put a multi-line string in the clipboard.
- // Setting the clipboard value is an async OS operation, so we need to poll
- // the clipboard for valid data before going on.
- waitForClipboard(kTestString, function() { cbHelper.copyString(kTestString); },
- next_test, finish);
-}
-
-function next_test() {
- if (gTests.length)
- test_paste(gTests.shift());
- else
- finish();
-}
-
-function test_paste(aCurrentTest) {
- var element = aCurrentTest.element;
-
- // Register input listener.
- var inputListener = {
- test: aCurrentTest,
- handleEvent: function(event) {
- element.removeEventListener(event.type, this, false);
-
- is(element.value, this.test.expected, this.test.desc);
-
- // Clear the field and go to next test.
- element.value = "";
- setTimeout(next_test, 0);
- }
- }
- element.addEventListener("input", inputListener, false);
-
- // Focus the window.
- window.focus();
- gBrowser.selectedBrowser.focus();
-
- // Focus the element and wait for focus event.
- info("About to focus " + element.id);
- element.addEventListener("focus", function() {
- element.removeEventListener("focus", arguments.callee, false);
- executeSoon(function() {
- // Pasting is async because the Accel+V codepath ends up going through
- // nsDocumentViewer::FireClipboardEvent.
- info("Pasting into " + element.id);
- EventUtils.synthesizeKey("v", { accelKey: true });
- });
- }, false);
- element.focus();
-}
diff --git a/browser/base/content/test/general/browser_bug356571.js b/browser/base/content/test/general/browser_bug356571.js
deleted file mode 100644
index ab689d0f8..000000000
--- a/browser/base/content/test/general/browser_bug356571.js
+++ /dev/null
@@ -1,93 +0,0 @@
-// Bug 356571 - loadOneOrMoreURIs gives up if one of the URLs has an unknown protocol
-
-var Cr = Components.results;
-var Cm = Components.manager;
-
-// Set to true when docShell alerts for unknown protocol error
-var didFail = false;
-
-// Override Alert to avoid blocking the test due to unknown protocol error
-const kPromptServiceUUID = "{6cc9c9fe-bc0b-432b-a410-253ef8bcc699}";
-const kPromptServiceContractID = "@mozilla.org/embedcomp/prompt-service;1";
-
-// Save original prompt service factory
-const kPromptServiceFactory = Cm.getClassObject(Cc[kPromptServiceContractID],
- Ci.nsIFactory);
-
-var fakePromptServiceFactory = {
- createInstance: function(aOuter, aIid) {
- if (aOuter != null)
- throw Cr.NS_ERROR_NO_AGGREGATION;
- return promptService.QueryInterface(aIid);
- }
-};
-
-var promptService = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]),
- alert: function() {
- didFail = true;
- }
-};
-
-/* FIXME
-Cm.QueryInterface(Ci.nsIComponentRegistrar)
- .registerFactory(Components.ID(kPromptServiceUUID), "Prompt Service",
- kPromptServiceContractID, fakePromptServiceFactory);
-*/
-
-const kCompleteState = Ci.nsIWebProgressListener.STATE_STOP +
- Ci.nsIWebProgressListener.STATE_IS_NETWORK;
-
-const kDummyPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-const kURIs = [
- "bad://www.mozilla.org/",
- kDummyPage,
- kDummyPage,
-];
-
-var gProgressListener = {
- _runCount: 0,
- onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
- if ((aStateFlags & kCompleteState) == kCompleteState) {
- if (++this._runCount != kURIs.length)
- return;
- // Check we failed on unknown protocol (received an alert from docShell)
- ok(didFail, "Correctly failed on unknown protocol");
- // Check we opened all tabs
- ok(gBrowser.tabs.length == kURIs.length, "Correctly opened all expected tabs");
- finishTest();
- }
- }
-}
-
-function test() {
- todo(false, "temp. disabled");
- return; /* FIXME */
- /*
- waitForExplicitFinish();
- // Wait for all tabs to finish loading
- gBrowser.addTabsProgressListener(gProgressListener);
- loadOneOrMoreURIs(kURIs.join("|"));
- */
-}
-
-function finishTest() {
- // Unregister the factory so we do not leak
- Cm.QueryInterface(Ci.nsIComponentRegistrar)
- .unregisterFactory(Components.ID(kPromptServiceUUID),
- fakePromptServiceFactory);
-
- // Restore the original factory
- Cm.QueryInterface(Ci.nsIComponentRegistrar)
- .registerFactory(Components.ID(kPromptServiceUUID), "Prompt Service",
- kPromptServiceContractID, kPromptServiceFactory);
-
- // Remove the listener
- gBrowser.removeTabsProgressListener(gProgressListener);
-
- // Close opened tabs
- for (var i = gBrowser.tabs.length-1; i > 0; i--)
- gBrowser.removeTab(gBrowser.tabs[i]);
-
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug380960.js b/browser/base/content/test/general/browser_bug380960.js
deleted file mode 100644
index d6b64543b..000000000
--- a/browser/base/content/test/general/browser_bug380960.js
+++ /dev/null
@@ -1,11 +0,0 @@
-function test() {
- var tab = gBrowser.addTab("about:blank", { skipAnimation: true });
- gBrowser.removeTab(tab);
- is(tab.parentNode, null, "tab removed immediately");
-
- tab = gBrowser.addTab("about:blank", { skipAnimation: true });
- gBrowser.removeTab(tab, { animate: true });
- gBrowser.removeTab(tab);
- is(tab.parentNode, null, "tab removed immediately when calling removeTab again after the animation was kicked off");
-}
-
diff --git a/browser/base/content/test/general/browser_bug386835.js b/browser/base/content/test/general/browser_bug386835.js
deleted file mode 100644
index 1c3ba99c5..000000000
--- a/browser/base/content/test/general/browser_bug386835.js
+++ /dev/null
@@ -1,89 +0,0 @@
-var gTestPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-var gTestImage = "http://example.org/browser/browser/base/content/test/general/moz.png";
-var gTab1, gTab2, gTab3;
-var gLevel;
-const BACK = 0;
-const FORWARD = 1;
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- gTab1 = gBrowser.addTab(gTestPage);
- gTab2 = gBrowser.addTab();
- gTab3 = gBrowser.addTab();
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoomHelper.load(gTab1, gTestPage);
- yield FullZoomHelper.load(gTab2, gTestPage);
- }).then(secondPageLoaded, FullZoomHelper.failAndContinue(finish));
-}
-
-function secondPageLoaded() {
- Task.spawn(function* () {
- FullZoomHelper.zoomTest(gTab1, 1, "Initial zoom of tab 1 should be 1");
- FullZoomHelper.zoomTest(gTab2, 1, "Initial zoom of tab 2 should be 1");
- FullZoomHelper.zoomTest(gTab3, 1, "Initial zoom of tab 3 should be 1");
-
- // Now have three tabs, two with the test page, one blank. Tab 1 is selected
- // Zoom tab 1
- FullZoom.enlarge();
- gLevel = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab1));
-
- ok(gLevel > 1, "New zoom for tab 1 should be greater than 1");
- FullZoomHelper.zoomTest(gTab2, 1, "Zooming tab 1 should not affect tab 2");
- FullZoomHelper.zoomTest(gTab3, 1, "Zooming tab 1 should not affect tab 3");
-
- yield FullZoomHelper.load(gTab3, gTestPage);
- }).then(thirdPageLoaded, FullZoomHelper.failAndContinue(finish));
-}
-
-function thirdPageLoaded() {
- Task.spawn(function* () {
- FullZoomHelper.zoomTest(gTab1, gLevel, "Tab 1 should still be zoomed");
- FullZoomHelper.zoomTest(gTab2, 1, "Tab 2 should still not be affected");
- FullZoomHelper.zoomTest(gTab3, gLevel, "Tab 3 should have zoomed as it was loading in the background");
-
- // Switching to tab 2 should update its zoom setting.
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- FullZoomHelper.zoomTest(gTab1, gLevel, "Tab 1 should still be zoomed");
- FullZoomHelper.zoomTest(gTab2, gLevel, "Tab 2 should be zoomed now");
- FullZoomHelper.zoomTest(gTab3, gLevel, "Tab 3 should still be zoomed");
-
- yield FullZoomHelper.load(gTab1, gTestImage);
- }).then(imageLoaded, FullZoomHelper.failAndContinue(finish));
-}
-
-function imageLoaded() {
- Task.spawn(function* () {
- FullZoomHelper.zoomTest(gTab1, 1, "Zoom should be 1 when image was loaded in the background");
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- FullZoomHelper.zoomTest(gTab1, 1, "Zoom should still be 1 when tab with image is selected");
- }).then(imageZoomSwitch, FullZoomHelper.failAndContinue(finish));
-}
-
-function imageZoomSwitch() {
- Task.spawn(function* () {
- yield FullZoomHelper.navigate(BACK);
- yield FullZoomHelper.navigate(FORWARD);
- FullZoomHelper.zoomTest(gTab1, 1, "Tab 1 should not be zoomed when an image loads");
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- FullZoomHelper.zoomTest(gTab1, 1, "Tab 1 should still not be zoomed when deselected");
- }).then(finishTest, FullZoomHelper.failAndContinue(finish));
-}
-
-var finishTestStarted = false;
-function finishTest() {
- Task.spawn(function* () {
- ok(!finishTestStarted, "finishTest called more than once");
- finishTestStarted = true;
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab1);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab2);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab3);
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug406216.js b/browser/base/content/test/general/browser_bug406216.js
deleted file mode 100644
index e1bd38395..000000000
--- a/browser/base/content/test/general/browser_bug406216.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-/*
- * "TabClose" event is possibly used for closing related tabs of the current.
- * "removeTab" method should work correctly even if the number of tabs are
- * changed while "TabClose" event.
- */
-
-var count = 0;
-const URIS = ["about:config",
- "about:plugins",
- "about:buildconfig",
- "data:text/html,<title>OK</title>"];
-
-function test() {
- waitForExplicitFinish();
- URIS.forEach(addTab);
-}
-
-function addTab(aURI, aIndex) {
- var tab = gBrowser.addTab(aURI);
- if (aIndex == 0)
- gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
-
- tab.linkedBrowser.addEventListener("load", function (event) {
- event.currentTarget.removeEventListener("load", arguments.callee, true);
- if (++count == URIS.length)
- executeSoon(doTabsTest);
- }, true);
-}
-
-function doTabsTest() {
- is(gBrowser.tabs.length, URIS.length, "Correctly opened all expected tabs");
-
- // sample of "close related tabs" feature
- gBrowser.tabContainer.addEventListener("TabClose", function (event) {
- event.currentTarget.removeEventListener("TabClose", arguments.callee, true);
- var closedTab = event.originalTarget;
- var scheme = closedTab.linkedBrowser.currentURI.scheme;
- Array.slice(gBrowser.tabs).forEach(function (aTab) {
- if (aTab != closedTab && aTab.linkedBrowser.currentURI.scheme == scheme)
- gBrowser.removeTab(aTab, {skipPermitUnload: true});
- });
- }, true);
-
- gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
- is(gBrowser.tabs.length, 1, "Related tabs are not closed unexpectedly");
-
- gBrowser.addTab("about:blank");
- gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug408415.js b/browser/base/content/test/general/browser_bug408415.js
deleted file mode 100644
index d8f80f8be..000000000
--- a/browser/base/content/test/general/browser_bug408415.js
+++ /dev/null
@@ -1,45 +0,0 @@
-add_task(function* test() {
- let testPath = getRootDirectory(gTestPath);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (tabBrowser) {
- const URI = testPath + "file_with_favicon.html";
- const expectedIcon = testPath + "file_generic_favicon.ico";
-
- let got_favicon = Promise.defer();
- let listener = {
- onLinkIconAvailable(browser, iconURI) {
- if (got_favicon && iconURI && browser === tabBrowser) {
- got_favicon.resolve(iconURI);
- got_favicon = null;
- }
- }
- };
- gBrowser.addTabsProgressListener(listener);
-
- BrowserTestUtils.loadURI(tabBrowser, URI);
-
- let iconURI = yield got_favicon.promise;
- is(iconURI, expectedIcon, "Correct icon before pushState.");
-
- got_favicon = Promise.defer();
- got_favicon.promise.then(() => { ok(false, "shouldn't be called"); }, (e) => e);
- yield ContentTask.spawn(tabBrowser, null, function() {
- content.location.href += "#foo";
- });
-
- // We've navigated and shouldn't get a call to onLinkIconAvailable.
- TestUtils.executeSoon(() => {
- got_favicon.reject(gBrowser.getIcon(gBrowser.getTabForBrowser(tabBrowser)));
- });
- try {
- yield got_favicon.promise;
- } catch (e) {
- iconURI = e;
- }
- is(iconURI, expectedIcon, "Correct icon after pushState.");
-
- gBrowser.removeTabsProgressListener(listener);
- });
-});
-
diff --git a/browser/base/content/test/general/browser_bug409481.js b/browser/base/content/test/general/browser_bug409481.js
deleted file mode 100644
index 395ad93d4..000000000
--- a/browser/base/content/test/general/browser_bug409481.js
+++ /dev/null
@@ -1,83 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- // XXX This looks a bit odd, but is needed to avoid throwing when removing the
- // event listeners below. See bug 310955.
- document.getElementById("sidebar").addEventListener("load", delayedOpenUrl, true);
- SidebarUI.show("viewWebPanelsSidebar");
-}
-
-function delayedOpenUrl() {
- ok(true, "Ran delayedOpenUrl");
- setTimeout(openPanelUrl, 100);
-}
-
-function openPanelUrl(event) {
- ok(!document.getElementById("sidebar-box").hidden, "Sidebar showing");
-
- var sidebar = document.getElementById("sidebar");
- var root = sidebar.contentDocument.documentElement;
- ok(root.nodeName != "parsererror", "Sidebar is well formed");
-
- sidebar.removeEventListener("load", delayedOpenUrl, true);
- // XXX See comment above
- sidebar.contentDocument.addEventListener("load", delayedRunTest, true);
- var url = 'data:text/html,<div%20id="test_bug409481">Content!</div><a id="link" href="http://www.example.com/ctest">Link</a><input id="textbox">';
- sidebar.contentWindow.loadWebPanel(url);
-}
-
-function delayedRunTest() {
- ok(true, "Ran delayedRunTest");
- setTimeout(runTest, 100);
-}
-
-function runTest(event) {
- var sidebar = document.getElementById("sidebar");
- sidebar.contentDocument.removeEventListener("load", delayedRunTest, true);
-
- var browser = sidebar.contentDocument.getElementById("web-panels-browser");
- var div = browser && browser.contentDocument.getElementById("test_bug409481");
- ok(div && div.textContent == "Content!", "Sidebar content loaded");
-
- var link = browser && browser.contentDocument.getElementById("link");
- sidebar.contentDocument.addEventListener("popupshown", contextMenuOpened, false);
-
- EventUtils.synthesizeMouseAtCenter(link, { type: "contextmenu", button: 2 }, browser.contentWindow);
-}
-
-function contextMenuOpened()
-{
- var sidebar = document.getElementById("sidebar");
- sidebar.contentDocument.removeEventListener("popupshown", contextMenuOpened, false);
-
- var copyLinkCommand = sidebar.contentDocument.getElementById("context-copylink");
- copyLinkCommand.addEventListener("command", copyLinkCommandExecuted, false);
- copyLinkCommand.doCommand();
-}
-
-function copyLinkCommandExecuted(event)
-{
- event.target.removeEventListener("command", copyLinkCommandExecuted, false);
-
- var sidebar = document.getElementById("sidebar");
- var browser = sidebar.contentDocument.getElementById("web-panels-browser");
- var textbox = browser && browser.contentDocument.getElementById("textbox");
- textbox.focus();
- document.commandDispatcher.getControllerForCommand("cmd_paste").doCommand("cmd_paste");
- is(textbox.value, "http://www.example.com/ctest", "copy link command");
-
- sidebar.contentDocument.addEventListener("popuphidden", contextMenuClosed, false);
- event.target.parentNode.hidePopup();
-}
-
-function contextMenuClosed()
-{
- var sidebar = document.getElementById("sidebar");
- sidebar.contentDocument.removeEventListener("popuphidden", contextMenuClosed, false);
-
- SidebarUI.hide();
-
- ok(document.getElementById("sidebar-box").hidden, "Sidebar successfully hidden");
-
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug409624.js b/browser/base/content/test/general/browser_bug409624.js
deleted file mode 100644
index 8e46ec0c2..000000000
--- a/browser/base/content/test/general/browser_bug409624.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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/. */
-
-XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
- "resource://gre/modules/FormHistory.jsm");
-
-add_task(function* test() {
- // This test relies on the form history being empty to start with delete
- // all the items first.
- yield new Promise((resolve, reject) => {
- FormHistory.update({ op: "remove" },
- { handleError(error) {
- reject(error);
- },
- handleCompletion(reason) {
- if (!reason) {
- resolve();
- } else {
- reject();
- }
- },
- });
- });
-
- let prefService = Cc["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefService);
-
- let tempScope = {};
- Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tempScope);
- let Sanitizer = tempScope.Sanitizer;
- let s = new Sanitizer();
- s.prefDomain = "privacy.cpd.";
- let prefBranch = prefService.getBranch(s.prefDomain);
-
- prefBranch.setBoolPref("cache", false);
- prefBranch.setBoolPref("cookies", false);
- prefBranch.setBoolPref("downloads", false);
- prefBranch.setBoolPref("formdata", true);
- prefBranch.setBoolPref("history", false);
- prefBranch.setBoolPref("offlineApps", false);
- prefBranch.setBoolPref("passwords", false);
- prefBranch.setBoolPref("sessions", false);
- prefBranch.setBoolPref("siteSettings", false);
-
- // Sanitize now so we can test the baseline point.
- yield s.sanitize();
- ok(!gFindBar.hasTransactions, "pre-test baseline for sanitizer");
-
- gFindBar.getElement("findbar-textbox").value = "m";
- ok(gFindBar.hasTransactions, "formdata can be cleared after input");
-
- yield s.sanitize();
- is(gFindBar.getElement("findbar-textbox").value, "", "findBar textbox should be empty after sanitize");
- ok(!gFindBar.hasTransactions, "No transactions after sanitize");
-});
diff --git a/browser/base/content/test/general/browser_bug413915.js b/browser/base/content/test/general/browser_bug413915.js
deleted file mode 100644
index 86c94c427..000000000
--- a/browser/base/content/test/general/browser_bug413915.js
+++ /dev/null
@@ -1,62 +0,0 @@
-XPCOMUtils.defineLazyModuleGetter(this, "Feeds",
- "resource:///modules/Feeds.jsm");
-
-function test() {
- var exampleUri = makeURI("http://example.com/");
- var secman = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager);
- var principal = secman.createCodebasePrincipal(exampleUri, {});
-
- function testIsFeed(aTitle, aHref, aType, aKnown) {
- var link = { title: aTitle, href: aHref, type: aType };
- return Feeds.isValidFeed(link, principal, aKnown);
- }
-
- var href = "http://example.com/feed/";
- var atomType = "application/atom+xml";
- var funkyAtomType = " aPPLICAtion/Atom+XML ";
- var rssType = "application/rss+xml";
- var funkyRssType = " Application/RSS+XML ";
- var rdfType = "application/rdf+xml";
- var texmlType = "text/xml";
- var appxmlType = "application/xml";
- var noRss = "Foo";
- var rss = "RSS";
-
- // things that should be valid
- ok(testIsFeed(noRss, href, atomType, false) == atomType,
- "detect Atom feed");
- ok(testIsFeed(noRss, href, funkyAtomType, false) == atomType,
- "clean up and detect Atom feed");
- ok(testIsFeed(noRss, href, rssType, false) == rssType,
- "detect RSS feed");
- ok(testIsFeed(noRss, href, funkyRssType, false) == rssType,
- "clean up and detect RSS feed");
-
- // things that should not be feeds
- ok(testIsFeed(noRss, href, rdfType, false) == null,
- "should not detect RDF non-feed");
- ok(testIsFeed(rss, href, rdfType, false) == null,
- "should not detect RDF feed from type and title");
- ok(testIsFeed(noRss, href, texmlType, false) == null,
- "should not detect text/xml non-feed");
- ok(testIsFeed(rss, href, texmlType, false) == null,
- "should not detect text/xml feed from type and title");
- ok(testIsFeed(noRss, href, appxmlType, false) == null,
- "should not detect application/xml non-feed");
- ok(testIsFeed(rss, href, appxmlType, false) == null,
- "should not detect application/xml feed from type and title");
-
- // security check only, returns cleaned up type or "application/rss+xml"
- ok(testIsFeed(noRss, href, atomType, true) == atomType,
- "feed security check should return Atom type");
- ok(testIsFeed(noRss, href, funkyAtomType, true) == atomType,
- "feed security check should return cleaned up Atom type");
- ok(testIsFeed(noRss, href, rssType, true) == rssType,
- "feed security check should return RSS type");
- ok(testIsFeed(noRss, href, funkyRssType, true) == rssType,
- "feed security check should return cleaned up RSS type");
- ok(testIsFeed(noRss, href, "", true) == rssType,
- "feed security check without type should return RSS type");
- ok(testIsFeed(noRss, href, "garbage", true) == "garbage",
- "feed security check with garbage type should return garbage");
-}
diff --git a/browser/base/content/test/general/browser_bug416661.js b/browser/base/content/test/general/browser_bug416661.js
deleted file mode 100644
index a37971a34..000000000
--- a/browser/base/content/test/general/browser_bug416661.js
+++ /dev/null
@@ -1,43 +0,0 @@
-var tabElm, zoomLevel;
-function start_test_prefNotSet() {
- Task.spawn(function* () {
- is(ZoomManager.zoom, 1, "initial zoom level should be 1");
- FullZoom.enlarge();
-
- // capture the zoom level to test later
- zoomLevel = ZoomManager.zoom;
- isnot(zoomLevel, 1, "zoom level should have changed");
-
- yield FullZoomHelper.load(gBrowser.selectedTab, "http://mochi.test:8888/browser/browser/base/content/test/general/moz.png");
- }).then(continue_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
-}
-
-function continue_test_prefNotSet () {
- Task.spawn(function* () {
- is(ZoomManager.zoom, 1, "zoom level pref should not apply to an image");
- yield FullZoom.reset();
-
- yield FullZoomHelper.load(gBrowser.selectedTab, "http://mochi.test:8888/browser/browser/base/content/test/general/zoom_test.html");
- }).then(end_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
-}
-
-function end_test_prefNotSet() {
- Task.spawn(function* () {
- is(ZoomManager.zoom, zoomLevel, "the zoom level should have persisted");
-
- // Reset the zoom so that other tests have a fresh zoom level
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange();
- finish();
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- tabElm = gBrowser.addTab();
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tabElm);
- yield FullZoomHelper.load(tabElm, "http://mochi.test:8888/browser/browser/base/content/test/general/zoom_test.html");
- }).then(start_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug417483.js b/browser/base/content/test/general/browser_bug417483.js
deleted file mode 100644
index 43ff7b917..000000000
--- a/browser/base/content/test/general/browser_bug417483.js
+++ /dev/null
@@ -1,30 +0,0 @@
-add_task(function* () {
- let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, true);
- const htmlContent = "data:text/html, <iframe src='data:text/html,text text'></iframe>";
- gBrowser.loadURI(htmlContent);
- yield loadedPromise;
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) {
- let frame = content.frames[0];
- let sel = frame.getSelection();
- let range = frame.document.createRange();
- let tn = frame.document.body.childNodes[0];
- range.setStart(tn, 4);
- range.setEnd(tn, 5);
- sel.addRange(range);
- frame.focus();
- });
-
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouse("frame", 5, 5,
- { type: "contextmenu", button: 2}, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- ok(document.getElementById("frame-sep").hidden, "'frame-sep' should be hidden if the selection contains only spaces");
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
-});
diff --git a/browser/base/content/test/general/browser_bug419612.js b/browser/base/content/test/general/browser_bug419612.js
deleted file mode 100644
index 8c34b2d39..000000000
--- a/browser/base/content/test/general/browser_bug419612.js
+++ /dev/null
@@ -1,32 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- let testPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
- let tab1 = gBrowser.addTab();
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab1);
- yield FullZoomHelper.load(tab1, testPage);
-
- let tab2 = gBrowser.addTab();
- yield FullZoomHelper.load(tab2, testPage);
-
- FullZoom.enlarge();
- let tab1Zoom = ZoomManager.getZoomForBrowser(tab1.linkedBrowser);
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab2);
- let tab2Zoom = ZoomManager.getZoomForBrowser(tab2.linkedBrowser);
- is(tab2Zoom, tab1Zoom, "Zoom should affect background tabs");
-
- gPrefService.setBoolPref("browser.zoom.updateBackgroundTabs", false);
- yield FullZoom.reset();
- gBrowser.selectedTab = tab1;
- tab1Zoom = ZoomManager.getZoomForBrowser(tab1.linkedBrowser);
- tab2Zoom = ZoomManager.getZoomForBrowser(tab2.linkedBrowser);
- isnot(tab1Zoom, tab2Zoom, "Zoom should not affect background tabs");
-
- if (gPrefService.prefHasUserValue("browser.zoom.updateBackgroundTabs"))
- gPrefService.clearUserPref("browser.zoom.updateBackgroundTabs");
- yield FullZoomHelper.removeTabAndWaitForLocationChange(tab1);
- yield FullZoomHelper.removeTabAndWaitForLocationChange(tab2);
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug422590.js b/browser/base/content/test/general/browser_bug422590.js
deleted file mode 100644
index f26919cc5..000000000
--- a/browser/base/content/test/general/browser_bug422590.js
+++ /dev/null
@@ -1,50 +0,0 @@
-function test() {
- waitForExplicitFinish();
- // test the main (normal) browser window
- testCustomize(window, testChromeless);
-}
-
-function testChromeless() {
- // test a chromeless window
- var newWin = openDialog(getBrowserURL(), "_blank",
- "chrome,dialog=no,location=yes,toolbar=no", "about:blank");
- ok(newWin, "got new window");
-
- whenDelayedStartupFinished(newWin, function () {
- // Check that the search bar is hidden
- var searchBar = newWin.BrowserSearch.searchBar;
- ok(searchBar, "got search bar");
-
- var searchBarBO = searchBar.boxObject;
- is(searchBarBO.width, 0, "search bar hidden");
- is(searchBarBO.height, 0, "search bar hidden");
-
- testCustomize(newWin, function () {
- newWin.close();
- finish();
- });
- });
-}
-
-function testCustomize(aWindow, aCallback) {
- var fileMenu = aWindow.document.getElementById("file-menu");
- ok(fileMenu, "got file menu");
- is(fileMenu.disabled, false, "file menu initially enabled");
-
- openToolbarCustomizationUI(function () {
- // Can't use the property, since the binding may have since been removed
- // if the element is hidden (see bug 422590)
- is(fileMenu.getAttribute("disabled"), "true",
- "file menu is disabled during toolbar customization");
-
- closeToolbarCustomizationUI(onClose, aWindow);
- }, aWindow);
-
- function onClose() {
- is(fileMenu.getAttribute("disabled"), "false",
- "file menu is enabled after toolbar customization");
-
- if (aCallback)
- aCallback();
- }
-}
diff --git a/browser/base/content/test/general/browser_bug423833.js b/browser/base/content/test/general/browser_bug423833.js
deleted file mode 100644
index d4069338b..000000000
--- a/browser/base/content/test/general/browser_bug423833.js
+++ /dev/null
@@ -1,138 +0,0 @@
-/* Tests for proper behaviour of "Show this frame" context menu options */
-
-// Two frames, one with text content, the other an error page
-var invalidPage = 'http://127.0.0.1:55555/';
-var validPage = 'http://example.com/';
-var testPage = 'data:text/html,<frameset cols="400,400"><frame src="' + validPage + '"><frame src="' + invalidPage + '"></frameset>';
-
-// Store the tab and window created in tests 2 and 3 respectively
-var test2tab;
-var test3window;
-
-// We use setInterval instead of setTimeout to avoid race conditions on error doc loads
-var intervalID;
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.selectedBrowser.addEventListener("load", test1Setup, true);
- content.location = testPage;
-}
-
-function test1Setup() {
- if (content.frames.length < 2 ||
- content.frames[1].location != invalidPage)
- // The error frame hasn't loaded yet
- return;
-
- gBrowser.selectedBrowser.removeEventListener("load", test1Setup, true);
-
- var badFrame = content.frames[1];
- document.popupNode = badFrame.document.firstChild;
-
- var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- var contextMenu = new nsContextMenu(contentAreaContextMenu);
-
- // We'd like to use another load listener here, but error pages don't fire load events
- contextMenu.showOnlyThisFrame();
- intervalID = setInterval(testShowOnlyThisFrame, 3000);
-}
-
-function testShowOnlyThisFrame() {
- if (content.location.href == testPage)
- // This is a stale event from the original page loading
- return;
-
- // We should now have loaded the error page frame content directly
- // in the tab, make sure the URL is right.
- clearInterval(intervalID);
-
- is(content.location.href, invalidPage, "Should navigate to page url, not about:neterror");
-
- // Go back to the frames page
- gBrowser.addEventListener("load", test2Setup, true);
- content.location = testPage;
-}
-
-function test2Setup() {
- if (content.frames.length < 2 ||
- content.frames[1].location != invalidPage)
- // The error frame hasn't loaded yet
- return;
-
- gBrowser.removeEventListener("load", test2Setup, true);
-
- // Now let's do the whole thing again, but this time for "Open frame in new tab"
- var badFrame = content.frames[1];
-
- document.popupNode = badFrame.document.firstChild;
-
- var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- var contextMenu = new nsContextMenu(contentAreaContextMenu);
-
- gBrowser.tabContainer.addEventListener("TabOpen", function (event) {
- test2tab = event.target;
- gBrowser.tabContainer.removeEventListener("TabOpen", arguments.callee, false);
- }, false);
- contextMenu.openFrameInTab();
- ok(test2tab, "openFrameInTab() opened a tab");
-
- gBrowser.selectedTab = test2tab;
-
- intervalID = setInterval(testOpenFrameInTab, 3000);
-}
-
-function testOpenFrameInTab() {
- if (gBrowser.contentDocument.location.href == "about:blank")
- // Wait another cycle
- return;
-
- clearInterval(intervalID);
-
- // We should now have the error page in a new, active tab.
- is(gBrowser.contentDocument.location.href, invalidPage, "New tab should have page url, not about:neterror");
-
- // Clear up the new tab, and punt to test 3
- gBrowser.removeCurrentTab();
-
- test3Setup();
-}
-
-function test3Setup() {
- // One more time, for "Open frame in new window"
- var badFrame = content.frames[1];
- document.popupNode = badFrame.document.firstChild;
-
- var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- var contextMenu = new nsContextMenu(contentAreaContextMenu);
-
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened")
- test3window = aSubject;
- Services.ww.unregisterNotification(arguments.callee);
- });
-
- contextMenu.openFrame();
-
- intervalID = setInterval(testOpenFrame, 3000);
-}
-
-function testOpenFrame() {
- if (!test3window || test3window.content.location.href == "about:blank") {
- info("testOpenFrame: Wait another cycle");
- return;
- }
-
- clearInterval(intervalID);
-
- is(test3window.content.location.href, invalidPage, "New window should have page url, not about:neterror");
-
- test3window.close();
- cleanup();
-}
-
-function cleanup() {
- gBrowser.removeCurrentTab();
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug424101.js b/browser/base/content/test/general/browser_bug424101.js
deleted file mode 100644
index 8000d2ae9..000000000
--- a/browser/base/content/test/general/browser_bug424101.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Make sure that the context menu appears on form elements */
-
-add_task(function *() {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/html,test");
-
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
-
- let tests = [
- { element: "input", type: "text" },
- { element: "input", type: "password" },
- { element: "input", type: "image" },
- { element: "input", type: "button" },
- { element: "input", type: "submit" },
- { element: "input", type: "reset" },
- { element: "input", type: "checkbox" },
- { element: "input", type: "radio" },
- { element: "button" },
- { element: "select" },
- { element: "option" },
- { element: "optgroup" }
- ];
-
- for (let index = 0; index < tests.length; index++) {
- let test = tests[index];
-
- yield ContentTask.spawn(gBrowser.selectedBrowser,
- { element: test.element, type: test.type, index: index },
- function* (arg) {
- let element = content.document.createElement(arg.element);
- element.id = "element" + arg.index;
- if (arg.type) {
- element.setAttribute("type", arg.type);
- }
- content.document.body.appendChild(element);
- });
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter("#element" + index,
- { type: "contextmenu", button: 2}, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- let typeAttr = test.type ? "type=" + test.type + " " : "";
- is(gContextMenu.shouldDisplay, true,
- "context menu behavior for <" + test.element + " " + typeAttr + "> is wrong");
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
- }
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug427559.js b/browser/base/content/test/general/browser_bug427559.js
deleted file mode 100644
index 78cecdefa..000000000
--- a/browser/base/content/test/general/browser_bug427559.js
+++ /dev/null
@@ -1,38 +0,0 @@
-"use strict";
-
-/*
- * Test bug 427559 to make sure focused elements that are no longer on the page
- * will have focus transferred to the window when changing tabs back to that
- * tab with the now-gone element.
- */
-
-// Default focus on a button and have it kill itself on blur.
-const URL = 'data:text/html;charset=utf-8,' +
- '<body><button onblur="this.remove()">' +
- '<script>document.body.firstChild.focus()</script></body>';
-
-function getFocusedLocalName(browser) {
- return ContentTask.spawn(browser, null, function* () {
- return content.document.activeElement.localName;
- });
-}
-
-add_task(function* () {
- let testTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL);
-
- let browser = testTab.linkedBrowser;
-
- is((yield getFocusedLocalName(browser)), "button", "button is focused");
-
- let blankTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- yield BrowserTestUtils.switchTab(gBrowser, testTab);
-
- // Make sure focus is given to the window because the element is now gone.
- is((yield getFocusedLocalName(browser)), "body", "body is focused");
-
- // Cleanup.
- gBrowser.removeTab(blankTab);
- gBrowser.removeCurrentTab();
-
-});
diff --git a/browser/base/content/test/general/browser_bug431826.js b/browser/base/content/test/general/browser_bug431826.js
deleted file mode 100644
index 592ea9cef..000000000
--- a/browser/base/content/test/general/browser_bug431826.js
+++ /dev/null
@@ -1,50 +0,0 @@
-function remote(task) {
- return ContentTask.spawn(gBrowser.selectedBrowser, null, task);
-}
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
-
- let promise = remote(function () {
- return ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true, event => {
- return content.document.documentURI != "about:blank";
- }).then(() => 0); // don't want to send the event to the chrome process
- });
- gBrowser.loadURI("https://nocert.example.com/");
- yield promise;
-
- yield remote(() => {
- // Confirm that we are displaying the contributed error page, not the default
- let uri = content.document.documentURI;
- Assert.ok(uri.startsWith("about:certerror"), "Broken page should go to about:certerror, not about:neterror");
- });
-
- yield remote(() => {
- let div = content.document.getElementById("badCertAdvancedPanel");
- // Confirm that the expert section is collapsed
- Assert.ok(div, "Advanced content div should exist");
- Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
- "none", "Advanced content should not be visible by default");
- });
-
- // Tweak the expert mode pref
- gPrefService.setBoolPref("browser.xul.error_pages.expert_bad_cert", true);
-
- promise = remote(function () {
- return ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true);
- });
- gBrowser.reload();
- yield promise;
-
- yield remote(() => {
- let div = content.document.getElementById("badCertAdvancedPanel");
- Assert.ok(div, "Advanced content div should exist");
- Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
- "block", "Advanced content should be visible by default");
- });
-
- // Clean up
- gBrowser.removeCurrentTab();
- if (gPrefService.prefHasUserValue("browser.xul.error_pages.expert_bad_cert"))
- gPrefService.clearUserPref("browser.xul.error_pages.expert_bad_cert");
-});
diff --git a/browser/base/content/test/general/browser_bug432599.js b/browser/base/content/test/general/browser_bug432599.js
deleted file mode 100644
index a5f7c0b5e..000000000
--- a/browser/base/content/test/general/browser_bug432599.js
+++ /dev/null
@@ -1,127 +0,0 @@
-function invokeUsingCtrlD(phase) {
- switch (phase) {
- case 1:
- EventUtils.synthesizeKey("d", { accelKey: true });
- break;
- case 2:
- case 4:
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- break;
- case 3:
- EventUtils.synthesizeKey("d", { accelKey: true });
- EventUtils.synthesizeKey("d", { accelKey: true });
- break;
- }
-}
-
-function invokeUsingStarButton(phase) {
- switch (phase) {
- case 1:
- EventUtils.synthesizeMouseAtCenter(BookmarkingUI.star, {});
- break;
- case 2:
- case 4:
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- break;
- case 3:
- EventUtils.synthesizeMouseAtCenter(BookmarkingUI.star,
- { clickCount: 2 });
- break;
- }
-}
-
-var testURL = "data:text/plain,Content";
-var bookmarkId;
-
-function add_bookmark(aURI, aTitle) {
- return PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI, PlacesUtils.bookmarks.DEFAULT_INDEX,
- aTitle);
-}
-
-// test bug 432599
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.selectedBrowser.addEventListener("load", function onLoad() {
- gBrowser.selectedBrowser.removeEventListener("load", onLoad, true);
- waitForStarChange(false, initTest);
- }, true);
-
- content.location = testURL;
-}
-
-function initTest() {
- // First, bookmark the page.
- bookmarkId = add_bookmark(makeURI(testURL), "Bug 432599 Test");
-
- checkBookmarksPanel(invokers[currentInvoker], 1);
-}
-
-function waitForStarChange(aValue, aCallback) {
- let expectedStatus = aValue ? BookmarkingUI.STATUS_STARRED
- : BookmarkingUI.STATUS_UNSTARRED;
- if (BookmarkingUI.status == BookmarkingUI.STATUS_UPDATING ||
- BookmarkingUI.status != expectedStatus) {
- info("Waiting for star button change.");
- setTimeout(waitForStarChange, 50, aValue, aCallback);
- return;
- }
- aCallback();
-}
-
-var invokers = [invokeUsingStarButton, invokeUsingCtrlD];
-var currentInvoker = 0;
-
-var initialValue;
-var initialRemoveHidden;
-
-var popupElement = document.getElementById("editBookmarkPanel");
-var titleElement = document.getElementById("editBookmarkPanelTitle");
-var removeElement = document.getElementById("editBookmarkPanelRemoveButton");
-
-function checkBookmarksPanel(invoker, phase)
-{
- let onPopupShown = function(aEvent) {
- if (aEvent.originalTarget == popupElement) {
- popupElement.removeEventListener("popupshown", arguments.callee, false);
- checkBookmarksPanel(invoker, phase + 1);
- }
- };
- let onPopupHidden = function(aEvent) {
- if (aEvent.originalTarget == popupElement) {
- popupElement.removeEventListener("popuphidden", arguments.callee, false);
- if (phase < 4) {
- checkBookmarksPanel(invoker, phase + 1);
- } else {
- ++currentInvoker;
- if (currentInvoker < invokers.length) {
- checkBookmarksPanel(invokers[currentInvoker], 1);
- } else {
- gBrowser.removeTab(gBrowser.selectedTab, {skipPermitUnload: true});
- PlacesUtils.bookmarks.removeItem(bookmarkId);
- executeSoon(finish);
- }
- }
- }
- };
-
- switch (phase) {
- case 1:
- case 3:
- popupElement.addEventListener("popupshown", onPopupShown, false);
- break;
- case 2:
- popupElement.addEventListener("popuphidden", onPopupHidden, false);
- initialValue = titleElement.value;
- initialRemoveHidden = removeElement.hidden;
- break;
- case 4:
- popupElement.addEventListener("popuphidden", onPopupHidden, false);
- is(titleElement.value, initialValue, "The bookmark panel's title should be the same");
- is(removeElement.hidden, initialRemoveHidden, "The bookmark panel's visibility should not change");
- break;
- }
- invoker(phase);
-}
diff --git a/browser/base/content/test/general/browser_bug435035.js b/browser/base/content/test/general/browser_bug435035.js
deleted file mode 100644
index 7570ef0d7..000000000
--- a/browser/base/content/test/general/browser_bug435035.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => {
- is(document.getElementById("identity-box").className,
- "unknownIdentity mixedDisplayContent",
- "identity box has class name for mixed content");
-
- gBrowser.removeCurrentTab();
- finish();
- });
-
- gBrowser.loadURI(
- "https://example.com/browser/browser/base/content/test/general/test_bug435035.html"
- );
-}
diff --git a/browser/base/content/test/general/browser_bug435325.js b/browser/base/content/test/general/browser_bug435325.js
deleted file mode 100644
index 2ae15deff..000000000
--- a/browser/base/content/test/general/browser_bug435325.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* Ensure that clicking the button in the Offline mode neterror page makes the browser go online. See bug 435325. */
-
-var proxyPrefValue;
-
-function test() {
- waitForExplicitFinish();
-
- // Go offline and disable the proxy and cache, then try to load the test URL.
- Services.io.offline = true;
-
- // Tests always connect to localhost, and per bug 87717, localhost is now
- // reachable in offline mode. To avoid this, disable any proxy.
- proxyPrefValue = Services.prefs.getIntPref("network.proxy.type");
- Services.prefs.setIntPref("network.proxy.type", 0);
-
- Services.prefs.setBoolPref("browser.cache.disk.enable", false);
- Services.prefs.setBoolPref("browser.cache.memory.enable", false);
-
- gBrowser.selectedTab = gBrowser.addTab("http://example.com/");
-
- let contentScript = `
- let listener = function () {
- removeEventListener("DOMContentLoaded", listener);
- sendAsyncMessage("Test:DOMContentLoaded", { uri: content.document.documentURI });
- };
- addEventListener("DOMContentLoaded", listener);
- `;
-
- function pageloaded({ data }) {
- mm.removeMessageListener("Test:DOMContentLoaded", pageloaded);
- checkPage(data);
- }
-
- let mm = gBrowser.selectedBrowser.messageManager;
- mm.addMessageListener("Test:DOMContentLoaded", pageloaded);
- mm.loadFrameScript("data:," + contentScript, true);
-}
-
-function checkPage(data) {
- ok(Services.io.offline, "Setting Services.io.offline to true.");
-
- is(data.uri.substring(0, 27),
- "about:neterror?e=netOffline", "Loading the Offline mode neterror page.");
-
- // Re-enable the proxy so example.com is resolved to localhost, rather than
- // the actual example.com.
- Services.prefs.setIntPref("network.proxy.type", proxyPrefValue);
-
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- ok(!Services.io.offline, "After clicking the Try Again button, we're back " +
- "online.");
- Services.obs.removeObserver(observer, "network:offline-status-changed", false);
- finish();
- }, "network:offline-status-changed", false);
-
- ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- content.document.getElementById("errorTryAgain").click();
- });
-}
-
-registerCleanupFunction(function() {
- Services.prefs.setBoolPref("browser.cache.disk.enable", true);
- Services.prefs.setBoolPref("browser.cache.memory.enable", true);
- Services.io.offline = false;
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug441778.js b/browser/base/content/test/general/browser_bug441778.js
deleted file mode 100644
index fa938541f..000000000
--- a/browser/base/content/test/general/browser_bug441778.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-/*
- * Test the fix for bug 441778 to ensure site-specific page zoom doesn't get
- * modified by sub-document loads of content from a different domain.
- */
-
-function test() {
- waitForExplicitFinish();
-
- const TEST_PAGE_URL = 'data:text/html,<body><iframe src=""></iframe></body>';
- const TEST_IFRAME_URL = "http://test2.example.org/";
-
- Task.spawn(function* () {
- // Prepare the test tab
- let tab = gBrowser.addTab();
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab);
-
- let testBrowser = tab.linkedBrowser;
-
- yield FullZoomHelper.load(tab, TEST_PAGE_URL);
-
- // Change the zoom level and then save it so we can compare it to the level
- // after loading the sub-document.
- FullZoom.enlarge();
- var zoomLevel = ZoomManager.zoom;
-
- // Start the sub-document load.
- let deferred = Promise.defer();
- executeSoon(function () {
- BrowserTestUtils.browserLoaded(testBrowser, true).then(url => {
- is(url, TEST_IFRAME_URL, "got the load event for the iframe");
- is(ZoomManager.zoom, zoomLevel, "zoom is retained after sub-document load");
-
- FullZoomHelper.removeTabAndWaitForLocationChange().
- then(() => deferred.resolve());
- });
- ContentTask.spawn(testBrowser, TEST_IFRAME_URL, url => {
- content.document.querySelector("iframe").src = url;
- });
- });
- yield deferred.promise;
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug455852.js b/browser/base/content/test/general/browser_bug455852.js
deleted file mode 100644
index ce883b581..000000000
--- a/browser/base/content/test/general/browser_bug455852.js
+++ /dev/null
@@ -1,20 +0,0 @@
-add_task(function*() {
- is(gBrowser.tabs.length, 1, "one tab is open");
-
- gBrowser.selectedBrowser.focus();
- isnot(document.activeElement, gURLBar.inputField, "location bar is not focused");
-
- var tab = gBrowser.selectedTab;
- gPrefService.setBoolPref("browser.tabs.closeWindowWithLastTab", false);
-
- let tabClosedPromise = BrowserTestUtils.removeTab(tab, {dontRemove: true});
- EventUtils.synthesizeKey("w", { accelKey: true });
- yield tabClosedPromise;
-
- is(tab.parentNode, null, "ctrl+w removes the tab");
- is(gBrowser.tabs.length, 1, "a new tab has been opened");
- is(document.activeElement, gURLBar.inputField, "location bar is focused for the new tab");
-
- if (gPrefService.prefHasUserValue("browser.tabs.closeWindowWithLastTab"))
- gPrefService.clearUserPref("browser.tabs.closeWindowWithLastTab");
-});
diff --git a/browser/base/content/test/general/browser_bug460146.js b/browser/base/content/test/general/browser_bug460146.js
deleted file mode 100644
index 1fdf0921c..000000000
--- a/browser/base/content/test/general/browser_bug460146.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Check proper image url retrieval from all kinds of elements/styles */
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- gBrowser.selectedBrowser.addEventListener("load", function () {
- gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
-
- var pageInfo = BrowserPageInfo(gBrowser.selectedBrowser.currentURI.spec,
- "mediaTab");
-
- pageInfo.addEventListener("load", function () {
- pageInfo.removeEventListener("load", arguments.callee, true);
- pageInfo.onFinished.push(function () {
- executeSoon(function () {
- var imageTree = pageInfo.document.getElementById("imagetree");
- var imageRowsNum = imageTree.view.rowCount;
-
- ok(imageTree, "Image tree is null (media tab is broken)");
-
- ok(imageRowsNum == 7, "Number of images listed: " +
- imageRowsNum + ", should be 7");
-
- pageInfo.close();
- gBrowser.removeCurrentTab();
- finish();
- });
- });
- }, true);
- }, true);
-
- content.location =
- "data:text/html," +
- "<html>" +
- " <head>" +
- " <title>Test for media tab</title>" +
- " <link rel='shortcut icon' href='file:///dummy_icon.ico'>" + // Icon
- " </head>" +
- " <body style='background-image:url(about:logo?a);'>" + // Background
- " <img src='file:///dummy_image.gif'>" + // Image
- " <ul>" +
- " <li style='list-style:url(about:logo?b);'>List Item 1</li>" + // Bullet
- " </ul> " +
- " <div style='-moz-border-image: url(about:logo?c) 20 20 20 20;'>test</div>" + // Border
- " <a href='' style='cursor: url(about:logo?d),default;'>test link</a>" + // Cursor
- " <object type='image/svg+xml' width=20 height=20 data='file:///dummy_object.svg'></object>" + // Object
- " </body>" +
- "</html>";
-}
diff --git a/browser/base/content/test/general/browser_bug462289.js b/browser/base/content/test/general/browser_bug462289.js
deleted file mode 100644
index 1ce79f07e..000000000
--- a/browser/base/content/test/general/browser_bug462289.js
+++ /dev/null
@@ -1,81 +0,0 @@
-var tab1, tab2;
-
-function focus_in_navbar()
-{
- var parent = document.activeElement.parentNode;
- while (parent && parent.id != "nav-bar")
- parent = parent.parentNode;
-
- return parent != null;
-}
-
-function test()
-{
- waitForExplicitFinish();
-
- tab1 = gBrowser.addTab("about:blank", {skipAnimation: true});
- tab2 = gBrowser.addTab("about:blank", {skipAnimation: true});
-
- EventUtils.synthesizeMouseAtCenter(tab1, {});
- executeSoon(step2);
-}
-
-function step2()
-{
- is(gBrowser.selectedTab, tab1, "1st click on tab1 selects tab");
- isnot(document.activeElement, tab1, "1st click on tab1 does not activate tab");
-
- EventUtils.synthesizeMouseAtCenter(tab1, {});
- executeSoon(step3);
-}
-
-function step3()
-{
- is(gBrowser.selectedTab, tab1, "2nd click on selected tab1 keeps tab selected");
- isnot(document.activeElement, tab1, "2nd click on selected tab1 does not activate tab");
-
- ok(true, "focusing URLBar then sending 1 Shift+Tab.");
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
- is(gBrowser.selectedTab, tab1, "tab key to selected tab1 keeps tab selected");
- is(document.activeElement, tab1, "tab key to selected tab1 activates tab");
-
- EventUtils.synthesizeMouseAtCenter(tab1, {});
- executeSoon(step4);
-}
-
-function step4()
-{
- is(gBrowser.selectedTab, tab1, "3rd click on activated tab1 keeps tab selected");
- is(document.activeElement, tab1, "3rd click on activated tab1 keeps tab activated");
-
- gBrowser.addEventListener("TabSwitchDone", step5);
- EventUtils.synthesizeMouseAtCenter(tab2, {});
-}
-
-function step5()
-{
- gBrowser.removeEventListener("TabSwitchDone", step5);
-
- // The tabbox selects a tab within a setTimeout in a bubbling mousedown event
- // listener, and focuses the current tab if another tab previously had focus.
- is(gBrowser.selectedTab, tab2, "click on tab2 while tab1 is activated selects tab");
- is(document.activeElement, tab2, "click on tab2 while tab1 is activated activates tab");
-
- info("focusing content then sending middle-button mousedown to tab2.");
- gBrowser.selectedBrowser.focus();
-
- EventUtils.synthesizeMouseAtCenter(tab2, {button: 1, type: "mousedown"});
- executeSoon(step6);
-}
-
-function step6()
-{
- is(gBrowser.selectedTab, tab2, "middle-button mousedown on selected tab2 keeps tab selected");
- isnot(document.activeElement, tab2, "middle-button mousedown on selected tab2 does not activate tab");
-
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab1);
-
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug462673.js b/browser/base/content/test/general/browser_bug462673.js
deleted file mode 100644
index f5b090917..000000000
--- a/browser/base/content/test/general/browser_bug462673.js
+++ /dev/null
@@ -1,36 +0,0 @@
-add_task(function* () {
- var win = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
- yield SimpleTest.promiseFocus(win);
-
- let tab = win.gBrowser.tabContainer.firstChild;
- yield promiseTabLoadEvent(tab, getRootDirectory(gTestPath) + "test_bug462673.html");
-
- is(win.gBrowser.browsers.length, 2, "test_bug462673.html has opened a second tab");
- is(win.gBrowser.selectedTab, tab.nextSibling, "dependent tab is selected");
- win.gBrowser.removeTab(tab);
-
- // Closing a tab will also close its parent chrome window, but async
- yield promiseWindowWillBeClosed(win);
-});
-
-add_task(function* () {
- var win = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
- yield SimpleTest.promiseFocus(win);
-
- let tab = win.gBrowser.tabContainer.firstChild;
- yield promiseTabLoadEvent(tab, getRootDirectory(gTestPath) + "test_bug462673.html");
-
- var newTab = win.gBrowser.addTab();
- var newBrowser = newTab.linkedBrowser;
- win.gBrowser.removeTab(tab);
- ok(!win.closed, "Window stays open");
- if (!win.closed) {
- is(win.gBrowser.tabContainer.childElementCount, 1, "Window has one tab");
- is(win.gBrowser.browsers.length, 1, "Window has one browser");
- is(win.gBrowser.selectedTab, newTab, "Remaining tab is selected");
- is(win.gBrowser.selectedBrowser, newBrowser, "Browser for remaining tab is selected");
- is(win.gBrowser.mTabBox.selectedPanel, newBrowser.parentNode.parentNode.parentNode.parentNode, "Panel for remaining tab is selected");
- }
-
- yield promiseWindowClosed(win);
-});
diff --git a/browser/base/content/test/general/browser_bug477014.js b/browser/base/content/test/general/browser_bug477014.js
deleted file mode 100644
index 8a0fac6d8..000000000
--- a/browser/base/content/test/general/browser_bug477014.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-// That's a gecko!
-const iconURLSpec = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==";
-var testPage="data:text/plain,test bug 477014";
-
-add_task(function*() {
- let tabToDetach = gBrowser.addTab(testPage);
- yield waitForDocLoadComplete(tabToDetach.linkedBrowser);
-
- gBrowser.setIcon(tabToDetach, iconURLSpec,
- Services.scriptSecurityManager.getSystemPrincipal());
- tabToDetach.setAttribute("busy", "true");
-
- // detach and set the listener on the new window
- let newWindow = gBrowser.replaceTabWithWindow(tabToDetach);
- yield promiseWaitForEvent(tabToDetach.linkedBrowser, "SwapDocShells");
-
- is(newWindow.gBrowser.selectedTab.hasAttribute("busy"), true, "Busy attribute should be correct");
- is(newWindow.gBrowser.getIcon(), iconURLSpec, "Icon should be correct");
-
- newWindow.close();
-});
diff --git a/browser/base/content/test/general/browser_bug479408.js b/browser/base/content/test/general/browser_bug479408.js
deleted file mode 100644
index 0dfa96f2e..000000000
--- a/browser/base/content/test/general/browser_bug479408.js
+++ /dev/null
@@ -1,17 +0,0 @@
-function test() {
- waitForExplicitFinish();
- let tab = gBrowser.selectedTab = gBrowser.addTab(
- "http://mochi.test:8888/browser/browser/base/content/test/general/browser_bug479408_sample.html");
-
- gBrowser.addEventListener("DOMLinkAdded", function(aEvent) {
- gBrowser.removeEventListener("DOMLinkAdded", arguments.callee, true);
-
- executeSoon(function() {
- ok(!tab.linkedBrowser.engines,
- "the subframe's search engine wasn't detected");
-
- gBrowser.removeTab(tab);
- finish();
- });
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_bug479408_sample.html b/browser/base/content/test/general/browser_bug479408_sample.html
deleted file mode 100644
index f83f02bb9..000000000
--- a/browser/base/content/test/general/browser_bug479408_sample.html
+++ /dev/null
@@ -1,4 +0,0 @@
-<!DOCTYPE html>
-<title>Testcase for bug 479408</title>
-
-<iframe src='data:text/html,<link%20rel="search"%20type="application/opensearchdescription+xml"%20title="Search%20bug%20479408"%20href="http://example.com/search.xml">'>
diff --git a/browser/base/content/test/general/browser_bug481560.js b/browser/base/content/test/general/browser_bug481560.js
deleted file mode 100644
index bb9249e75..000000000
--- a/browser/base/content/test/general/browser_bug481560.js
+++ /dev/null
@@ -1,21 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- whenNewWindowLoaded(null, function (win) {
- waitForFocus(function () {
- function onTabClose() {
- ok(false, "shouldn't have gotten the TabClose event for the last tab");
- }
- var tab = win.gBrowser.selectedTab;
- tab.addEventListener("TabClose", onTabClose, false);
-
- EventUtils.synthesizeKey("w", { accelKey: true }, win);
-
- ok(win.closed, "accel+w closed the window immediately");
-
- tab.removeEventListener("TabClose", onTabClose, false);
-
- finish();
- }, win);
- });
-}
diff --git a/browser/base/content/test/general/browser_bug484315.js b/browser/base/content/test/general/browser_bug484315.js
deleted file mode 100644
index fb23ae33a..000000000
--- a/browser/base/content/test/general/browser_bug484315.js
+++ /dev/null
@@ -1,23 +0,0 @@
-function test() {
- var contentWin = window.open("about:blank", "", "width=100,height=100");
- var enumerator = Services.wm.getEnumerator("navigator:browser");
-
- while (enumerator.hasMoreElements()) {
- let win = enumerator.getNext();
- if (win.content == contentWin) {
- gPrefService.setBoolPref("browser.tabs.closeWindowWithLastTab", false);
- win.gBrowser.removeCurrentTab();
- ok(win.closed, "popup is closed");
-
- // clean up
- if (!win.closed)
- win.close();
- if (gPrefService.prefHasUserValue("browser.tabs.closeWindowWithLastTab"))
- gPrefService.clearUserPref("browser.tabs.closeWindowWithLastTab");
-
- return;
- }
- }
-
- throw "couldn't find the content window";
-}
diff --git a/browser/base/content/test/general/browser_bug491431.js b/browser/base/content/test/general/browser_bug491431.js
deleted file mode 100644
index d270e912e..000000000
--- a/browser/base/content/test/general/browser_bug491431.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* 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/. */
-
-var testPage = "data:text/plain,test bug 491431 Page";
-
-function test() {
- waitForExplicitFinish();
-
- let newWin, tabA, tabB;
-
- // test normal close
- tabA = gBrowser.addTab(testPage);
- gBrowser.tabContainer.addEventListener("TabClose", function(firstTabCloseEvent) {
- gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
- ok(!firstTabCloseEvent.detail.adoptedBy, "This was a normal tab close");
-
- // test tab close by moving
- tabB = gBrowser.addTab(testPage);
- gBrowser.tabContainer.addEventListener("TabClose", function(secondTabCloseEvent) {
- gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
- executeSoon(function() {
- ok(secondTabCloseEvent.detail.adoptedBy, "This was a tab closed by moving");
-
- // cleanup
- newWin.close();
- executeSoon(finish);
- });
- }, true);
- newWin = gBrowser.replaceTabWithWindow(tabB);
- }, true);
- gBrowser.removeTab(tabA);
-}
-
diff --git a/browser/base/content/test/general/browser_bug495058.js b/browser/base/content/test/general/browser_bug495058.js
deleted file mode 100644
index a82c6c931..000000000
--- a/browser/base/content/test/general/browser_bug495058.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Tests that the right elements of a tab are focused when it is
- * torn out into its own window.
- */
-
-const URIS = [
- "about:blank",
- "about:sessionrestore",
- "about:privatebrowsing",
-];
-
-add_task(function*() {
- for (let uri of URIS) {
- let tab = gBrowser.addTab();
- yield BrowserTestUtils.loadURI(tab.linkedBrowser, uri);
-
- let win = gBrowser.replaceTabWithWindow(tab);
- yield TestUtils.topicObserved("browser-delayed-startup-finished",
- subject => subject == win);
- tab = win.gBrowser.selectedTab;
-
- // BrowserTestUtils doesn't get the add-on shims, which means that
- // MozAfterPaint won't get shimmed over if we add an event handler
- // for it in the parent.
- if (tab.linkedBrowser.isRemoteBrowser) {
- yield BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "MozAfterPaint");
- } else {
- yield BrowserTestUtils.waitForEvent(tab.linkedBrowser, "MozAfterPaint");
- }
-
- Assert.equal(win.gBrowser.currentURI.spec, uri, uri + ": uri loaded in detached tab");
- Assert.equal(win.document.activeElement, win.gBrowser.selectedBrowser, uri + ": browser is focused");
- Assert.equal(win.gURLBar.value, "", uri + ": urlbar is empty");
- Assert.ok(win.gURLBar.placeholder, uri + ": placeholder text is present");
-
- yield BrowserTestUtils.closeWindow(win);
- }
-});
diff --git a/browser/base/content/test/general/browser_bug517902.js b/browser/base/content/test/general/browser_bug517902.js
deleted file mode 100644
index bc1d16f4b..000000000
--- a/browser/base/content/test/general/browser_bug517902.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Make sure that "View Image Info" loads the correct image data */
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- gBrowser.selectedBrowser.addEventListener("load", function () {
- gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
-
- var doc = gBrowser.contentDocument;
- var testImg = doc.getElementById("test-image");
- var pageInfo = BrowserPageInfo(gBrowser.selectedBrowser.currentURI.spec,
- "mediaTab", testImg);
-
- pageInfo.addEventListener("load", function () {
- pageInfo.removeEventListener("load", arguments.callee, true);
- pageInfo.onFinished.push(function () {
- executeSoon(function () {
- var pageInfoImg = pageInfo.document.getElementById("thepreviewimage");
-
- is(pageInfoImg.src, testImg.src, "selected image has the correct source");
- is(pageInfoImg.width, testImg.width, "selected image has the correct width");
- is(pageInfoImg.height, testImg.height, "selected image has the correct height");
-
- pageInfo.close();
- gBrowser.removeCurrentTab();
- finish();
- });
- });
- }, true);
- }, true);
-
- content.location =
- "data:text/html," +
- "<style type='text/css'>%23test-image,%23not-test-image {background-image: url('about:logo?c');}</style>" +
- "<img src='about:logo?b' height=300 width=350 alt=2 id='not-test-image'>" +
- "<img src='about:logo?b' height=300 width=350 alt=2>" +
- "<img src='about:logo?a' height=200 width=250>" +
- "<img src='about:logo?b' height=200 width=250 alt=1>" +
- "<img src='about:logo?b' height=100 width=150 alt=2 id='test-image'>";
-}
diff --git a/browser/base/content/test/general/browser_bug519216.js b/browser/base/content/test/general/browser_bug519216.js
deleted file mode 100644
index d3a517086..000000000
--- a/browser/base/content/test/general/browser_bug519216.js
+++ /dev/null
@@ -1,45 +0,0 @@
-function test() {
- waitForExplicitFinish();
- gBrowser.addProgressListener(progressListener1);
- gBrowser.addProgressListener(progressListener2);
- gBrowser.addProgressListener(progressListener3);
- gBrowser.loadURI("data:text/plain,bug519216");
-}
-
-var calledListener1 = false;
-var progressListener1 = {
- onLocationChange: function onLocationChange() {
- calledListener1 = true;
- gBrowser.removeProgressListener(this);
- }
-};
-
-var calledListener2 = false;
-var progressListener2 = {
- onLocationChange: function onLocationChange() {
- ok(calledListener1, "called progressListener1 before progressListener2");
- calledListener2 = true;
- gBrowser.removeProgressListener(this);
- }
-};
-
-var progressListener3 = {
- onLocationChange: function onLocationChange() {
- ok(calledListener2, "called progressListener2 before progressListener3");
- gBrowser.removeProgressListener(this);
- gBrowser.addProgressListener(progressListener4);
- executeSoon(function () {
- expectListener4 = true;
- gBrowser.reload();
- });
- }
-};
-
-var expectListener4 = false;
-var progressListener4 = {
- onLocationChange: function onLocationChange() {
- ok(expectListener4, "didn't call progressListener4 for the first location change");
- gBrowser.removeProgressListener(this);
- executeSoon(finish);
- }
-};
diff --git a/browser/base/content/test/general/browser_bug520538.js b/browser/base/content/test/general/browser_bug520538.js
deleted file mode 100644
index e0b64db9d..000000000
--- a/browser/base/content/test/general/browser_bug520538.js
+++ /dev/null
@@ -1,15 +0,0 @@
-function test() {
- var tabCount = gBrowser.tabs.length;
- gBrowser.selectedBrowser.focus();
- browserDOMWindow.openURI(makeURI("about:blank"),
- null,
- Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
- Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
- is(gBrowser.tabs.length, tabCount + 1,
- "'--new-tab about:blank' opens a new tab");
- is(gBrowser.selectedTab, gBrowser.tabs[tabCount],
- "'--new-tab about:blank' selects the new tab");
- is(document.activeElement, gURLBar.inputField,
- "'--new-tab about:blank' focuses the location bar");
- gBrowser.removeCurrentTab();
-}
diff --git a/browser/base/content/test/general/browser_bug521216.js b/browser/base/content/test/general/browser_bug521216.js
deleted file mode 100644
index 735ae92f6..000000000
--- a/browser/base/content/test/general/browser_bug521216.js
+++ /dev/null
@@ -1,50 +0,0 @@
-var expected = ["TabOpen", "onStateChange", "onLocationChange", "onLinkIconAvailable"];
-var actual = [];
-var tabIndex = -1;
-this.__defineGetter__("tab", () => gBrowser.tabs[tabIndex]);
-
-function test() {
- waitForExplicitFinish();
- tabIndex = gBrowser.tabs.length;
- gBrowser.addTabsProgressListener(progressListener);
- gBrowser.tabContainer.addEventListener("TabOpen", TabOpen, false);
- gBrowser.addTab("data:text/html,<html><head><link href='about:logo' rel='shortcut icon'>");
-}
-
-function record(aName) {
- info("got " + aName);
- if (actual.indexOf(aName) == -1)
- actual.push(aName);
- if (actual.length == expected.length) {
- is(actual.toString(), expected.toString(),
- "got events and progress notifications in expected order");
-
- executeSoon(function(tab) {
- gBrowser.removeTab(tab);
- gBrowser.removeTabsProgressListener(progressListener);
- gBrowser.tabContainer.removeEventListener("TabOpen", TabOpen, false);
- finish();
- }.bind(null, tab));
- }
-}
-
-function TabOpen(aEvent) {
- if (aEvent.target == tab)
- record(arguments.callee.name);
-}
-
-var progressListener = {
- onLocationChange: function onLocationChange(aBrowser) {
- if (aBrowser == tab.linkedBrowser)
- record(arguments.callee.name);
- },
- onStateChange: function onStateChange(aBrowser) {
- if (aBrowser == tab.linkedBrowser)
- record(arguments.callee.name);
- },
- onLinkIconAvailable: function onLinkIconAvailable(aBrowser, aIconURL) {
- if (aBrowser == tab.linkedBrowser &&
- aIconURL == "about:logo")
- record(arguments.callee.name);
- }
-};
diff --git a/browser/base/content/test/general/browser_bug533232.js b/browser/base/content/test/general/browser_bug533232.js
deleted file mode 100644
index 6c7a0e51f..000000000
--- a/browser/base/content/test/general/browser_bug533232.js
+++ /dev/null
@@ -1,36 +0,0 @@
-function test() {
- var tab1 = gBrowser.selectedTab;
- var tab2 = gBrowser.addTab();
- var childTab1;
- var childTab2;
-
- childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
- gBrowser.selectedTab = childTab1;
- gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
- is(idx(gBrowser.selectedTab), idx(tab1),
- "closing a tab next to its parent selects the parent");
-
- childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
- gBrowser.selectedTab = tab2;
- gBrowser.selectedTab = childTab1;
- gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
- is(idx(gBrowser.selectedTab), idx(tab2),
- "closing a tab next to its parent doesn't select the parent if another tab had been selected ad interim");
-
- gBrowser.selectedTab = tab1;
- childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
- childTab2 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
- gBrowser.selectedTab = childTab1;
- gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
- is(idx(gBrowser.selectedTab), idx(childTab2),
- "closing a tab next to its parent selects the next tab with the same parent");
- gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
- is(idx(gBrowser.selectedTab), idx(tab2),
- "closing the last tab in a set of child tabs doesn't go back to the parent");
-
- gBrowser.removeTab(tab2, { skipPermitUnload: true });
-}
-
-function idx(tab) {
- return Array.indexOf(gBrowser.tabs, tab);
-}
diff --git a/browser/base/content/test/general/browser_bug537013.js b/browser/base/content/test/general/browser_bug537013.js
deleted file mode 100644
index 5ae1586ea..000000000
--- a/browser/base/content/test/general/browser_bug537013.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* Tests for bug 537013 to ensure proper tab-sequestration of find bar. */
-
-var tabs = [];
-var texts = [
- "This side up.",
- "The world is coming to an end. Please log off.",
- "Klein bottle for sale. Inquire within.",
- "To err is human; to forgive is not company policy."
-];
-
-var Clipboard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
-var HasFindClipboard = Clipboard.supportsFindClipboard();
-
-function addTabWithText(aText, aCallback) {
- let newTab = gBrowser.addTab("data:text/html;charset=utf-8,<h1 id='h1'>" +
- aText + "</h1>");
- tabs.push(newTab);
- gBrowser.selectedTab = newTab;
-}
-
-function setFindString(aString) {
- gFindBar.open();
- gFindBar._findField.focus();
- gFindBar._findField.select();
- EventUtils.sendString(aString);
- is(gFindBar._findField.value, aString, "Set the field correctly!");
-}
-
-var newWindow;
-
-function test() {
- waitForExplicitFinish();
- registerCleanupFunction(function () {
- while (tabs.length) {
- gBrowser.removeTab(tabs.pop());
- }
- });
- texts.forEach(aText => addTabWithText(aText));
-
- // Set up the first tab
- gBrowser.selectedTab = tabs[0];
-
- setFindString(texts[0]);
- // Turn on highlight for testing bug 891638
- gFindBar.toggleHighlight(true);
-
- // Make sure the second tab is correct, then set it up
- gBrowser.selectedTab = tabs[1];
- gBrowser.selectedTab.addEventListener("TabFindInitialized", continueTests1);
- // Initialize the findbar
- gFindBar;
-}
-function continueTests1() {
- gBrowser.selectedTab.removeEventListener("TabFindInitialized",
- continueTests1);
- ok(true, "'TabFindInitialized' event properly dispatched!");
- ok(gFindBar.hidden, "Second tab doesn't show find bar!");
- gFindBar.open();
- is(gFindBar._findField.value, texts[0],
- "Second tab kept old find value for new initialization!");
- setFindString(texts[1]);
-
- // Confirm the first tab is still correct, ensure re-hiding works as expected
- gBrowser.selectedTab = tabs[0];
- ok(!gFindBar.hidden, "First tab shows find bar!");
- // When the Find Clipboard is supported, this test not relevant.
- if (!HasFindClipboard)
- is(gFindBar._findField.value, texts[0], "First tab persists find value!");
- ok(gFindBar.getElement("highlight").checked,
- "Highlight button state persists!");
-
- // While we're here, let's test the backout of bug 253793.
- gBrowser.reload();
- gBrowser.addEventListener("DOMContentLoaded", continueTests2, true);
-}
-
-function continueTests2() {
- gBrowser.removeEventListener("DOMContentLoaded", continueTests2, true);
- ok(gFindBar.getElement("highlight").checked, "Highlight never reset!");
- continueTests3();
-}
-
-function continueTests3() {
- ok(gFindBar.getElement("highlight").checked, "Highlight button reset!");
- gFindBar.close();
- ok(gFindBar.hidden, "First tab doesn't show find bar!");
- gBrowser.selectedTab = tabs[1];
- ok(!gFindBar.hidden, "Second tab shows find bar!");
- // Test for bug 892384
- is(gFindBar._findField.getAttribute("focused"), "true",
- "Open findbar refocused on tab change!");
- gURLBar.focus();
- gBrowser.selectedTab = tabs[0];
- ok(gFindBar.hidden, "First tab doesn't show find bar!");
-
- // Set up a third tab, no tests here
- gBrowser.selectedTab = tabs[2];
- setFindString(texts[2]);
-
- // Now we jump to the second, then first, and then fourth
- gBrowser.selectedTab = tabs[1];
- // Test for bug 892384
- ok(!gFindBar._findField.hasAttribute("focused"),
- "Open findbar not refocused on tab change!");
- gBrowser.selectedTab = tabs[0];
- gBrowser.selectedTab = tabs[3];
- ok(gFindBar.hidden, "Fourth tab doesn't show find bar!");
- is(gFindBar, gBrowser.getFindBar(), "Find bar is right one!");
- gFindBar.open();
- // Disabled the following assertion due to intermittent failure on OSX 10.6 Debug.
- if (!HasFindClipboard) {
- is(gFindBar._findField.value, texts[1],
- "Fourth tab has second tab's find value!");
- }
-
- newWindow = gBrowser.replaceTabWithWindow(tabs.pop());
- whenDelayedStartupFinished(newWindow, checkNewWindow);
-}
-
-// Test that findbar gets restored when a tab is moved to a new window.
-function checkNewWindow() {
- ok(!newWindow.gFindBar.hidden, "New window shows find bar!");
- // Disabled the following assertion due to intermittent failure on OSX 10.6 Debug.
- if (!HasFindClipboard) {
- is(newWindow.gFindBar._findField.value, texts[1],
- "New window find bar has correct find value!");
- }
- ok(!newWindow.gFindBar.getElement("find-next").disabled,
- "New window findbar has enabled buttons!");
- newWindow.close();
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug537474.js b/browser/base/content/test/general/browser_bug537474.js
deleted file mode 100644
index f1139f235..000000000
--- a/browser/base/content/test/general/browser_bug537474.js
+++ /dev/null
@@ -1,8 +0,0 @@
-add_task(function *() {
- let browserLoadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- browserDOMWindow.openURI(makeURI("about:"), null,
- Ci.nsIBrowserDOMWindow.OPEN_CURRENTWINDOW, null)
- yield browserLoadedPromise;
- is(gBrowser.currentURI.spec, "about:", "page loads in the current content window");
-});
-
diff --git a/browser/base/content/test/general/browser_bug550565.js b/browser/base/content/test/general/browser_bug550565.js
deleted file mode 100644
index b0e094e07..000000000
--- a/browser/base/content/test/general/browser_bug550565.js
+++ /dev/null
@@ -1,44 +0,0 @@
-add_task(function* test() {
- let testPath = getRootDirectory(gTestPath);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (tabBrowser) {
- const URI = testPath + "file_with_favicon.html";
- const expectedIcon = testPath + "file_generic_favicon.ico";
-
- let got_favicon = Promise.defer();
- let listener = {
- onLinkIconAvailable(browser, iconURI) {
- if (got_favicon && iconURI && browser === tabBrowser) {
- got_favicon.resolve(iconURI);
- got_favicon = null;
- }
- }
- };
- gBrowser.addTabsProgressListener(listener);
-
- BrowserTestUtils.loadURI(tabBrowser, URI);
-
- let iconURI = yield got_favicon.promise;
- is(iconURI, expectedIcon, "Correct icon before pushState.");
-
- got_favicon = Promise.defer();
- got_favicon.promise.then(() => { ok(false, "shouldn't be called"); }, (e) => e);
- yield ContentTask.spawn(tabBrowser, null, function() {
- content.history.pushState("page2", "page2", "page2");
- });
-
- // We've navigated and shouldn't get a call to onLinkIconAvailable.
- TestUtils.executeSoon(() => {
- got_favicon.reject(gBrowser.getIcon(gBrowser.getTabForBrowser(tabBrowser)));
- });
- try {
- yield got_favicon.promise;
- } catch (e) {
- iconURI = e;
- }
- is(iconURI, expectedIcon, "Correct icon after pushState.");
-
- gBrowser.removeTabsProgressListener(listener);
- });
-});
diff --git a/browser/base/content/test/general/browser_bug553455.js b/browser/base/content/test/general/browser_bug553455.js
deleted file mode 100644
index c29a810de..000000000
--- a/browser/base/content/test/general/browser_bug553455.js
+++ /dev/null
@@ -1,1200 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const TESTROOT = "http://example.com/browser/toolkit/mozapps/extensions/test/xpinstall/";
-const TESTROOT2 = "http://example.org/browser/toolkit/mozapps/extensions/test/xpinstall/";
-const SECUREROOT = "https://example.com/browser/toolkit/mozapps/extensions/test/xpinstall/";
-const XPINSTALL_URL = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
-const PREF_INSTALL_REQUIREBUILTINCERTS = "extensions.install.requireBuiltInCerts";
-const PROGRESS_NOTIFICATION = "addon-progress";
-
-const { REQUIRE_SIGNING } = Cu.import("resource://gre/modules/addons/AddonConstants.jsm", {});
-const { Task } = Cu.import("resource://gre/modules/Task.jsm");
-
-var rootDir = getRootDirectory(gTestPath);
-var rootPath = rootDir.split('/');
-var chromeName = rootPath[0] + '//' + rootPath[2];
-var croot = chromeName + "/content/browser/toolkit/mozapps/extensions/test/xpinstall/";
-var jar = getJar(croot);
-if (jar) {
- var tmpdir = extractJarToTmp(jar);
- croot = 'file://' + tmpdir.path + '/';
-}
-const CHROMEROOT = croot;
-
-var gApp = document.getElementById("bundle_brand").getString("brandShortName");
-var gVersion = Services.appinfo.version;
-
-function getObserverTopic(aNotificationId) {
- let topic = aNotificationId;
- if (topic == "xpinstall-disabled")
- topic = "addon-install-disabled";
- else if (topic == "addon-progress")
- topic = "addon-install-started";
- else if (topic == "addon-install-restart")
- topic = "addon-install-complete";
- return topic;
-}
-
-function waitForProgressNotification(aPanelOpen = false, aExpectedCount = 1) {
- return Task.spawn(function* () {
- let notificationId = PROGRESS_NOTIFICATION;
- info("Waiting for " + notificationId + " notification");
-
- let topic = getObserverTopic(notificationId);
-
- let observerPromise = new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
- // Ignore the progress notification unless that is the notification we want
- if (notificationId != PROGRESS_NOTIFICATION &&
- aTopic == getObserverTopic(PROGRESS_NOTIFICATION)) {
- return;
- }
- Services.obs.removeObserver(observer, topic);
- resolve();
- }, topic, false);
- });
-
- let panelEventPromise;
- if (aPanelOpen) {
- panelEventPromise = Promise.resolve();
- } else {
- panelEventPromise = new Promise(resolve => {
- PopupNotifications.panel.addEventListener("popupshowing", function eventListener() {
- PopupNotifications.panel.removeEventListener("popupshowing", eventListener);
- resolve();
- });
- });
- }
-
- yield observerPromise;
- yield panelEventPromise;
-
- info("Saw a notification");
- ok(PopupNotifications.isPanelOpen, "Panel should be open");
- is(PopupNotifications.panel.childNodes.length, aExpectedCount, "Should be the right number of notifications");
- if (PopupNotifications.panel.childNodes.length) {
- let nodes = Array.from(PopupNotifications.panel.childNodes);
- let notification = nodes.find(n => n.id == notificationId + "-notification");
- ok(notification, `Should have seen the right notification`);
- }
-
- return PopupNotifications.panel;
- });
-}
-
-function waitForNotification(aId, aExpectedCount = 1) {
- return Task.spawn(function* () {
- info("Waiting for " + aId + " notification");
-
- let topic = getObserverTopic(aId);
-
- let observerPromise = new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
- // Ignore the progress notification unless that is the notification we want
- if (aId != PROGRESS_NOTIFICATION &&
- aTopic == getObserverTopic(PROGRESS_NOTIFICATION)) {
- return;
- }
- Services.obs.removeObserver(observer, topic);
- resolve();
- }, topic, false);
- });
-
- let panelEventPromise = new Promise(resolve => {
- PopupNotifications.panel.addEventListener("PanelUpdated", function eventListener(e) {
- // Skip notifications that are not the one that we are supposed to be looking for
- if (e.detail.indexOf(aId) == -1) {
- return;
- }
- PopupNotifications.panel.removeEventListener("PanelUpdated", eventListener);
- resolve();
- });
- });
-
- yield observerPromise;
- yield panelEventPromise;
-
- info("Saw a notification");
- ok(PopupNotifications.isPanelOpen, "Panel should be open");
- is(PopupNotifications.panel.childNodes.length, aExpectedCount, "Should be the right number of notifications");
- if (PopupNotifications.panel.childNodes.length) {
- let nodes = Array.from(PopupNotifications.panel.childNodes);
- let notification = nodes.find(n => n.id == aId + "-notification");
- ok(notification, `Should have seen the right notification`);
- }
-
- return PopupNotifications.panel;
- });
-}
-
-function waitForNotificationClose() {
- return new Promise(resolve => {
- info("Waiting for notification to close");
- PopupNotifications.panel.addEventListener("popuphidden", function listener() {
- PopupNotifications.panel.removeEventListener("popuphidden", listener, false);
- resolve();
- }, false);
- });
-}
-
-function waitForInstallDialog() {
- return Task.spawn(function* () {
- if (Preferences.get("xpinstall.customConfirmationUI", false)) {
- yield waitForNotification("addon-install-confirmation");
- return;
- }
-
- info("Waiting for install dialog");
-
- let window = yield new Promise(resolve => {
- Services.wm.addListener({
- onOpenWindow: function(aXULWindow) {
- Services.wm.removeListener(this);
- resolve(aXULWindow);
- },
- onCloseWindow: function(aXULWindow) {
- },
- onWindowTitleChange: function(aXULWindow, aNewTitle) {
- }
- });
- });
- info("Install dialog opened, waiting for focus");
-
- let domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- yield new Promise(resolve => {
- waitForFocus(function() {
- resolve();
- }, domwindow);
- });
- info("Saw install dialog");
- is(domwindow.document.location.href, XPINSTALL_URL, "Should have seen the right window open");
-
- // Override the countdown timer on the accept button
- let button = domwindow.document.documentElement.getButton("accept");
- button.disabled = false;
-
- return;
- });
-}
-
-function removeTab() {
- return Promise.all([
- waitForNotificationClose(),
- BrowserTestUtils.removeTab(gBrowser.selectedTab)
- ]);
-}
-
-function acceptInstallDialog() {
- if (Preferences.get("xpinstall.customConfirmationUI", false)) {
- document.getElementById("addon-install-confirmation-accept").click();
- } else {
- let win = Services.wm.getMostRecentWindow("Addons:Install");
- win.document.documentElement.acceptDialog();
- }
-}
-
-function cancelInstallDialog() {
- if (Preferences.get("xpinstall.customConfirmationUI", false)) {
- document.getElementById("addon-install-confirmation-cancel").click();
- } else {
- let win = Services.wm.getMostRecentWindow("Addons:Install");
- win.document.documentElement.cancelDialog();
- }
-}
-
-function waitForSingleNotification(aCallback) {
- return Task.spawn(function* () {
- while (PopupNotifications.panel.childNodes.length == 2) {
- yield new Promise(resolve => executeSoon(resolve));
-
- info("Waiting for single notification");
- // Notification should never close while we wait
- ok(PopupNotifications.isPanelOpen, "Notification should still be open");
- }
- });
-}
-
-function setupRedirect(aSettings) {
- var url = "https://example.com/browser/toolkit/mozapps/extensions/test/xpinstall/redirect.sjs?mode=setup";
- for (var name in aSettings) {
- url += "&" + name + "=" + aSettings[name];
- }
-
- var req = new XMLHttpRequest();
- req.open("GET", url, false);
- req.send(null);
-}
-
-function getInstalls() {
- return new Promise(resolve => {
- AddonManager.getAllInstalls(installs => resolve(installs));
- });
-}
-
-var TESTS = [
-function test_disabledInstall() {
- return Task.spawn(function* () {
- Services.prefs.setBoolPref("xpinstall.enabled", false);
-
- let notificationPromise = waitForNotification("xpinstall-disabled");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Enable", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "Software installation is currently disabled. Click Enable and try again.");
-
- let closePromise = waitForNotificationClose();
- // Click on Enable
- EventUtils.synthesizeMouseAtCenter(notification.button, {});
- yield closePromise;
-
- try {
- ok(Services.prefs.getBoolPref("xpinstall.enabled"), "Installation should be enabled");
- }
- catch (e) {
- ok(false, "xpinstall.enabled should be set");
- }
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- let installs = yield getInstalls();
- is(installs.length, 0, "Shouldn't be any pending installs");
- });
-},
-
-function test_blockedInstall() {
- return Task.spawn(function* () {
- let notificationPromise = waitForNotification("addon-install-blocked");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Allow", "Should have seen the right button");
- is(notification.getAttribute("origin"), "example.com",
- "Should have seen the right origin host");
- is(notification.getAttribute("label"),
- gApp + " prevented this site from asking you to install software on your computer.",
- "Should have seen the right message");
-
- let dialogPromise = waitForInstallDialog();
- // Click on Allow
- EventUtils.synthesizeMouse(notification.button, 20, 10, {});
- // Notification should have changed to progress notification
- ok(PopupNotifications.isPanelOpen, "Notification should still be open");
- notification = panel.childNodes[0];
- is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
- yield dialogPromise;
-
- notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- panel = yield notificationPromise;
-
- notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "XPI Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
- yield removeTab();
- });
-},
-
-function test_whitelistedInstall() {
- return Task.spawn(function* () {
- let originalTab = gBrowser.selectedTab;
- let tab;
- gBrowser.selectedTab = originalTab;
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?"
- + triggers).then(newTab => tab = newTab);
- yield progressPromise;
- yield dialogPromise;
- yield BrowserTestUtils.waitForCondition(() => !!tab, "tab should be present");
-
- is(gBrowser.selectedTab, tab,
- "tab selected in response to the addon-install-confirmation notification");
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "XPI Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_failedDownload() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let failPromise = waitForNotification("addon-install-failed");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "missing.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- let panel = yield failPromise;
-
- let notification = panel.childNodes[0];
- is(notification.getAttribute("label"),
- "The add-on could not be downloaded because of a connection failure.",
- "Should have seen the right message");
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_corruptFile() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let failPromise = waitForNotification("addon-install-failed");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "corrupt.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- let panel = yield failPromise;
-
- let notification = panel.childNodes[0];
- is(notification.getAttribute("label"),
- "The add-on downloaded from this site could not be installed " +
- "because it appears to be corrupt.",
- "Should have seen the right message");
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_incompatible() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let failPromise = waitForNotification("addon-install-failed");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "incompatible.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- let panel = yield failPromise;
-
- let notification = panel.childNodes[0];
- is(notification.getAttribute("label"),
- "XPI Test could not be installed because it is not compatible with " +
- gApp + " " + gVersion + ".",
- "Should have seen the right message");
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_restartless() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "restartless.xpi"
- }));
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-complete");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.getAttribute("label"),
- "XPI Test has been installed successfully.",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 0, "Should be no pending installs");
-
- let addon = yield new Promise(resolve => {
- AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", result => {
- resolve(result);
- });
- });
- addon.uninstall();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
-
- let closePromise = waitForNotificationClose();
- gBrowser.removeTab(gBrowser.selectedTab);
- yield closePromise;
- });
-},
-
-function test_multiple() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Unsigned XPI": "amosigned.xpi",
- "Restartless XPI": "restartless.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- let panel = yield progressPromise;
- yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "2 add-ons will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
-
- let addon = yield new Promise(resolve => {
- AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function (result) {
- resolve(result);
- });
- });
- addon.uninstall();
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_sequential() {
- return Task.spawn(function* () {
- // This test is only relevant if using the new doorhanger UI
- if (!Preferences.get("xpinstall.customConfirmationUI", false)) {
- return;
- }
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Restartless XPI": "restartless.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- // Should see the right add-on
- let container = document.getElementById("addon-install-confirmation-content");
- is(container.childNodes.length, 1, "Should be one item listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
-
- progressPromise = waitForProgressNotification(true, 2);
- triggers = encodeURIComponent(JSON.stringify({
- "Theme XPI": "theme.xpi"
- }));
- gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
-
- // Should still have the right add-on in the confirmation notification
- is(container.childNodes.length, 1, "Should be one item listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
-
- // Wait for the install to complete, we won't see a new confirmation
- // notification
- yield new Promise(resolve => {
- Services.obs.addObserver(function observer() {
- Services.obs.removeObserver(observer, "addon-install-confirmation");
- resolve();
- }, "addon-install-confirmation", false);
- });
-
- // Make sure browser-addons.js executes first
- yield new Promise(resolve => executeSoon(resolve));
-
- // Should have dropped the progress notification
- is(PopupNotifications.panel.childNodes.length, 1, "Should be the right number of notifications");
- is(PopupNotifications.panel.childNodes[0].id, "addon-install-confirmation-notification",
- "Should only be showing one install confirmation");
-
- // Should still have the right add-on in the confirmation notification
- is(container.childNodes.length, 1, "Should be one item listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
-
- cancelInstallDialog();
-
- ok(PopupNotifications.isPanelOpen, "Panel should still be open");
- is(PopupNotifications.panel.childNodes.length, 1, "Should be the right number of notifications");
- is(PopupNotifications.panel.childNodes[0].id, "addon-install-confirmation-notification",
- "Should still have an install confirmation open");
-
- // Should have the next add-on's confirmation dialog
- is(container.childNodes.length, 1, "Should be one item listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "Theme Test", "Should have the right add-on");
-
- Services.perms.remove(makeURI("http://example.com"), "install");
- let closePromise = waitForNotificationClose();
- cancelInstallDialog();
- yield closePromise;
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-},
-
-function test_someUnverified() {
- return Task.spawn(function* () {
- // This test is only relevant if using the new doorhanger UI and allowing
- // unsigned add-ons
- if (!Preferences.get("xpinstall.customConfirmationUI", false) ||
- Preferences.get("xpinstall.signatures.required", true) ||
- REQUIRE_SIGNING) {
- return;
- }
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Extension XPI": "restartless-unsigned.xpi",
- "Theme XPI": "theme.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let notification = document.getElementById("addon-install-confirmation-notification");
- let message = notification.getAttribute("label");
- is(message, "Caution: This site would like to install 2 add-ons in " + gApp +
- ", some of which are unverified. Proceed at your own risk.",
- "Should see the right message");
-
- let container = document.getElementById("addon-install-confirmation-content");
- is(container.childNodes.length, 2, "Should be two items listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
- is(container.childNodes[0].lastChild.getAttribute("class"),
- "addon-install-confirmation-unsigned", "Should have the unverified marker");
- is(container.childNodes[1].firstChild.getAttribute("value"), "Theme Test", "Should have the right add-on");
- is(container.childNodes[1].childNodes.length, 1, "Shouldn't have the unverified marker");
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- yield notificationPromise;
-
- let [addon, theme] = yield new Promise(resolve => {
- AddonManager.getAddonsByIDs(["restartless-xpi@tests.mozilla.org",
- "theme-xpi@tests.mozilla.org"],
- function(addons) {
- resolve(addons);
- });
- });
- addon.uninstall();
- // Installing a new theme tries to switch to it, switch back to the
- // default theme.
- theme.userDisabled = true;
- theme.uninstall();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_allUnverified() {
- return Task.spawn(function* () {
- // This test is only relevant if using the new doorhanger UI and allowing
- // unsigned add-ons
- if (!Preferences.get("xpinstall.customConfirmationUI", false) ||
- Preferences.get("xpinstall.signatures.required", true) ||
- REQUIRE_SIGNING) {
- return;
- }
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Extension XPI": "restartless-unsigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let notification = document.getElementById("addon-install-confirmation-notification");
- let message = notification.getAttribute("label");
- is(message, "Caution: This site would like to install an unverified add-on in " + gApp + ". Proceed at your own risk.");
-
- let container = document.getElementById("addon-install-confirmation-content");
- is(container.childNodes.length, 1, "Should be one item listed");
- is(container.childNodes[0].firstChild.getAttribute("value"), "XPI Test", "Should have the right add-on");
- is(container.childNodes[0].childNodes.length, 1, "Shouldn't have the unverified marker");
-
- let notificationPromise = waitForNotification("addon-install-complete");
- acceptInstallDialog();
- yield notificationPromise;
-
- let addon = yield new Promise(resolve => {
- AddonManager.getAddonByID("restartless-xpi@tests.mozilla.org", function(result) {
- resolve(result);
- });
- });
- addon.uninstall();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_url() {
- return Task.spawn(function* () {
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI(TESTROOT + "amosigned.xpi");
- yield progressPromise;
- yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "XPI Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
-
- yield removeTab();
- });
-},
-
-function test_localFile() {
- return Task.spawn(function* () {
- let cr = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Components.interfaces.nsIChromeRegistry);
- let path;
- try {
- path = cr.convertChromeURL(makeURI(CHROMEROOT + "corrupt.xpi")).spec;
- } catch (ex) {
- path = CHROMEROOT + "corrupt.xpi";
- }
-
- let failPromise = new Promise(resolve => {
- Services.obs.addObserver(function observer() {
- Services.obs.removeObserver(observer, "addon-install-failed");
- resolve();
- }, "addon-install-failed", false);
- });
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI(path);
- yield failPromise;
-
- // Wait for the browser code to add the failure notification
- yield waitForSingleNotification();
-
- let notification = PopupNotifications.panel.childNodes[0];
- is(notification.id, "addon-install-failed-notification", "Should have seen the install fail");
- is(notification.getAttribute("label"),
- "This add-on could not be installed because it appears to be corrupt.",
- "Should have seen the right message");
-
- yield removeTab();
- });
-},
-
-function test_tabClose() {
- return Task.spawn(function* () {
- if (!Preferences.get("xpinstall.customConfirmationUI", false)) {
- runNextTest();
- return;
- }
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI(TESTROOT + "amosigned.xpi");
- yield progressPromise;
- yield dialogPromise;
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
-
- let closePromise = waitForNotificationClose();
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield closePromise;
-
- installs = yield getInstalls();
- is(installs.length, 0, "Should be no pending install since the tab is closed");
- });
-},
-
-// Add-ons should be cancelled and the install notification destroyed when
-// navigating to a new origin
-function test_tabNavigate() {
- return Task.spawn(function* () {
- if (!Preferences.get("xpinstall.customConfirmationUI", false)) {
- return;
- }
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Extension XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let closePromise = waitForNotificationClose();
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI("about:blank");
- yield closePromise;
-
- let installs = yield getInstalls();
- is(installs.length, 0, "Should be no pending install");
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield loadPromise;
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-},
-
-function test_urlBar() {
- return Task.spawn(function* () {
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gURLBar.value = TESTROOT + "amosigned.xpi";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- yield progressPromise;
- let installDialog = yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog(installDialog);
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "XPI Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
-
- yield removeTab();
- });
-},
-
-function test_wrongHost() {
- return Task.spawn(function* () {
- let requestedUrl = TESTROOT2 + "enabled.html";
- gBrowser.selectedTab = gBrowser.addTab();
-
- let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, requestedUrl);
- gBrowser.loadURI(TESTROOT2 + "enabled.html");
- yield loadedPromise;
-
- let progressPromise = waitForProgressNotification();
- let notificationPromise = waitForNotification("addon-install-failed");
- gBrowser.loadURI(TESTROOT + "corrupt.xpi");
- yield progressPromise;
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.getAttribute("label"),
- "The add-on downloaded from this site could not be installed " +
- "because it appears to be corrupt.",
- "Should have seen the right message");
-
- yield removeTab();
- });
-},
-
-function test_reload() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Unsigned XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "XPI Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- function testFail() {
- ok(false, "Reloading should not have hidden the notification");
- }
- PopupNotifications.panel.addEventListener("popuphiding", testFail, false);
- let requestedUrl = TESTROOT2 + "enabled.html";
- let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, requestedUrl);
- gBrowser.loadURI(TESTROOT2 + "enabled.html");
- yield loadedPromise;
- PopupNotifications.panel.removeEventListener("popuphiding", testFail, false);
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending install");
- installs[0].cancel();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_theme() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "Theme XPI": "theme.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
- is(notification.getAttribute("label"),
- "Theme Test will be installed after you restart " + gApp + ".",
- "Should have seen the right message");
-
- let addon = yield new Promise(resolve => {
- AddonManager.getAddonByID("{972ce4c6-7e08-4474-a285-3208198ce6fd}", function(result) {
- resolve(result);
- });
- });
- ok(addon.userDisabled, "Should be switching away from the default theme.");
- // Undo the pending theme switch
- addon.userDisabled = false;
-
- addon = yield new Promise(resolve => {
- AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(result) {
- resolve(result);
- });
- });
- isnot(addon, null, "Test theme will have been installed");
- addon.uninstall();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_renotifyBlocked() {
- return Task.spawn(function* () {
- let notificationPromise = waitForNotification("addon-install-blocked");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- let panel = yield notificationPromise;
-
- let closePromise = waitForNotificationClose();
- // hide the panel (this simulates the user dismissing it)
- panel.hidePopup();
- yield closePromise;
-
- info("Timeouts after this probably mean bug 589954 regressed");
-
- yield new Promise(resolve => executeSoon(resolve));
-
- notificationPromise = waitForNotification("addon-install-blocked");
- gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
- yield notificationPromise;
-
- let installs = yield getInstalls();
- is(installs.length, 2, "Should be two pending installs");
-
- closePromise = waitForNotificationClose();
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield closePromise;
-
- installs = yield getInstalls();
- is(installs.length, 0, "Should have cancelled the installs");
- });
-},
-
-function test_renotifyInstalled() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let progressPromise = waitForProgressNotification();
- let dialogPromise = waitForInstallDialog();
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- // Wait for the complete notification
- let notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- let panel = yield notificationPromise;
-
- let closePromise = waitForNotificationClose();
- // hide the panel (this simulates the user dismissing it)
- panel.hidePopup();
- yield closePromise;
-
- // Install another
- yield new Promise(resolve => executeSoon(resolve));
-
- progressPromise = waitForProgressNotification();
- dialogPromise = waitForInstallDialog();
- gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
- yield progressPromise;
- yield dialogPromise;
-
- info("Timeouts after this probably mean bug 589954 regressed");
-
- // Wait for the complete notification
- notificationPromise = waitForNotification("addon-install-restart");
- acceptInstallDialog();
- yield notificationPromise;
-
- let installs = yield getInstalls();
- is(installs.length, 1, "Should be one pending installs");
- installs[0].cancel();
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield removeTab();
- });
-},
-
-function test_cancel() {
- return Task.spawn(function* () {
- let pm = Services.perms;
- pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
-
- let notificationPromise = waitForNotification(PROGRESS_NOTIFICATION);
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "slowinstall.sjs?file=amosigned.xpi"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, TESTROOT + "installtrigger.html?" + triggers);
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- // Close the notification
- let anchor = document.getElementById("addons-notification-icon");
- anchor.click();
- // Reopen the notification
- anchor.click();
-
- ok(PopupNotifications.isPanelOpen, "Notification should still be open");
- is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
- notification = panel.childNodes[0];
- is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
- let button = document.getElementById("addon-progress-cancel");
-
- // Cancel the download
- let install = notification.notification.options.installs[0];
- let cancelledPromise = new Promise(resolve => {
- install.addListener({
- onDownloadCancelled: function() {
- install.removeListener(this);
- resolve();
- }
- });
- });
- EventUtils.synthesizeMouseAtCenter(button, {});
- yield cancelledPromise;
-
- yield new Promise(resolve => executeSoon(resolve));
-
- ok(!PopupNotifications.isPanelOpen, "Notification should be closed");
-
- let installs = yield getInstalls();
- is(installs.length, 0, "Should be no pending install");
-
- Services.perms.remove(makeURI("http://example.com/"), "install");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-},
-
-function test_failedSecurity() {
- return Task.spawn(function* () {
- Services.prefs.setBoolPref(PREF_INSTALL_REQUIREBUILTINCERTS, false);
- setupRedirect({
- "Location": TESTROOT + "amosigned.xpi"
- });
-
- let notificationPromise = waitForNotification("addon-install-blocked");
- let triggers = encodeURIComponent(JSON.stringify({
- "XPI": "redirect.sjs?mode=redirect"
- }));
- BrowserTestUtils.openNewForegroundTab(gBrowser, SECUREROOT + "installtrigger.html?" + triggers);
- let panel = yield notificationPromise;
-
- let notification = panel.childNodes[0];
- // Click on Allow
- EventUtils.synthesizeMouse(notification.button, 20, 10, {});
-
- // Notification should have changed to progress notification
- ok(PopupNotifications.isPanelOpen, "Notification should still be open");
- is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
- notification = panel.childNodes[0];
- is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
-
- // Wait for it to fail
- yield new Promise(resolve => {
- Services.obs.addObserver(function observer() {
- Services.obs.removeObserver(observer, "addon-install-failed");
- resolve();
- }, "addon-install-failed", false);
- });
-
- // Allow the browser code to add the failure notification and then wait
- // for the progress notification to dismiss itself
- yield waitForSingleNotification();
- is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
- notification = panel.childNodes[0];
- is(notification.id, "addon-install-failed-notification", "Should have seen the install fail");
-
- Services.prefs.setBoolPref(PREF_INSTALL_REQUIREBUILTINCERTS, true);
- yield removeTab();
- });
-}
-];
-
-var gTestStart = null;
-
-var XPInstallObserver = {
- observe: function (aSubject, aTopic, aData) {
- var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo);
- info("Observed " + aTopic + " for " + installInfo.installs.length + " installs");
- installInfo.installs.forEach(function(aInstall) {
- info("Install of " + aInstall.sourceURI.spec + " was in state " + aInstall.state);
- });
- }
-};
-
-add_task(function* () {
- requestLongerTimeout(4);
-
- Services.prefs.setBoolPref("extensions.logging.enabled", true);
- Services.prefs.setBoolPref("extensions.strictCompatibility", true);
- Services.prefs.setBoolPref("extensions.install.requireSecureOrigin", false);
- Services.prefs.setIntPref("security.dialog_enable_delay", 0);
-
- Services.obs.addObserver(XPInstallObserver, "addon-install-started", false);
- Services.obs.addObserver(XPInstallObserver, "addon-install-blocked", false);
- Services.obs.addObserver(XPInstallObserver, "addon-install-failed", false);
- Services.obs.addObserver(XPInstallObserver, "addon-install-complete", false);
-
- registerCleanupFunction(function() {
- // Make sure no more test parts run in case we were timed out
- TESTS = [];
-
- AddonManager.getAllInstalls(function(aInstalls) {
- aInstalls.forEach(function(aInstall) {
- aInstall.cancel();
- });
- });
-
- Services.prefs.clearUserPref("extensions.logging.enabled");
- Services.prefs.clearUserPref("extensions.strictCompatibility");
- Services.prefs.clearUserPref("extensions.install.requireSecureOrigin");
- Services.prefs.clearUserPref("security.dialog_enable_delay");
-
- Services.obs.removeObserver(XPInstallObserver, "addon-install-started");
- Services.obs.removeObserver(XPInstallObserver, "addon-install-blocked");
- Services.obs.removeObserver(XPInstallObserver, "addon-install-failed");
- Services.obs.removeObserver(XPInstallObserver, "addon-install-complete");
- });
-
- for (let i = 0; i < TESTS.length; ++i) {
- if (gTestStart)
- info("Test part took " + (Date.now() - gTestStart) + "ms");
-
- ok(!PopupNotifications.isPanelOpen, "Notification should be closed");
-
- let installs = yield new Promise(resolve => {
- AddonManager.getAllInstalls(function(aInstalls) {
- resolve(aInstalls);
- });
- });
-
- is(installs.length, 0, "Should be no active installs");
- info("Running " + TESTS[i].name);
- gTestStart = Date.now();
- yield TESTS[i]();
- }
-});
diff --git a/browser/base/content/test/general/browser_bug555224.js b/browser/base/content/test/general/browser_bug555224.js
deleted file mode 100644
index d27bf0040..000000000
--- a/browser/base/content/test/general/browser_bug555224.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/* 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/. */
-const TEST_PAGE = "/browser/browser/base/content/test/general/dummy_page.html";
-var gTestTab, gBgTab, gTestZoom;
-
-function testBackgroundLoad() {
- Task.spawn(function* () {
- is(ZoomManager.zoom, gTestZoom, "opening a background tab should not change foreground zoom");
-
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gBgTab);
-
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTestTab);
- finish();
- });
-}
-
-function testInitialZoom() {
- Task.spawn(function* () {
- is(ZoomManager.zoom, 1, "initial zoom level should be 1");
- FullZoom.enlarge();
-
- gTestZoom = ZoomManager.zoom;
- isnot(gTestZoom, 1, "zoom level should have changed");
-
- gBgTab = gBrowser.addTab();
- yield FullZoomHelper.load(gBgTab, "http://mochi.test:8888" + TEST_PAGE);
- }).then(testBackgroundLoad, FullZoomHelper.failAndContinue(finish));
-}
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- gTestTab = gBrowser.addTab();
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTestTab);
- yield FullZoomHelper.load(gTestTab, "http://example.org" + TEST_PAGE);
- }).then(testInitialZoom, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug555767.js b/browser/base/content/test/general/browser_bug555767.js
deleted file mode 100644
index bc774f7dc..000000000
--- a/browser/base/content/test/general/browser_bug555767.js
+++ /dev/null
@@ -1,54 +0,0 @@
- /* 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/. */
-
- add_task(function* () {
- let testURL = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
- let tabSelected = false;
-
- // Open the base tab
- let baseTab = gBrowser.addTab(testURL);
-
- // Wait for the tab to be fully loaded so matching happens correctly
- yield promiseTabLoaded(baseTab);
- if (baseTab.linkedBrowser.currentURI.spec == "about:blank")
- return;
- baseTab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- let testTab = gBrowser.addTab();
-
- // Select the testTab
- gBrowser.selectedTab = testTab;
-
- // Set the urlbar to include the moz-action
- gURLBar.value = "moz-action:switchtab," + JSON.stringify({url: testURL});
- // Focus the urlbar so we can press enter
- gURLBar.focus();
-
- // Functions for TabClose and TabSelect
- function onTabClose(aEvent) {
- gBrowser.tabContainer.removeEventListener("TabClose", onTabClose, false);
- // Make sure we get the TabClose event for testTab
- is(aEvent.originalTarget, testTab, "Got the TabClose event for the right tab");
- // Confirm that we did select the tab
- ok(tabSelected, "Confirming that the tab was selected");
- gBrowser.removeTab(baseTab);
- finish();
- }
- function onTabSelect(aEvent) {
- gBrowser.tabContainer.removeEventListener("TabSelect", onTabSelect, false);
- // Make sure we got the TabSelect event for baseTab
- is(aEvent.originalTarget, baseTab, "Got the TabSelect event for the right tab");
- // Confirm that the selected tab is in fact base tab
- is(gBrowser.selectedTab, baseTab, "We've switched to the correct tab");
- tabSelected = true;
- }
-
- // Add the TabClose, TabSelect event listeners before we press enter
- gBrowser.tabContainer.addEventListener("TabClose", onTabClose, false);
- gBrowser.tabContainer.addEventListener("TabSelect", onTabSelect, false);
-
- // Press enter!
- EventUtils.synthesizeKey("VK_RETURN", {});
- });
-
diff --git a/browser/base/content/test/general/browser_bug559991.js b/browser/base/content/test/general/browser_bug559991.js
deleted file mode 100644
index b1516a8b4..000000000
--- a/browser/base/content/test/general/browser_bug559991.js
+++ /dev/null
@@ -1,42 +0,0 @@
-var tab;
-
-function test() {
-
- // ----------
- // Test setup
-
- waitForExplicitFinish();
-
- gPrefService.setBoolPref("browser.zoom.updateBackgroundTabs", true);
- gPrefService.setBoolPref("browser.zoom.siteSpecific", true);
-
- let uri = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-
- Task.spawn(function* () {
- tab = gBrowser.addTab();
- yield FullZoomHelper.load(tab, uri);
-
- // -------------------------------------------------------------------
- // Test - Trigger a tab switch that should update the zoom level
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab);
- ok(true, "applyPrefToSetting was called");
- }).then(endTest, FullZoomHelper.failAndContinue(endTest));
-}
-
-// -------------
-// Test clean-up
-function endTest() {
- Task.spawn(function* () {
- yield FullZoomHelper.removeTabAndWaitForLocationChange(tab);
-
- tab = null;
-
- if (gPrefService.prefHasUserValue("browser.zoom.updateBackgroundTabs"))
- gPrefService.clearUserPref("browser.zoom.updateBackgroundTabs");
-
- if (gPrefService.prefHasUserValue("browser.zoom.siteSpecific"))
- gPrefService.clearUserPref("browser.zoom.siteSpecific");
-
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_bug561636.js b/browser/base/content/test/general/browser_bug561636.js
deleted file mode 100644
index 69bc475c3..000000000
--- a/browser/base/content/test/general/browser_bug561636.js
+++ /dev/null
@@ -1,370 +0,0 @@
-var gInvalidFormPopup = document.getElementById('invalid-form-popup');
-ok(gInvalidFormPopup,
- "The browser should have a popup to show when a form is invalid");
-
-function checkPopupShow()
-{
- ok(gInvalidFormPopup.state == 'showing' || gInvalidFormPopup.state == 'open',
- "[Test " + testId + "] The invalid form popup should be shown");
-}
-
-function checkPopupHide()
-{
- ok(gInvalidFormPopup.state != 'showing' && gInvalidFormPopup.state != 'open',
- "[Test " + testId + "] The invalid form popup should not be shown");
-}
-
-var gObserver = {
- QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]),
-
- notifyInvalidSubmit : function (aFormElement, aInvalidElements)
- {
- }
-};
-
-var testId = 0;
-
-function incrementTest()
-{
- testId++;
- info("Starting next part of test");
-}
-
-function getDocHeader()
-{
- return "<html><head><meta charset='utf-8'></head><body>" + getEmptyFrame();
-}
-
-function getDocFooter()
-{
- return "</body></html>";
-}
-
-function getEmptyFrame()
-{
- return "<iframe style='width:100px; height:30px; margin:3px; border:1px solid lightgray;' " +
- "name='t' srcdoc=\"<html><head><meta charset='utf-8'></head><body>form target</body></html>\"></iframe>";
-}
-
-function* openNewTab(uri, background)
-{
- let tab = gBrowser.addTab();
- let browser = gBrowser.getBrowserForTab(tab);
- if (!background) {
- gBrowser.selectedTab = tab;
- }
- yield promiseTabLoadEvent(tab, "data:text/html," + escape(uri));
- return browser;
-}
-
-function* clickChildElement(browser)
-{
- yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementById('s').click();
- });
-}
-
-function* blurChildElement(browser)
-{
- yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementById('i').blur();
- });
-}
-
-function* checkChildFocus(browser, message)
-{
- yield ContentTask.spawn(browser, [message, testId], function* (args) {
- let [msg, id] = args;
- var focused = content.document.activeElement == content.document.getElementById('i');
-
- var validMsg = true;
- if (msg) {
- validMsg = (msg == content.document.getElementById('i').validationMessage);
- }
-
- Assert.equal(focused, true, "Test " + id + " First invalid element should be focused");
- Assert.equal(validMsg, true, "Test " + id + " The panel should show the message from validationMessage");
- });
-}
-
-/**
- * In this test, we check that no popup appears if the form is valid.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- yield clickChildElement(browser);
-
- yield new Promise((resolve, reject) => {
- // XXXndeakin This isn't really going to work when the content is another process
- executeSoon(function() {
- checkPopupHide();
- resolve();
- });
- });
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that, when an invalid form is submitted,
- * the invalid element is focused and a popup appears.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input required id='i'><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that, when an invalid form is submitted,
- * the first invalid element is focused and a popup appears.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input><input id='i' required><input required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that, we hide the popup by interacting with the
- * invalid element if the element becomes valid.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
- EventUtils.synthesizeKey("a", {});
- yield popupHiddenPromise;
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that, we don't hide the popup by interacting with the
- * invalid element if the element is still invalid.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input type='email' id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- yield new Promise((resolve, reject) => {
- EventUtils.synthesizeKey("a", {});
- executeSoon(function() {
- checkPopupShow();
- resolve();
- })
- });
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that we can hide the popup by blurring the invalid
- * element.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
- yield blurChildElement(browser);
- yield popupHiddenPromise;
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that we can hide the popup by pressing TAB.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_TAB", {});
- yield popupHiddenPromise;
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that the popup will hide if we move to another tab.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser1 = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser1);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser1, gInvalidFormPopup.firstChild.textContent);
-
- let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
-
- let browser2 = yield openNewTab("data:text/html,<html></html>");
- yield popupHiddenPromise;
-
- gBrowser.removeTab(gBrowser.getTabForBrowser(browser1));
- gBrowser.removeTab(gBrowser.getTabForBrowser(browser2));
-});
-
-/**
- * In this test, we check that nothing happen if the invalid form is
- * submitted in a background tab.
- */
-add_task(function* ()
-{
- // Observers don't propagate currently across processes. We may add support for this in the
- // future via the addon compat layer.
- if (gMultiProcessBrowser) {
- return;
- }
-
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri, true);
- isnot(gBrowser.selectedBrowser, browser, "This tab should have been loaded in background");
-
- let notifierPromise = new Promise((resolve, reject) => {
- gObserver.notifyInvalidSubmit = function() {
- executeSoon(function() {
- checkPopupHide();
-
- // Clean-up
- Services.obs.removeObserver(gObserver, "invalidformsubmit");
- gObserver.notifyInvalidSubmit = function () {};
- resolve();
- });
- };
-
- Services.obs.addObserver(gObserver, "invalidformsubmit", false);
-
- executeSoon(function () {
- browser.contentDocument.getElementById('s').click();
- });
- });
-
- yield notifierPromise;
-
- gBrowser.removeTab(gBrowser.getTabForBrowser(browser));
-});
-
-/**
- * In this test, we check that the author defined error message is shown.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input x-moz-errormessage='foo' required id='i'><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- is(gInvalidFormPopup.firstChild.textContent, "foo",
- "The panel should show the author defined error message");
-
- gBrowser.removeCurrentTab();
-});
-
-/**
- * In this test, we check that the message is correctly updated when it changes.
- */
-add_task(function* ()
-{
- incrementTest();
- let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input type='email' required id='i'><input id='s' type='submit'></form>" + getDocFooter();
- let browser = yield openNewTab(uri);
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
- yield clickChildElement(browser);
- yield popupShownPromise;
-
- checkPopupShow();
- yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
-
- let inputPromise = promiseWaitForEvent(gBrowser.contentDocument.getElementById('i'), "input");
- EventUtils.synthesizeKey('f', {});
- yield inputPromise;
-
- // Now, the element suffers from another error, the message should have
- // been updated.
- yield new Promise((resolve, reject) => {
- // XXXndeakin This isn't really going to work when the content is another process
- executeSoon(function() {
- checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
- resolve();
- });
- });
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug563588.js b/browser/base/content/test/general/browser_bug563588.js
deleted file mode 100644
index a1774fb7e..000000000
--- a/browser/base/content/test/general/browser_bug563588.js
+++ /dev/null
@@ -1,30 +0,0 @@
-function press(key, expectedPos) {
- var originalSelectedTab = gBrowser.selectedTab;
- EventUtils.synthesizeKey("VK_" + key.toUpperCase(), { accelKey: true });
- is(gBrowser.selectedTab, originalSelectedTab,
- "accel+" + key + " doesn't change which tab is selected");
- is(gBrowser.tabContainer.selectedIndex, expectedPos,
- "accel+" + key + " moves the tab to the expected position");
- is(document.activeElement, gBrowser.selectedTab,
- "accel+" + key + " leaves the selected tab focused");
-}
-
-function test() {
- gBrowser.addTab();
- gBrowser.addTab();
- is(gBrowser.tabs.length, 3, "got three tabs");
- is(gBrowser.tabs[0], gBrowser.selectedTab, "first tab is selected");
-
- gBrowser.selectedTab.focus();
- is(document.activeElement, gBrowser.selectedTab, "selected tab is focused");
-
- press("right", 1);
- press("down", 2);
- press("left", 1);
- press("up", 0);
- press("end", 2);
- press("home", 0);
-
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
-}
diff --git a/browser/base/content/test/general/browser_bug565575.js b/browser/base/content/test/general/browser_bug565575.js
deleted file mode 100644
index 3555a2e7f..000000000
--- a/browser/base/content/test/general/browser_bug565575.js
+++ /dev/null
@@ -1,14 +0,0 @@
-add_task(function* () {
- gBrowser.selectedBrowser.focus();
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => BrowserOpenTab(), false);
- ok(gURLBar.focused, "location bar is focused for a new tab");
-
- yield BrowserTestUtils.switchTab(gBrowser, gBrowser.tabs[0]);
- ok(!gURLBar.focused, "location bar isn't focused for the previously selected tab");
-
- yield BrowserTestUtils.switchTab(gBrowser, gBrowser.tabs[1]);
- ok(gURLBar.focused, "location bar is re-focused when selecting the new tab");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug567306.js b/browser/base/content/test/general/browser_bug567306.js
deleted file mode 100644
index 742ff6726..000000000
--- a/browser/base/content/test/general/browser_bug567306.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var {Ci: interfaces, Cc: classes} = Components;
-
-var Clipboard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
-var HasFindClipboard = Clipboard.supportsFindClipboard();
-
-add_task(function* () {
- let newwindow = yield BrowserTestUtils.openNewBrowserWindow();
-
- let selectedBrowser = newwindow.gBrowser.selectedBrowser;
- yield new Promise((resolve, reject) => {
- selectedBrowser.addEventListener("pageshow", function pageshowListener() {
- if (selectedBrowser.currentURI.spec == "about:blank")
- return;
-
- selectedBrowser.removeEventListener("pageshow", pageshowListener, true);
- ok(true, "pageshow listener called: " + newwindow.content.location);
- resolve();
- }, true);
- selectedBrowser.loadURI("data:text/html,<h1 id='h1'>Select Me</h1>");
- });
-
- yield SimpleTest.promiseFocus(newwindow);
-
- ok(!newwindow.gFindBarInitialized, "find bar is not yet initialized");
- let findBar = newwindow.gFindBar;
-
- yield ContentTask.spawn(selectedBrowser, { }, function* () {
- let elt = content.document.getElementById("h1");
- let selection = content.getSelection();
- let range = content.document.createRange();
- range.setStart(elt, 0);
- range.setEnd(elt, 1);
- selection.removeAllRanges();
- selection.addRange(range);
- });
-
- yield findBar.onFindCommand();
-
- // When the OS supports the Find Clipboard (OSX), the find field value is
- // persisted across Fx sessions, thus not useful to test.
- if (!HasFindClipboard)
- is(findBar._findField.value, "Select Me", "Findbar is initialized with selection");
- findBar.close();
- yield promiseWindowClosed(newwindow);
-});
-
diff --git a/browser/base/content/test/general/browser_bug575561.js b/browser/base/content/test/general/browser_bug575561.js
deleted file mode 100644
index b6d17a447..000000000
--- a/browser/base/content/test/general/browser_bug575561.js
+++ /dev/null
@@ -1,97 +0,0 @@
-requestLongerTimeout(2);
-
-const TEST_URL = "http://example.com/browser/browser/base/content/test/general/app_bug575561.html";
-
-add_task(function*() {
- SimpleTest.requestCompleteLog();
-
- // Pinned: Link to the same domain should not open a new tab
- // Tests link to http://example.com/browser/browser/base/content/test/general/dummy_page.html
- yield testLink(0, true, false);
- // Pinned: Link to a different subdomain should open a new tab
- // Tests link to http://test1.example.com/browser/browser/base/content/test/general/dummy_page.html
- yield testLink(1, true, true);
-
- // Pinned: Link to a different domain should open a new tab
- // Tests link to http://example.org/browser/browser/base/content/test/general/dummy_page.html
- yield testLink(2, true, true);
-
- // Not Pinned: Link to a different domain should not open a new tab
- // Tests link to http://example.org/browser/browser/base/content/test/general/dummy_page.html
- yield testLink(2, false, false);
-
- // Pinned: Targetted link should open a new tab
- // Tests link to http://example.org/browser/browser/base/content/test/general/dummy_page.html with target="foo"
- yield testLink(3, true, true);
-
- // Pinned: Link in a subframe should not open a new tab
- // Tests link to http://example.org/browser/browser/base/content/test/general/dummy_page.html in subframe
- yield testLink(0, true, false, true);
-
- // Pinned: Link to the same domain (with www prefix) should not open a new tab
- // Tests link to http://www.example.com/browser/browser/base/content/test/general/dummy_page.html
- yield testLink(4, true, false);
-
- // Pinned: Link to a data: URI should not open a new tab
- // Tests link to data:text/html,<!DOCTYPE html><html><body>Another Page</body></html>
- yield testLink(5, true, false);
-
- // Pinned: Link to an about: URI should not open a new tab
- // Tests link to about:logo
- yield testLink(function(doc) {
- let link = doc.createElement("a");
- link.textContent = "Link to Mozilla";
- link.href = "about:logo";
- doc.body.appendChild(link);
- return link;
- }, true, false, false, "about:robots");
-});
-
-var waitForPageLoad = Task.async(function*(browser, linkLocation) {
- yield waitForDocLoadComplete();
-
- is(browser.contentDocument.location.href, linkLocation, "Link should not open in a new tab");
-});
-
-var waitForTabOpen = Task.async(function*() {
- let event = yield promiseWaitForEvent(gBrowser.tabContainer, "TabOpen", true);
- ok(true, "Link should open a new tab");
-
- yield waitForDocLoadComplete(event.target.linkedBrowser);
- yield Promise.resolve();
-
- gBrowser.removeCurrentTab();
-});
-
-var testLink = Task.async(function*(aLinkIndexOrFunction, pinTab, expectNewTab, testSubFrame, aURL = TEST_URL) {
- let appTab = gBrowser.addTab(aURL, {skipAnimation: true});
- if (pinTab)
- gBrowser.pinTab(appTab);
- gBrowser.selectedTab = appTab;
-
- yield waitForDocLoadComplete();
-
- let browser = appTab.linkedBrowser;
- if (testSubFrame)
- browser = browser.contentDocument.querySelector("iframe");
-
- let link;
- if (typeof aLinkIndexOrFunction == "function") {
- link = aLinkIndexOrFunction(browser.contentDocument);
- } else {
- link = browser.contentDocument.querySelectorAll("a")[aLinkIndexOrFunction];
- }
-
- let promise;
- if (expectNewTab)
- promise = waitForTabOpen();
- else
- promise = waitForPageLoad(browser, link.href);
-
- info("Clicking " + link.textContent);
- link.click();
-
- yield promise;
-
- gBrowser.removeTab(appTab);
-});
diff --git a/browser/base/content/test/general/browser_bug575830.js b/browser/base/content/test/general/browser_bug575830.js
deleted file mode 100644
index 5393c08d7..000000000
--- a/browser/base/content/test/general/browser_bug575830.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* 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/. */
-"use strict";
-
-function test() {
- let tab1, tab2;
- const TEST_IMAGE = "http://example.org/browser/browser/base/content/test/general/moz.png";
-
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- tab1 = gBrowser.addTab();
- tab2 = gBrowser.addTab();
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab1);
- yield FullZoomHelper.load(tab1, TEST_IMAGE);
-
- is(ZoomManager.zoom, 1, "initial zoom level for first should be 1");
-
- FullZoom.enlarge();
- let zoom = ZoomManager.zoom;
- isnot(zoom, 1, "zoom level should have changed");
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab2);
- is(ZoomManager.zoom, 1, "initial zoom level for second tab should be 1");
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(tab1);
- is(ZoomManager.zoom, zoom, "zoom level for first tab should not have changed");
-
- yield FullZoomHelper.removeTabAndWaitForLocationChange(tab1);
- yield FullZoomHelper.removeTabAndWaitForLocationChange(tab2);
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug577121.js b/browser/base/content/test/general/browser_bug577121.js
deleted file mode 100644
index 5ebfdc115..000000000
--- a/browser/base/content/test/general/browser_bug577121.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* 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/. */
-
-function test() {
- Services.prefs.setBoolPref("browser.tabs.animate", false);
- registerCleanupFunction(function() {
- Services.prefs.clearUserPref("browser.tabs.animate");
- });
-
- // Open 2 other tabs, and pin the second one. Like that, the initial tab
- // should get closed.
- let testTab1 = gBrowser.addTab();
- let testTab2 = gBrowser.addTab();
- gBrowser.pinTab(testTab2);
-
- // Now execute "Close other Tabs" on the first manually opened tab (tab1).
- // -> tab2 ist pinned, tab1 should remain open and the initial tab should
- // get closed.
- gBrowser.removeAllTabsBut(testTab1);
-
- is(gBrowser.tabs.length, 2, "there are two remaining tabs open");
- is(gBrowser.tabs[0], testTab2, "pinned tab2 stayed open");
- is(gBrowser.tabs[1], testTab1, "tab1 stayed open");
-
- // Cleanup. Close only one tab because we need an opened tab at the end of
- // the test.
- gBrowser.removeTab(testTab2);
-}
diff --git a/browser/base/content/test/general/browser_bug578534.js b/browser/base/content/test/general/browser_bug578534.js
deleted file mode 100644
index 0d61cca76..000000000
--- a/browser/base/content/test/general/browser_bug578534.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* 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/. */
-
-add_task(function* test() {
- let uriString = "http://example.com/";
- let cookieBehavior = "network.cookie.cookieBehavior";
- let uriObj = Services.io.newURI(uriString, null, null)
- let cp = Components.classes["@mozilla.org/cookie/permission;1"]
- .getService(Components.interfaces.nsICookiePermission);
-
- yield SpecialPowers.pushPrefEnv({ set: [[ cookieBehavior, 2 ]] });
- cp.setAccess(uriObj, cp.ACCESS_ALLOW);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: uriString }, function* (browser) {
- yield ContentTask.spawn(browser, null, function() {
- is(content.navigator.cookieEnabled, true,
- "navigator.cookieEnabled should be true");
- });
- });
-
- cp.setAccess(uriObj, cp.ACCESS_DEFAULT);
-});
diff --git a/browser/base/content/test/general/browser_bug579872.js b/browser/base/content/test/general/browser_bug579872.js
deleted file mode 100644
index bc10ca0c8..000000000
--- a/browser/base/content/test/general/browser_bug579872.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* 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/. */
-
-function test() {
- let newTab = gBrowser.addTab();
- waitForExplicitFinish();
- BrowserTestUtils.browserLoaded(newTab.linkedBrowser).then(mainPart);
-
- function mainPart() {
- gBrowser.pinTab(newTab);
- gBrowser.selectedTab = newTab;
-
- openUILinkIn("javascript:var x=0;", "current");
- is(gBrowser.tabs.length, 2, "Should open in current tab");
-
- openUILinkIn("http://example.com/1", "current");
- is(gBrowser.tabs.length, 2, "Should open in current tab");
-
- openUILinkIn("http://example.org/", "current");
- is(gBrowser.tabs.length, 3, "Should open in new tab");
-
- gBrowser.removeTab(newTab);
- gBrowser.removeTab(gBrowser.tabs[1]); // example.org tab
- finish();
- }
- newTab.linkedBrowser.loadURI("http://example.com");
-}
diff --git a/browser/base/content/test/general/browser_bug580638.js b/browser/base/content/test/general/browser_bug580638.js
deleted file mode 100644
index 66defafe3..000000000
--- a/browser/base/content/test/general/browser_bug580638.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- function testState(aPinned) {
- function elemAttr(id, attr) {
- return document.getElementById(id).getAttribute(attr);
- }
-
- if (aPinned) {
- is(elemAttr("key_close", "disabled"), "true",
- "key_close should be disabled when a pinned-tab is selected");
- is(elemAttr("menu_close", "key"), "",
- "menu_close shouldn't have a key set when a pinned is selected");
- }
- else {
- is(elemAttr("key_close", "disabled"), "",
- "key_closed shouldn't have disabled state set when a non-pinned tab is selected");
- is(elemAttr("menu_close", "key"), "key_close",
- "menu_close should have key_close set as its key when a non-pinned tab is selected");
- }
- }
-
- let lastSelectedTab = gBrowser.selectedTab;
- ok(!lastSelectedTab.pinned, "We should have started with a regular tab selected");
-
- testState(false);
-
- let pinnedTab = gBrowser.addTab("about:blank");
- gBrowser.pinTab(pinnedTab);
-
- // Just pinning the tab shouldn't change the key state.
- testState(false);
-
- // Test updating key state after selecting a tab.
- gBrowser.selectedTab = pinnedTab;
- testState(true);
-
- gBrowser.selectedTab = lastSelectedTab;
- testState(false);
-
- gBrowser.selectedTab = pinnedTab;
- testState(true);
-
- // Test updating the key state after un/pinning the tab.
- gBrowser.unpinTab(pinnedTab);
- testState(false);
-
- gBrowser.pinTab(pinnedTab);
- testState(true);
-
- // Test updating the key state after removing the tab.
- gBrowser.removeTab(pinnedTab);
- testState(false);
-
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug580956.js b/browser/base/content/test/general/browser_bug580956.js
deleted file mode 100644
index b8e7bc20b..000000000
--- a/browser/base/content/test/general/browser_bug580956.js
+++ /dev/null
@@ -1,26 +0,0 @@
-function numClosedTabs() {
- return SessionStore.getClosedTabCount(window);
-}
-
-function isUndoCloseEnabled() {
- updateTabContextMenu();
- return !document.getElementById("context_undoCloseTab").disabled;
-}
-
-function test() {
- waitForExplicitFinish();
-
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", 0);
- gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
- is(numClosedTabs(), 0, "There should be 0 closed tabs.");
- ok(!isUndoCloseEnabled(), "Undo Close Tab should be disabled.");
-
- var tab = gBrowser.addTab("http://mochi.test:8888/");
- var browser = gBrowser.getBrowserForTab(tab);
- BrowserTestUtils.browserLoaded(browser).then(() => {
- BrowserTestUtils.removeTab(tab).then(() => {
- ok(isUndoCloseEnabled(), "Undo Close Tab should be enabled.");
- finish();
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_bug581242.js b/browser/base/content/test/general/browser_bug581242.js
deleted file mode 100644
index 668c0cd41..000000000
--- a/browser/base/content/test/general/browser_bug581242.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* 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/. */
-
-function test() {
- // Create a new tab and load about:addons
- let blanktab = gBrowser.addTab();
- gBrowser.selectedTab = blanktab;
- BrowserOpenAddonsMgr();
-
- is(blanktab, gBrowser.selectedTab, "Current tab should be blank tab");
- // Verify that about:addons loads
- waitForExplicitFinish();
- gBrowser.selectedBrowser.addEventListener("load", function() {
- gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
- let browser = blanktab.linkedBrowser;
- is(browser.currentURI.spec, "about:addons", "about:addons should load into blank tab.");
- gBrowser.removeTab(blanktab);
- finish();
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_bug581253.js b/browser/base/content/test/general/browser_bug581253.js
deleted file mode 100644
index 0c537c3d3..000000000
--- a/browser/base/content/test/general/browser_bug581253.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var testURL = "data:text/plain,nothing but plain text";
-var testTag = "581253_tag";
-var timerID = -1;
-
-function test() {
- registerCleanupFunction(function() {
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- if (timerID > 0) {
- clearTimeout(timerID);
- }
- });
- waitForExplicitFinish();
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- tab.linkedBrowser.addEventListener("load", (function(event) {
- tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- let uri = makeURI(testURL);
- let bmTxn =
- new PlacesCreateBookmarkTransaction(uri,
- PlacesUtils.unfiledBookmarksFolderId,
- -1, "", null, []);
- PlacesUtils.transactionManager.doTransaction(bmTxn);
-
- ok(PlacesUtils.bookmarks.isBookmarked(uri), "the test url is bookmarked");
- waitForStarChange(true, onStarred);
- }), true);
-
- content.location = testURL;
-}
-
-function waitForStarChange(aValue, aCallback) {
- let expectedStatus = aValue ? BookmarkingUI.STATUS_STARRED
- : BookmarkingUI.STATUS_UNSTARRED;
- if (BookmarkingUI.status == BookmarkingUI.STATUS_UPDATING ||
- BookmarkingUI.status != expectedStatus) {
- info("Waiting for star button change.");
- setTimeout(waitForStarChange, 50, aValue, aCallback);
- return;
- }
- aCallback();
-}
-
-function onStarred() {
- is(BookmarkingUI.status, BookmarkingUI.STATUS_STARRED,
- "star button indicates that the page is bookmarked");
-
- let uri = makeURI(testURL);
- let tagTxn = new PlacesTagURITransaction(uri, [testTag]);
- PlacesUtils.transactionManager.doTransaction(tagTxn);
-
- StarUI.panel.addEventListener("popupshown", onPanelShown, false);
- BookmarkingUI.star.click();
-}
-
-function onPanelShown(aEvent) {
- if (aEvent.target == StarUI.panel) {
- StarUI.panel.removeEventListener("popupshown", arguments.callee, false);
- let tagsField = document.getElementById("editBMPanel_tagsField");
- ok(tagsField.value == testTag, "tags field value was set");
- tagsField.focus();
-
- StarUI.panel.addEventListener("popuphidden", onPanelHidden, false);
- let removeButton = document.getElementById("editBookmarkPanelRemoveButton");
- removeButton.click();
- }
-}
-
-function onPanelHidden(aEvent) {
- if (aEvent.target == StarUI.panel) {
- StarUI.panel.removeEventListener("popuphidden", arguments.callee, false);
-
- executeSoon(function() {
- ok(!PlacesUtils.bookmarks.isBookmarked(makeURI(testURL)),
- "the bookmark for the test url has been removed");
- is(BookmarkingUI.status, BookmarkingUI.STATUS_UNSTARRED,
- "star button indicates that the bookmark has been removed");
- gBrowser.removeCurrentTab();
- PlacesTestUtils.clearHistory().then(finish);
- });
- }
-}
diff --git a/browser/base/content/test/general/browser_bug585558.js b/browser/base/content/test/general/browser_bug585558.js
deleted file mode 100644
index bae832b4d..000000000
--- a/browser/base/content/test/general/browser_bug585558.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var tabs = [];
-
-function addTab(aURL) {
- tabs.push(gBrowser.addTab(aURL, {skipAnimation: true}));
-}
-
-function testAttrib(elem, attrib, attribValue, msg) {
- is(elem.hasAttribute(attrib), attribValue, msg);
-}
-
-function test() {
- waitForExplicitFinish();
-
- is(gBrowser.tabs.length, 1, "one tab is open initially");
-
- // Add several new tabs in sequence, hiding some, to ensure that the
- // correct attributes get set
-
- addTab("http://mochi.test:8888/#0");
- addTab("http://mochi.test:8888/#1");
- addTab("http://mochi.test:8888/#2");
- addTab("http://mochi.test:8888/#3");
-
- gBrowser.selectedTab = gBrowser.tabs[0];
- testAttrib(gBrowser.tabs[0], "first-visible-tab", true,
- "First tab marked first-visible-tab!");
- testAttrib(gBrowser.tabs[4], "last-visible-tab", true,
- "Fifth tab marked last-visible-tab!");
- testAttrib(gBrowser.tabs[0], "selected", true, "First tab marked selected!");
- testAttrib(gBrowser.tabs[0], "afterselected-visible", false,
- "First tab not marked afterselected-visible!");
- testAttrib(gBrowser.tabs[1], "afterselected-visible", true,
- "Second tab marked afterselected-visible!");
- gBrowser.hideTab(gBrowser.tabs[1]);
- executeSoon(test_hideSecond);
-}
-
-function test_hideSecond() {
- testAttrib(gBrowser.tabs[2], "afterselected-visible", true,
- "Third tab marked afterselected-visible!");
- gBrowser.showTab(gBrowser.tabs[1])
- executeSoon(test_showSecond);
-}
-
-function test_showSecond() {
- testAttrib(gBrowser.tabs[1], "afterselected-visible", true,
- "Second tab marked afterselected-visible!");
- testAttrib(gBrowser.tabs[2], "afterselected-visible", false,
- "Third tab not marked as afterselected-visible!");
- gBrowser.selectedTab = gBrowser.tabs[1];
- gBrowser.hideTab(gBrowser.tabs[0]);
- executeSoon(test_hideFirst);
-}
-
-function test_hideFirst() {
- testAttrib(gBrowser.tabs[0], "first-visible-tab", false,
- "Hidden first tab not marked first-visible-tab!");
- testAttrib(gBrowser.tabs[1], "first-visible-tab", true,
- "Second tab marked first-visible-tab!");
- gBrowser.showTab(gBrowser.tabs[0]);
- executeSoon(test_showFirst);
-}
-
-function test_showFirst() {
- testAttrib(gBrowser.tabs[0], "first-visible-tab", true,
- "First tab marked first-visible-tab!");
- gBrowser.selectedTab = gBrowser.tabs[2];
- testAttrib(gBrowser.tabs[3], "afterselected-visible", true,
- "Fourth tab marked afterselected-visible!");
-
- gBrowser.moveTabTo(gBrowser.selectedTab, 1);
- executeSoon(test_movedLower);
-}
-
-function test_movedLower() {
- testAttrib(gBrowser.tabs[2], "afterselected-visible", true,
- "Third tab marked afterselected-visible!");
- test_hoverOne();
-}
-
-function test_hoverOne() {
- EventUtils.synthesizeMouseAtCenter(gBrowser.tabs[4], { type: "mousemove" });
- testAttrib(gBrowser.tabs[3], "beforehovered", true, "Fourth tab marked beforehovered");
- EventUtils.synthesizeMouseAtCenter(gBrowser.tabs[3], { type: "mousemove" });
- testAttrib(gBrowser.tabs[2], "beforehovered", true, "Third tab marked beforehovered!");
- testAttrib(gBrowser.tabs[2], "afterhovered", false, "Third tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[4], "afterhovered", true, "Fifth tab marked afterhovered!");
- testAttrib(gBrowser.tabs[4], "beforehovered", false, "Fifth tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[0], "beforehovered", false, "First tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[0], "afterhovered", false, "First tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[1], "beforehovered", false, "Second tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[1], "afterhovered", false, "Second tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[3], "beforehovered", false, "Fourth tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[3], "afterhovered", false, "Fourth tab not marked afterhovered!");
- gBrowser.removeTab(tabs.pop());
- executeSoon(test_hoverStatePersistence);
-}
-
-function test_hoverStatePersistence() {
- // Test that the afterhovered and beforehovered attributes are still there when
- // a tab is selected and then unselected again. See bug 856107.
-
- function assertState() {
- testAttrib(gBrowser.tabs[0], "beforehovered", true, "First tab still marked beforehovered!");
- testAttrib(gBrowser.tabs[0], "afterhovered", false, "First tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[2], "afterhovered", true, "Third tab still marked afterhovered!");
- testAttrib(gBrowser.tabs[2], "beforehovered", false, "Third tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[1], "beforehovered", false, "Second tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[1], "afterhovered", false, "Second tab not marked afterhovered!");
- testAttrib(gBrowser.tabs[3], "beforehovered", false, "Fourth tab not marked beforehovered!");
- testAttrib(gBrowser.tabs[3], "afterhovered", false, "Fourth tab not marked afterhovered!");
- }
-
- gBrowser.selectedTab = gBrowser.tabs[3];
- EventUtils.synthesizeMouseAtCenter(gBrowser.tabs[1], { type: "mousemove" });
- assertState();
- gBrowser.selectedTab = gBrowser.tabs[1];
- assertState();
- gBrowser.selectedTab = gBrowser.tabs[3];
- assertState();
- executeSoon(test_pinning);
-}
-
-function test_pinning() {
- gBrowser.selectedTab = gBrowser.tabs[3];
- testAttrib(gBrowser.tabs[3], "last-visible-tab", true,
- "Fourth tab marked last-visible-tab!");
- testAttrib(gBrowser.tabs[3], "selected", true, "Fourth tab marked selected!");
- testAttrib(gBrowser.tabs[3], "afterselected-visible", false,
- "Fourth tab not marked afterselected-visible!");
- // Causes gBrowser.tabs to change indices
- gBrowser.pinTab(gBrowser.tabs[3]);
- testAttrib(gBrowser.tabs[3], "last-visible-tab", true,
- "Fourth tab marked last-visible-tab!");
- testAttrib(gBrowser.tabs[1], "afterselected-visible", true,
- "Second tab marked afterselected-visible!");
- testAttrib(gBrowser.tabs[0], "first-visible-tab", true,
- "First tab marked first-visible-tab!");
- testAttrib(gBrowser.tabs[0], "selected", true, "First tab marked selected!");
- gBrowser.selectedTab = gBrowser.tabs[1];
- testAttrib(gBrowser.tabs[2], "afterselected-visible", true,
- "Third tab marked afterselected-visible!");
- test_cleanUp();
-}
-
-function test_cleanUp() {
- tabs.forEach(gBrowser.removeTab, gBrowser);
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug585785.js b/browser/base/content/test/general/browser_bug585785.js
deleted file mode 100644
index 4f9045231..000000000
--- a/browser/base/content/test/general/browser_bug585785.js
+++ /dev/null
@@ -1,35 +0,0 @@
-var tab;
-
-function test() {
- waitForExplicitFinish();
-
- tab = gBrowser.addTab();
- isnot(tab.getAttribute("fadein"), "true", "newly opened tab is yet to fade in");
-
- // Try to remove the tab right before the opening animation's first frame
- window.requestAnimationFrame(checkAnimationState);
-}
-
-function checkAnimationState() {
- is(tab.getAttribute("fadein"), "true", "tab opening animation initiated");
-
- info(window.getComputedStyle(tab).maxWidth);
- gBrowser.removeTab(tab, { animate: true });
- if (!tab.parentNode) {
- ok(true, "tab removed synchronously since the opening animation hasn't moved yet");
- finish();
- return;
- }
-
- info("tab didn't close immediately, so the tab opening animation must have started moving");
- info("waiting for the tab to close asynchronously");
- tab.addEventListener("transitionend", function (event) {
- if (event.propertyName == "max-width") {
- tab.removeEventListener("transitionend", arguments.callee, false);
- executeSoon(function () {
- ok(!tab.parentNode, "tab removed asynchronously");
- finish();
- });
- }
- }, false);
-}
diff --git a/browser/base/content/test/general/browser_bug585830.js b/browser/base/content/test/general/browser_bug585830.js
deleted file mode 100644
index 6d3adf198..000000000
--- a/browser/base/content/test/general/browser_bug585830.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-function test() {
- let tab1 = gBrowser.selectedTab;
- let tab2 = gBrowser.addTab("about:blank", {skipAnimation: true});
- gBrowser.addTab();
- gBrowser.selectedTab = tab2;
-
- gBrowser.removeCurrentTab({animate: true});
- gBrowser.tabContainer.advanceSelectedTab(-1, true);
- is(gBrowser.selectedTab, tab1, "First tab should be selected");
- gBrowser.removeTab(tab2);
-
- // test for "null has no properties" fix. See Bug 585830 Comment 13
- gBrowser.removeCurrentTab({animate: true});
- try {
- gBrowser.tabContainer.advanceSelectedTab(-1, false);
- } catch (err) {
- ok(false, "Shouldn't throw");
- }
-
- gBrowser.removeTab(tab1);
-}
diff --git a/browser/base/content/test/general/browser_bug590206.js b/browser/base/content/test/general/browser_bug590206.js
deleted file mode 100644
index f73d144e9..000000000
--- a/browser/base/content/test/general/browser_bug590206.js
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Test the identity mode UI for a variety of page types
- */
-
-"use strict";
-
-const DUMMY = "browser/browser/base/content/test/general/dummy_page.html";
-
-function loadNewTab(url) {
- return BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-}
-
-function getIdentityMode() {
- return document.getElementById("identity-box").className;
-}
-
-function getConnectionState() {
- gIdentityHandler.refreshIdentityPopup();
- return document.getElementById("identity-popup").getAttribute("connection");
-}
-
-// This test is slow on Linux debug e10s
-requestLongerTimeout(2);
-
-add_task(function* test_webpage() {
- let oldTab = gBrowser.selectedTab;
-
- let newTab = yield loadNewTab("http://example.com/" + DUMMY);
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_blank() {
- let oldTab = gBrowser.selectedTab;
-
- let newTab = yield loadNewTab("about:blank");
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_chrome() {
- let oldTab = gBrowser.selectedTab;
-
- let newTab = yield loadNewTab("chrome://mozapps/content/extensions/extensions.xul");
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_https() {
- let oldTab = gBrowser.selectedTab;
-
- let newTab = yield loadNewTab("https://example.com/" + DUMMY);
- is(getIdentityMode(), "verifiedDomain", "Identity should be verified");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getIdentityMode(), "verifiedDomain", "Identity should be verified");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_addons() {
- let oldTab = gBrowser.selectedTab;
-
- let newTab = yield loadNewTab("about:addons");
- is(getIdentityMode(), "chromeUI", "Identity should be chrome");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getIdentityMode(), "chromeUI", "Identity should be chrome");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_file() {
- let oldTab = gBrowser.selectedTab;
- let fileURI = getTestFilePath("");
-
- let newTab = yield loadNewTab(fileURI);
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_resource_uri() {
- let oldTab = gBrowser.selectedTab;
- let dataURI = "resource://gre/modules/Services.jsm";
-
- let newTab = yield loadNewTab(dataURI);
-
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_data_uri() {
- let oldTab = gBrowser.selectedTab;
- let dataURI = "data:text/html,hi"
-
- let newTab = yield loadNewTab(dataURI);
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* test_about_uri() {
- let oldTab = gBrowser.selectedTab;
- let aboutURI = "about:robots"
-
- let newTab = yield loadNewTab(aboutURI);
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.selectedTab = oldTab;
- is(getIdentityMode(), "unknownIdentity", "Identity should be unknown");
-
- gBrowser.selectedTab = newTab;
- is(getConnectionState(), "file", "Connection should be file");
-
- gBrowser.removeTab(newTab);
-});
diff --git a/browser/base/content/test/general/browser_bug592338.js b/browser/base/content/test/general/browser_bug592338.js
deleted file mode 100644
index ca9cc361a..000000000
--- a/browser/base/content/test/general/browser_bug592338.js
+++ /dev/null
@@ -1,163 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const TESTROOT = "http://example.com/browser/toolkit/mozapps/extensions/test/xpinstall/";
-
-var tempScope = {};
-Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", tempScope);
-var LightweightThemeManager = tempScope.LightweightThemeManager;
-
-function wait_for_notification(aCallback) {
- PopupNotifications.panel.addEventListener("popupshown", function() {
- PopupNotifications.panel.removeEventListener("popupshown", arguments.callee, false);
- aCallback(PopupNotifications.panel);
- }, false);
-}
-
-var TESTS = [
-function test_install_http() {
- is(LightweightThemeManager.currentTheme, null, "Should be no lightweight theme selected");
-
- var pm = Services.perms;
- pm.add(makeURI("http://example.org/"), "install", pm.ALLOW_ACTION);
-
- gBrowser.selectedTab = gBrowser.addTab("http://example.org/browser/browser/base/content/test/general/bug592338.html");
- gBrowser.selectedBrowser.addEventListener("pageshow", function() {
- if (gBrowser.contentDocument.location.href == "about:blank")
- return;
-
- gBrowser.selectedBrowser.removeEventListener("pageshow", arguments.callee, false);
-
- executeSoon(function() {
- BrowserTestUtils.synthesizeMouse("#theme-install", 2, 2, {}, gBrowser.selectedBrowser);
-
- is(LightweightThemeManager.currentTheme, null, "Should not have installed the test theme");
-
- gBrowser.removeTab(gBrowser.selectedTab);
-
- pm.remove(makeURI("http://example.org/"), "install");
-
- runNextTest();
- });
- }, false);
-},
-
-function test_install_lwtheme() {
- is(LightweightThemeManager.currentTheme, null, "Should be no lightweight theme selected");
-
- var pm = Services.perms;
- pm.add(makeURI("https://example.com/"), "install", pm.ALLOW_ACTION);
-
- gBrowser.selectedTab = gBrowser.addTab("https://example.com/browser/browser/base/content/test/general/bug592338.html");
- gBrowser.selectedBrowser.addEventListener("pageshow", function() {
- if (gBrowser.contentDocument.location.href == "about:blank")
- return;
-
- gBrowser.selectedBrowser.removeEventListener("pageshow", arguments.callee, false);
-
- BrowserTestUtils.synthesizeMouse("#theme-install", 2, 2, {}, gBrowser.selectedBrowser);
- let notificationBox = gBrowser.getNotificationBox(gBrowser.selectedBrowser);
- waitForCondition(
- () => notificationBox.getNotificationWithValue("lwtheme-install-notification"),
- () => {
- is(LightweightThemeManager.currentTheme.id, "test", "Should have installed the test theme");
-
- LightweightThemeManager.currentTheme = null;
- gBrowser.removeTab(gBrowser.selectedTab);
- Services.perms.remove(makeURI("http://example.com/"), "install");
-
- runNextTest();
- }
- );
- }, false);
-},
-
-function test_lwtheme_switch_theme() {
- is(LightweightThemeManager.currentTheme, null, "Should be no lightweight theme selected");
-
- AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) {
- aAddon.userDisabled = false;
- ok(aAddon.isActive, "Theme should have immediately enabled");
- Services.prefs.setBoolPref("extensions.dss.enabled", false);
-
- var pm = Services.perms;
- pm.add(makeURI("https://example.com/"), "install", pm.ALLOW_ACTION);
-
- gBrowser.selectedTab = gBrowser.addTab("https://example.com/browser/browser/base/content/test/general/bug592338.html");
- gBrowser.selectedBrowser.addEventListener("pageshow", function() {
- if (gBrowser.contentDocument.location.href == "about:blank")
- return;
-
- gBrowser.selectedBrowser.removeEventListener("pageshow", arguments.callee, false);
-
- executeSoon(function() {
- wait_for_notification(function(aPanel) {
- is(LightweightThemeManager.currentTheme, null, "Should not have installed the test lwtheme");
- ok(aAddon.isActive, "Test theme should still be active");
-
- let notification = aPanel.childNodes[0];
- is(notification.button.label, "Restart Now", "Should have seen the right button");
-
- ok(aAddon.userDisabled, "Should be waiting to disable the test theme");
- aAddon.userDisabled = false;
- Services.prefs.setBoolPref("extensions.dss.enabled", true);
-
- gBrowser.removeTab(gBrowser.selectedTab);
-
- Services.perms.remove(makeURI("http://example.com"), "install");
-
- runNextTest();
- });
- BrowserTestUtils.synthesizeMouse("#theme-install", 2, 2, {}, gBrowser.selectedBrowser);
- });
- }, false);
- });
-}
-];
-
-function runNextTest() {
- AddonManager.getAllInstalls(function(aInstalls) {
- is(aInstalls.length, 0, "Should be no active installs");
-
- if (TESTS.length == 0) {
- AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) {
- aAddon.uninstall();
-
- Services.prefs.setBoolPref("extensions.logging.enabled", false);
- Services.prefs.setBoolPref("extensions.dss.enabled", false);
-
- finish();
- });
- return;
- }
-
- info("Running " + TESTS[0].name);
- TESTS.shift()();
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref("extensions.logging.enabled", true);
-
- AddonManager.getInstallForURL(TESTROOT + "theme.xpi", function(aInstall) {
- aInstall.addListener({
- onInstallEnded: function() {
- AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) {
- isnot(aAddon, null, "Should have installed the test theme.");
-
- // In order to switch themes while the test is running we turn on dynamic
- // theme switching. This means the test isn't exactly correct but should
- // do some good
- Services.prefs.setBoolPref("extensions.dss.enabled", true);
-
- runNextTest();
- });
- }
- });
-
- aInstall.install();
- }, "application/x-xpinstall");
-}
diff --git a/browser/base/content/test/general/browser_bug594131.js b/browser/base/content/test/general/browser_bug594131.js
deleted file mode 100644
index ce09026ac..000000000
--- a/browser/base/content/test/general/browser_bug594131.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* 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/. */
-
-function test() {
- let newTab = gBrowser.addTab("http://example.com");
- waitForExplicitFinish();
- BrowserTestUtils.browserLoaded(newTab.linkedBrowser).then(mainPart);
-
- function mainPart() {
- gBrowser.pinTab(newTab);
- gBrowser.selectedTab = newTab;
-
- openUILinkIn("http://example.org/", "current", { inBackground: true });
- isnot(gBrowser.selectedTab, newTab, "shouldn't load in background");
-
- gBrowser.removeTab(newTab);
- gBrowser.removeTab(gBrowser.tabs[1]); // example.org tab
- finish();
- }
-}
diff --git a/browser/base/content/test/general/browser_bug595507.js b/browser/base/content/test/general/browser_bug595507.js
deleted file mode 100644
index 54ae42346..000000000
--- a/browser/base/content/test/general/browser_bug595507.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Make sure that the form validation error message shows even if the form is in an iframe.
- */
-add_task(function* () {
- let uri = "<iframe src=\"data:text/html,<iframe name='t'></iframe><form target='t' action='data:text/html,'><input required id='i'><input id='s' type='submit'></form>\"</iframe>";
-
- var gInvalidFormPopup = document.getElementById('invalid-form-popup');
- ok(gInvalidFormPopup,
- "The browser should have a popup to show when a form is invalid");
-
- let tab = gBrowser.addTab();
- let browser = gBrowser.getBrowserForTab(tab);
- gBrowser.selectedTab = tab;
-
- yield promiseTabLoadEvent(tab, "data:text/html," + escape(uri));
-
- let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
-
- yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementsByTagName('iframe')[0]
- .contentDocument.getElementById('s').click();
- });
- yield popupShownPromise;
-
- yield ContentTask.spawn(browser, {}, function* () {
- let childdoc = content.document.getElementsByTagName('iframe')[0].contentDocument;
- Assert.equal(childdoc.activeElement, childdoc.getElementById("i"),
- "First invalid element should be focused");
- });
-
- ok(gInvalidFormPopup.state == 'showing' || gInvalidFormPopup.state == 'open',
- "The invalid form popup should be shown");
-
- gBrowser.removeCurrentTab();
-});
-
diff --git a/browser/base/content/test/general/browser_bug596687.js b/browser/base/content/test/general/browser_bug596687.js
deleted file mode 100644
index 5c2b4fbfe..000000000
--- a/browser/base/content/test/general/browser_bug596687.js
+++ /dev/null
@@ -1,25 +0,0 @@
-add_task(function* test() {
- var tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- var gotTabAttrModified = false;
- var gotTabClose = false;
-
- function onTabClose() {
- gotTabClose = true;
- tab.addEventListener("TabAttrModified", onTabAttrModified, false);
- }
-
- function onTabAttrModified() {
- gotTabAttrModified = true;
- }
-
- tab.addEventListener("TabClose", onTabClose, false);
-
- yield BrowserTestUtils.removeTab(tab);
-
- ok(gotTabClose, "should have got the TabClose event");
- ok(!gotTabAttrModified, "shouldn't have got the TabAttrModified event after TabClose");
-
- tab.removeEventListener("TabClose", onTabClose, false);
- tab.removeEventListener("TabAttrModified", onTabAttrModified, false);
-});
diff --git a/browser/base/content/test/general/browser_bug597218.js b/browser/base/content/test/general/browser_bug597218.js
deleted file mode 100644
index 5f4ededc3..000000000
--- a/browser/base/content/test/general/browser_bug597218.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- // establish initial state
- is(gBrowser.tabs.length, 1, "we start with one tab");
-
- // create a tab
- let tab = gBrowser.loadOneTab("about:blank");
- ok(!tab.hidden, "tab starts out not hidden");
- is(gBrowser.tabs.length, 2, "we now have two tabs");
-
- // make sure .hidden is read-only
- tab.hidden = true;
- ok(!tab.hidden, "can't set .hidden directly");
-
- // hide the tab
- gBrowser.hideTab(tab);
- ok(tab.hidden, "tab is hidden");
-
- // now pin it and make sure it gets unhidden
- gBrowser.pinTab(tab);
- ok(tab.pinned, "tab was pinned");
- ok(!tab.hidden, "tab was unhidden");
-
- // try hiding it now that it's pinned; shouldn't be able to
- gBrowser.hideTab(tab);
- ok(!tab.hidden, "tab did not hide");
-
- // clean up
- gBrowser.removeTab(tab);
- is(gBrowser.tabs.length, 1, "we finish with one tab");
-
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug609700.js b/browser/base/content/test/general/browser_bug609700.js
deleted file mode 100644
index 8b4f1ea91..000000000
--- a/browser/base/content/test/general/browser_bug609700.js
+++ /dev/null
@@ -1,20 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- Services.ww.unregisterNotification(arguments.callee);
-
- ok(true, "duplicateTabIn opened a new window");
-
- whenDelayedStartupFinished(aSubject, function () {
- executeSoon(function () {
- aSubject.close();
- finish();
- });
- }, false);
- }
- });
-
- duplicateTabIn(gBrowser.selectedTab, "window");
-}
diff --git a/browser/base/content/test/general/browser_bug623893.js b/browser/base/content/test/general/browser_bug623893.js
deleted file mode 100644
index fa6da1b22..000000000
--- a/browser/base/content/test/general/browser_bug623893.js
+++ /dev/null
@@ -1,37 +0,0 @@
-add_task(function* test() {
- yield BrowserTestUtils.withNewTab("data:text/plain;charset=utf-8,1", function* (browser) {
- BrowserTestUtils.loadURI(browser, "data:text/plain;charset=utf-8,2");
- yield BrowserTestUtils.browserLoaded(browser);
-
- BrowserTestUtils.loadURI(browser, "data:text/plain;charset=utf-8,3");
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield duplicate(0, "maintained the original index");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- yield duplicate(-1, "went back");
- yield duplicate(1, "went forward");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-});
-
-function promiseGetIndex(browser) {
- return ContentTask.spawn(browser, null, function() {
- let shistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- return shistory.index;
- });
-}
-
-let duplicate = Task.async(function* (delta, msg, cb) {
- var startIndex = yield promiseGetIndex(gBrowser.selectedBrowser);
-
- duplicateTabIn(gBrowser.selectedTab, "tab", delta);
-
- let tab = gBrowser.selectedTab;
- yield BrowserTestUtils.waitForEvent(tab, "SSTabRestored");
-
- let endIndex = yield promiseGetIndex(gBrowser.selectedBrowser);
- is(endIndex, startIndex + delta, msg);
-});
diff --git a/browser/base/content/test/general/browser_bug624734.js b/browser/base/content/test/general/browser_bug624734.js
deleted file mode 100644
index d6fc7acbc..000000000
--- a/browser/base/content/test/general/browser_bug624734.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-// Bug 624734 - Star UI has no tooltip until bookmarked page is visited
-
-function finishTest() {
- is(BookmarkingUI.button.getAttribute("buttontooltiptext"),
- BookmarkingUI._unstarredTooltip,
- "Star icon should have the unstarred tooltip text");
-
- gBrowser.removeCurrentTab();
- finish();
-}
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- BrowserTestUtils.browserLoaded(tab.linkedBrowser).then(() => {
- if (BookmarkingUI.status == BookmarkingUI.STATUS_UPDATING) {
- waitForCondition(() => BookmarkingUI.status != BookmarkingUI.STATUS_UPDATING, finishTest, "BookmarkingUI was updating for too long");
- } else {
- finishTest();
- }
- });
-
- tab.linkedBrowser.loadURI("http://example.com/browser/browser/base/content/test/general/dummy_page.html");
-}
diff --git a/browser/base/content/test/general/browser_bug633691.js b/browser/base/content/test/general/browser_bug633691.js
deleted file mode 100644
index 28a8440ff..000000000
--- a/browser/base/content/test/general/browser_bug633691.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-add_task(function* test() {
- const URL = "data:text/html,<iframe width='700' height='700'></iframe>";
- yield BrowserTestUtils.withNewTab({ gBrowser, url: URL }, function* (browser) {
- yield ContentTask.spawn(browser,
- { is_element_hidden_: is_element_hidden.toSource(),
- is_hidden_: is_hidden.toSource() },
- function* ({ is_element_hidden_, is_hidden_ }) {
- let loadError =
- ContentTaskUtils.waitForEvent(this, "AboutNetErrorLoad", false, null, true);
- let iframe = content.document.querySelector("iframe");
- iframe.src = "https://expired.example.com/";
-
- yield loadError;
-
- let is_hidden = eval(`(() => ${is_hidden_})()`);
- let is_element_hidden = eval(`(() => ${is_element_hidden_})()`);
- let doc = content.document.getElementsByTagName("iframe")[0].contentDocument;
- let aP = doc.getElementById("badCertAdvancedPanel");
- ok(aP, "Advanced content should exist");
- void is_hidden; // Quiet eslint warnings (actual use under is_element_hidden)
- is_element_hidden(aP, "Advanced content should not be visible by default")
- });
- });
-});
diff --git a/browser/base/content/test/general/browser_bug647886.js b/browser/base/content/test/general/browser_bug647886.js
deleted file mode 100644
index 6c28c465c..000000000
--- a/browser/base/content/test/general/browser_bug647886.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- content.history.pushState({}, "2", "2.html");
- });
-
- var backButton = document.getElementById("back-button");
- var rect = backButton.getBoundingClientRect();
-
- info("waiting for the history menu to open");
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(backButton, "popupshown");
- EventUtils.synthesizeMouseAtCenter(backButton, {type: "mousedown"});
- EventUtils.synthesizeMouse(backButton, rect.width / 2, rect.height, {type: "mouseup"});
- let event = yield popupShownPromise;
-
- ok(true, "history menu opened");
-
- // Wait for the session data to be flushed before continuing the test
- yield new Promise(resolve => SessionStore.getSessionHistory(gBrowser.selectedTab, resolve));
-
- is(event.target.children.length, 2, "Two history items");
-
- let node = event.target.firstChild;
- is(node.getAttribute("uri"), "http://example.com/2.html", "first item uri");
- is(node.getAttribute("index"), "1", "first item index");
- is(node.getAttribute("historyindex"), "0", "first item historyindex");
-
- node = event.target.lastChild;
- is(node.getAttribute("uri"), "http://example.com/", "second item uri");
- is(node.getAttribute("index"), "0", "second item index");
- is(node.getAttribute("historyindex"), "-1", "second item historyindex");
-
- event.target.hidePopup();
- gBrowser.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_bug655584.js b/browser/base/content/test/general/browser_bug655584.js
deleted file mode 100644
index b836e3173..000000000
--- a/browser/base/content/test/general/browser_bug655584.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-// Bug 655584 - awesomebar suggestions don't update after tab is closed
-
-add_task(function* () {
- var tab1 = gBrowser.addTab();
- var tab2 = gBrowser.addTab();
-
- // When urlbar in a new tab is focused, and a tab switch occurs,
- // the urlbar popup should be closed
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- gURLBar.focus(); // focus the urlbar in the tab we will switch to
- yield BrowserTestUtils.switchTab(gBrowser, tab1);
- gURLBar.openPopup();
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- ok(!gURLBar.popupOpen, "urlbar focused in tab to switch to, close popup");
-
- // cleanup
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug664672.js b/browser/base/content/test/general/browser_bug664672.js
deleted file mode 100644
index 2064f77d0..000000000
--- a/browser/base/content/test/general/browser_bug664672.js
+++ /dev/null
@@ -1,19 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- var tab = gBrowser.addTab();
-
- tab.addEventListener("TabClose", function () {
- tab.removeEventListener("TabClose", arguments.callee, false);
-
- ok(tab.linkedBrowser, "linkedBrowser should still exist during the TabClose event");
-
- executeSoon(function () {
- ok(!tab.linkedBrowser, "linkedBrowser should be gone after the TabClose event");
-
- finish();
- });
- }, false);
-
- gBrowser.removeTab(tab);
-}
diff --git a/browser/base/content/test/general/browser_bug676619.js b/browser/base/content/test/general/browser_bug676619.js
deleted file mode 100644
index 6b596481d..000000000
--- a/browser/base/content/test/general/browser_bug676619.js
+++ /dev/null
@@ -1,124 +0,0 @@
-function test () {
- requestLongerTimeout(3);
- waitForExplicitFinish();
-
- var isHTTPS = false;
-
- function loadListener() {
- function testLocation(link, url, next) {
- new TabOpenListener(url, function () {
- gBrowser.removeTab(this.tab);
- }, function () {
- next();
- });
-
- ContentTask.spawn(gBrowser.selectedBrowser, link, contentLink => {
- content.document.getElementById(contentLink).click();
- });
- }
-
- function testLink(link, name, next) {
- addWindowListener("chrome://mozapps/content/downloads/unknownContentType.xul", function (win) {
- ContentTask.spawn(gBrowser.selectedBrowser, null, () => {
- Assert.equal(content.document.getElementById("unload-flag").textContent,
- "Okay", "beforeunload shouldn't have fired");
- }).then(() => {
- is(win.document.getElementById("location").value, name, "file name should match");
- win.close();
- next();
- });
- });
-
- ContentTask.spawn(gBrowser.selectedBrowser, link, contentLink => {
- content.document.getElementById(contentLink).click();
- });
- }
-
- testLink("link1", "test.txt",
- testLink.bind(null, "link2", "video.ogg",
- testLink.bind(null, "link3", "just some video",
- testLink.bind(null, "link4", "with-target.txt",
- testLink.bind(null, "link5", "javascript.txt",
- testLink.bind(null, "link6", "test.blob",
- testLocation.bind(null, "link7", "http://example.com/",
- function () {
- if (isHTTPS) {
- finish();
- } else {
- // same test again with https:
- isHTTPS = true;
- gBrowser.loadURI("https://example.com:443/browser/browser/base/content/test/general/download_page.html");
- }
- })))))));
-
- }
-
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => {
- loadListener();
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(loadListener);
- });
-
- gBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/general/download_page.html");
-}
-
-
-function addWindowListener(aURL, aCallback) {
- Services.wm.addListener({
- onOpenWindow: function(aXULWindow) {
- info("window opened, waiting for focus");
- Services.wm.removeListener(this);
-
- var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- waitForFocus(function() {
- is(domwindow.document.location.href, aURL, "should have seen the right window open");
- aCallback(domwindow);
- }, domwindow);
- },
- onCloseWindow: function(aXULWindow) { },
- onWindowTitleChange: function(aXULWindow, aNewTitle) { }
- });
-}
-
-// This listens for the next opened tab and checks it is of the right url.
-// opencallback is called when the new tab is fully loaded
-// closecallback is called when the tab is closed
-function TabOpenListener(url, opencallback, closecallback) {
- this.url = url;
- this.opencallback = opencallback;
- this.closecallback = closecallback;
-
- gBrowser.tabContainer.addEventListener("TabOpen", this, false);
-}
-
-TabOpenListener.prototype = {
- url: null,
- opencallback: null,
- closecallback: null,
- tab: null,
- browser: null,
-
- handleEvent: function(event) {
- if (event.type == "TabOpen") {
- gBrowser.tabContainer.removeEventListener("TabOpen", this, false);
- this.tab = event.originalTarget;
- this.browser = this.tab.linkedBrowser;
- BrowserTestUtils.browserLoaded(this.browser, false, this.url).then(() => {
- this.tab.addEventListener("TabClose", this, false);
- var url = this.browser.currentURI.spec;
- is(url, this.url, "Should have opened the correct tab");
- this.opencallback();
- });
- } else if (event.type == "TabClose") {
- if (event.originalTarget != this.tab)
- return;
- this.tab.removeEventListener("TabClose", this, false);
- this.opencallback = null;
- this.tab = null;
- this.browser = null;
- // Let the window close complete
- executeSoon(this.closecallback);
- this.closecallback = null;
- }
- }
-};
diff --git a/browser/base/content/test/general/browser_bug678392-1.html b/browser/base/content/test/general/browser_bug678392-1.html
deleted file mode 100644
index c3b235dd0..000000000
--- a/browser/base/content/test/general/browser_bug678392-1.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html>
- <head>
- <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
- <meta content="utf-8" http-equiv="encoding">
- <title>bug678392 - 1</title>
- </head>
- <body>
-bug 678392 test page 1
- </body>
-</html> \ No newline at end of file
diff --git a/browser/base/content/test/general/browser_bug678392-2.html b/browser/base/content/test/general/browser_bug678392-2.html
deleted file mode 100644
index 9b18efcf7..000000000
--- a/browser/base/content/test/general/browser_bug678392-2.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html>
- <head>
- <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
- <meta content="utf-8" http-equiv="encoding">
- <title>bug678392 - 2</title>
- </head>
- <body>
-bug 678392 test page 2
- </body>
-</html> \ No newline at end of file
diff --git a/browser/base/content/test/general/browser_bug678392.js b/browser/base/content/test/general/browser_bug678392.js
deleted file mode 100644
index 6aedeefdf..000000000
--- a/browser/base/content/test/general/browser_bug678392.js
+++ /dev/null
@@ -1,191 +0,0 @@
-/* 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/. */
-
-var HTTPROOT = "http://example.com/browser/browser/base/content/test/general/";
-
-function maxSnapshotOverride() {
- return 5;
-}
-
-function test() {
- waitForExplicitFinish();
-
- BrowserOpenTab();
- let tab = gBrowser.selectedTab;
- registerCleanupFunction(function () { gBrowser.removeTab(tab); });
-
- ok(gHistorySwipeAnimation, "gHistorySwipeAnimation exists.");
-
- if (!gHistorySwipeAnimation._isSupported()) {
- is(gHistorySwipeAnimation.active, false, "History swipe animation is not " +
- "active when not supported by the platform.");
- finish();
- return;
- }
-
- gHistorySwipeAnimation._getMaxSnapshots = maxSnapshotOverride;
- gHistorySwipeAnimation.init();
-
- is(gHistorySwipeAnimation.active, true, "History swipe animation support " +
- "was successfully initialized when supported.");
-
- cleanupArray();
- load(gBrowser.selectedTab, HTTPROOT + "browser_bug678392-2.html", test0);
-}
-
-function load(aTab, aUrl, aCallback) {
- aTab.linkedBrowser.addEventListener("load", function onload(aEvent) {
- aEvent.currentTarget.removeEventListener("load", onload, true);
- waitForFocus(aCallback, content);
- }, true);
- aTab.linkedBrowser.loadURI(aUrl);
-}
-
-function cleanupArray() {
- let arr = gHistorySwipeAnimation._trackedSnapshots;
- while (arr.length > 0) {
- delete arr[0].browser.snapshots[arr[0].index]; // delete actual snapshot
- arr.splice(0, 1);
- }
-}
-
-function testArrayCleanup() {
- // Test cleanup of array of tracked snapshots.
- let arr = gHistorySwipeAnimation._trackedSnapshots;
- is(arr.length, 0, "Snapshots were removed correctly from the array of " +
- "tracked snapshots.");
-}
-
-function test0() {
- // Test growing of array of tracked snapshots.
- let tab = gBrowser.selectedTab;
-
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- ok(gHistorySwipeAnimation._trackedSnapshots, "Array for snapshot " +
- "tracking is initialized.");
- is(gHistorySwipeAnimation._trackedSnapshots.length, 1, "Snapshot array " +
- "has correct length of 1 after loading one page.");
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- is(gHistorySwipeAnimation._trackedSnapshots.length, 2, "Snapshot array " +
- " has correct length of 2 after loading two pages.");
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- is(gHistorySwipeAnimation._trackedSnapshots.length, 3, "Snapshot " +
- "array has correct length of 3 after loading three pages.");
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- is(gHistorySwipeAnimation._trackedSnapshots.length, 4, "Snapshot " +
- "array has correct length of 4 after loading four pages.");
- cleanupArray();
- testArrayCleanup();
- test1();
- });
- });
- });
- });
-}
-
-function verifyRefRemoved(aIndex, aBrowser) {
- let wasFound = false;
- let arr = gHistorySwipeAnimation._trackedSnapshots;
- for (let i = 0; i < arr.length; i++) {
- if (arr[i].index == aIndex && arr[i].browser == aBrowser)
- wasFound = true;
- }
- is(wasFound, false, "The reference that was previously removed was " +
- "still found in the array of tracked snapshots.");
-}
-
-function test1() {
- // Test presence of snpashots in per-tab array of snapshots and removal of
- // individual snapshots (and corresponding references in the array of
- // tracked snapshots).
- let tab = gBrowser.selectedTab;
-
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- var historyIndex = gBrowser.webNavigation.sessionHistory.index - 1;
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- let browser = gBrowser.selectedBrowser;
- ok(browser.snapshots, "Array of snapshots exists in browser.");
- ok(browser.snapshots[historyIndex], "First page exists in snapshot " +
- "array.");
- ok(browser.snapshots[historyIndex + 1], "Second page exists in " +
- "snapshot array.");
- ok(browser.snapshots[historyIndex + 2], "Third page exists in " +
- "snapshot array.");
- ok(browser.snapshots[historyIndex + 3], "Fourth page exists in " +
- "snapshot array.");
- is(gHistorySwipeAnimation._trackedSnapshots.length, 4, "Length of " +
- "array of tracked snapshots is equal to 4 after loading four " +
- "pages.");
-
- // Test removal of reference in the middle of the array.
- gHistorySwipeAnimation._removeTrackedSnapshot(historyIndex + 1,
- browser);
- verifyRefRemoved(historyIndex + 1, browser);
- is(gHistorySwipeAnimation._trackedSnapshots.length, 3, "Length of " +
- "array of tracked snapshots is equal to 3 after removing one" +
- "reference from the array with length 4.");
-
- // Test removal of reference at end of array.
- gHistorySwipeAnimation._removeTrackedSnapshot(historyIndex + 3,
- browser);
- verifyRefRemoved(historyIndex + 3, browser);
- is(gHistorySwipeAnimation._trackedSnapshots.length, 2, "Length of " +
- "array of tracked snapshots is equal to 2 after removing two" +
- "references from the array with length 4.");
-
- // Test removal of reference at head of array.
- gHistorySwipeAnimation._removeTrackedSnapshot(historyIndex,
- browser);
- verifyRefRemoved(historyIndex, browser);
- is(gHistorySwipeAnimation._trackedSnapshots.length, 1, "Length of " +
- "array of tracked snapshots is equal to 1 after removing three" +
- "references from the array with length 4.");
-
- cleanupArray();
- test2();
- });
- });
- });
- });
-}
-
-function test2() {
- // Test growing of snapshot array across tabs.
- let tab = gBrowser.selectedTab;
-
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- is(gHistorySwipeAnimation._trackedSnapshots.length, 2, "Length of " +
- "snapshot array is equal to 2 after loading two pages");
- let prevTab = tab;
- tab = gBrowser.addTab("about:newtab");
- gBrowser.selectedTab = tab;
- load(tab, HTTPROOT + "browser_bug678392-2.html" /* initial page */,
- function() {
- load(tab, HTTPROOT + "browser_bug678392-1.html", function() {
- load(tab, HTTPROOT + "browser_bug678392-2.html", function() {
- is(gHistorySwipeAnimation._trackedSnapshots.length, 4, "Length " +
- "of snapshot array is equal to 4 after loading two pages in " +
- "two tabs each.");
- gBrowser.removeCurrentTab();
- gBrowser.selectedTab = prevTab;
- cleanupArray();
- test3();
- });
- });
- });
- });
- });
-}
-
-function test3() {
- // Test uninit of gHistorySwipeAnimation.
- // This test MUST be the last one to execute.
- gHistorySwipeAnimation.uninit();
- is(gHistorySwipeAnimation.active, false, "History swipe animation support " +
- "was successfully uninitialized");
- finish();
-}
diff --git a/browser/base/content/test/general/browser_bug710878.js b/browser/base/content/test/general/browser_bug710878.js
deleted file mode 100644
index dd99d67cf..000000000
--- a/browser/base/content/test/general/browser_bug710878.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PAGE = "data:text/html;charset=utf-8,<a href='%23xxx'><span>word1 <span> word2 </span></span><span> word3</span></a>";
-
-/**
- * Tests that we correctly compute the text for context menu
- * selection of some content.
- */
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu,
- "popupshown");
- let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu,
- "popuphidden");
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("a", {
- type: "contextmenu",
- button: 2,
- }, browser);
-
- yield awaitPopupShown;
-
- is(gContextMenu.linkTextStr, "word1 word2 word3",
- "Text under link is correctly computed.");
-
- contextMenu.hidePopup();
- yield awaitPopupHidden;
- });
-});
diff --git a/browser/base/content/test/general/browser_bug719271.js b/browser/base/content/test/general/browser_bug719271.js
deleted file mode 100644
index c3bb9cd26..000000000
--- a/browser/base/content/test/general/browser_bug719271.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* 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/. */
-"use strict";
-
-const TEST_PAGE = "http://example.org/browser/browser/base/content/test/general/zoom_test.html";
-const TEST_VIDEO = "http://example.org/browser/browser/base/content/test/general/video.ogg";
-
-var gTab1, gTab2, gLevel1;
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- gTab1 = gBrowser.addTab();
- gTab2 = gBrowser.addTab();
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoomHelper.load(gTab1, TEST_PAGE);
- yield FullZoomHelper.load(gTab2, TEST_VIDEO);
- }).then(zoomTab1, FullZoomHelper.failAndContinue(finish));
-}
-
-function zoomTab1() {
- Task.spawn(function* () {
- is(gBrowser.selectedTab, gTab1, "Tab 1 is selected");
-
- // Reset zoom level if we run this test > 1 time in same browser session.
- var level1 = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab1));
- if (level1 > 1)
- FullZoom.reduce();
-
- FullZoomHelper.zoomTest(gTab1, 1, "Initial zoom of tab 1 should be 1");
- FullZoomHelper.zoomTest(gTab2, 1, "Initial zoom of tab 2 should be 1");
-
- FullZoom.enlarge();
- gLevel1 = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab1));
-
- ok(gLevel1 > 1, "New zoom for tab 1 should be greater than 1");
- FullZoomHelper.zoomTest(gTab2, 1, "Zooming tab 1 should not affect tab 2");
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- FullZoomHelper.zoomTest(gTab2, 1, "Tab 2 is still unzoomed after it is selected");
- FullZoomHelper.zoomTest(gTab1, gLevel1, "Tab 1 is still zoomed");
- }).then(zoomTab2, FullZoomHelper.failAndContinue(finish));
-}
-
-function zoomTab2() {
- Task.spawn(function* () {
- is(gBrowser.selectedTab, gTab2, "Tab 2 is selected");
-
- FullZoom.reduce();
- let level2 = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab2));
-
- ok(level2 < 1, "New zoom for tab 2 should be less than 1");
- FullZoomHelper.zoomTest(gTab1, gLevel1, "Zooming tab 2 should not affect tab 1");
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- FullZoomHelper.zoomTest(gTab1, gLevel1, "Tab 1 should have the same zoom after it's selected");
- }).then(testNavigation, FullZoomHelper.failAndContinue(finish));
-}
-
-function testNavigation() {
- Task.spawn(function* () {
- yield FullZoomHelper.load(gTab1, TEST_VIDEO);
- FullZoomHelper.zoomTest(gTab1, 1, "Zoom should be 1 when a video was loaded");
- yield waitForNextTurn(); // trying to fix orange bug 806046
- yield FullZoomHelper.navigate(FullZoomHelper.BACK);
- FullZoomHelper.zoomTest(gTab1, gLevel1, "Zoom should be restored when a page is loaded");
- yield waitForNextTurn(); // trying to fix orange bug 806046
- yield FullZoomHelper.navigate(FullZoomHelper.FORWARD);
- FullZoomHelper.zoomTest(gTab1, 1, "Zoom should be 1 again when navigating back to a video");
- }).then(finishTest, FullZoomHelper.failAndContinue(finish));
-}
-
-function waitForNextTurn() {
- let deferred = Promise.defer();
- setTimeout(() => deferred.resolve(), 0);
- return deferred.promise;
-}
-
-var finishTestStarted = false;
-function finishTest() {
- Task.spawn(function* () {
- ok(!finishTestStarted, "finishTest called more than once");
- finishTestStarted = true;
-
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab1);
- yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
- yield FullZoom.reset();
- yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab2);
- }).then(finish, FullZoomHelper.failAndContinue(finish));
-}
diff --git a/browser/base/content/test/general/browser_bug724239.js b/browser/base/content/test/general/browser_bug724239.js
deleted file mode 100644
index 430751b91..000000000
--- a/browser/base/content/test/general/browser_bug724239.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* test() {
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (browser) {
- BrowserTestUtils.loadURI(browser, "http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(!gBrowser.canGoBack, "about:newtab wasn't added to the session history");
- });
-});
diff --git a/browser/base/content/test/general/browser_bug734076.js b/browser/base/content/test/general/browser_bug734076.js
deleted file mode 100644
index 9de7d913f..000000000
--- a/browser/base/content/test/general/browser_bug734076.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* ()
-{
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, null, false);
-
- let browser = tab.linkedBrowser;
- browser.stop(); // stop the about:blank load
-
- let writeDomainURL = encodeURI("data:text/html,<script>document.write(document.domain);</script>");
-
- let tests = [
- {
- name: "view background image",
- url: "http://mochi.test:8888/",
- element: "body",
- go: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) {
- let contentBody = content.document.body;
- contentBody.style.backgroundImage = "url('" + arg.writeDomainURL + "')";
-
- return "context-viewbgimage";
- });
- },
- verify: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) {
- Assert.ok(!content.document.body.textContent,
- "no domain was inherited for view background image");
- });
- }
- },
- {
- name: "view image",
- url: "http://mochi.test:8888/",
- element: "img",
- go: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) {
- let doc = content.document;
- let img = doc.createElement("img");
- img.height = 100;
- img.width = 100;
- img.setAttribute("src", arg.writeDomainURL);
- doc.body.insertBefore(img, doc.body.firstChild);
-
- return "context-viewimage";
- });
- },
- verify: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) {
- Assert.ok(!content.document.body.textContent,
- "no domain was inherited for view image");
- });
- }
- },
- {
- name: "show only this frame",
- url: "http://mochi.test:8888/",
- element: "iframe",
- go: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) {
- let doc = content.document;
- let iframe = doc.createElement("iframe");
- iframe.setAttribute("src", arg.writeDomainURL);
- doc.body.insertBefore(iframe, doc.body.firstChild);
-
- // Wait for the iframe to load.
- return new Promise(resolve => {
- iframe.addEventListener("load", function onload() {
- iframe.removeEventListener("load", onload, true);
- resolve("context-showonlythisframe");
- }, true);
- });
- });
- },
- verify: function () {
- return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) {
- Assert.ok(!content.document.body.textContent,
- "no domain was inherited for 'show only this frame'");
- });
- }
- }
- ];
-
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
-
- for (let test of tests) {
- let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI(test.url);
- yield loadedPromise;
-
- info("Run subtest " + test.name);
- let commandToRun = yield test.go();
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouse(test.element, 3, 3,
- { type: "contextmenu", button: 2 }, gBrowser.selectedBrowser);
- yield popupShownPromise;
- info("onImage: " + gContextMenu.onImage);
- info("target: " + gContextMenu.target.tagName);
-
- let loadedAfterCommandPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- document.getElementById(commandToRun).click();
- yield loadedAfterCommandPromise;
-
- yield test.verify();
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
- }
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug735471.js b/browser/base/content/test/general/browser_bug735471.js
deleted file mode 100644
index 9afb52c4b..000000000
--- a/browser/base/content/test/general/browser_bug735471.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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/.
- */
-
-
-function test() {
- waitForExplicitFinish();
- // Open a new tab.
- whenNewTabLoaded(window, testPreferences);
-}
-
-function testPreferences() {
- whenTabLoaded(gBrowser.selectedTab, function () {
- is(content.location.href, "about:preferences", "Checking if the preferences tab was opened");
-
- gBrowser.removeCurrentTab();
- finish();
- });
-
- openPreferences();
-}
diff --git a/browser/base/content/test/general/browser_bug749738.js b/browser/base/content/test/general/browser_bug749738.js
deleted file mode 100644
index 7e805b799..000000000
--- a/browser/base/content/test/general/browser_bug749738.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const DUMMY_PAGE = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
-
- BrowserTestUtils.loadURI(tab.linkedBrowser, DUMMY_PAGE);
- BrowserTestUtils.browserLoaded(tab.linkedBrowser).then(() => {
- gFindBar.onFindCommand();
- EventUtils.sendString("Dummy");
- gBrowser.removeTab(tab);
-
- try {
- gFindBar.close();
- ok(true, "findbar.close should not throw an exception");
- } catch (e) {
- ok(false, "findbar.close threw exception: " + e);
- }
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_bug763468_perwindowpb.js b/browser/base/content/test/general/browser_bug763468_perwindowpb.js
deleted file mode 100644
index 23cb14b8c..000000000
--- a/browser/base/content/test/general/browser_bug763468_perwindowpb.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 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/. */
-"use strict";
-
-/* globals
- waitForExplicitFinish, whenNewWindowLoaded, whenNewTabLoaded,
- executeSoon, registerCleanupFunction, finish, is
-*/
-/* exported test */
-
-// This test makes sure that opening a new tab in private browsing mode opens about:privatebrowsing
-function test() {
- // initialization
- waitForExplicitFinish();
-
- let windowsToClose = [];
- let newTabURL;
- let mode;
-
- function doTest(aIsPrivateMode, aWindow, aCallback) {
- whenNewTabLoaded(aWindow, function() {
- if (aIsPrivateMode) {
- mode = "per window private browsing";
- newTabURL = "about:privatebrowsing";
- } else {
- mode = "normal";
- newTabURL = "about:newtab";
- }
-
- is(aWindow.gBrowser.currentURI.spec, newTabURL,
- "URL of NewTab should be " + newTabURL + " in " + mode + " mode");
-
- aWindow.gBrowser.removeTab(aWindow.gBrowser.selectedTab);
- aCallback();
- });
- }
-
- function testOnWindow(aOptions, aCallback) {
- whenNewWindowLoaded(aOptions, function(aWin) {
- windowsToClose.push(aWin);
- // execute should only be called when need, like when you are opening
- // web pages on the test. If calling executeSoon() is not necesary, then
- // call whenNewWindowLoaded() instead of testOnWindow() on your test.
- executeSoon(() => aCallback(aWin));
- });
- }
-
- // this function is called after calling finish() on the test.
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- // test first when not on private mode
- testOnWindow({}, function(aWin) {
- doTest(false, aWin, function() {
- // then test when on private mode
- testOnWindow({private: true}, function(aWin2) {
- doTest(true, aWin2, function() {
- // then test again when not on private mode
- testOnWindow({}, function(aWin3) {
- doTest(false, aWin3, finish);
- });
- });
- });
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_bug767836_perwindowpb.js b/browser/base/content/test/general/browser_bug767836_perwindowpb.js
deleted file mode 100644
index 7f5d15e76..000000000
--- a/browser/base/content/test/general/browser_bug767836_perwindowpb.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* 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/. */
-"use strict";
-/* globals waitForExplicitFinish, executeSoon, finish, whenNewWindowLoaded, ok */
-/* globals is */
-/* exported test */
-
-function test() {
- // initialization
- waitForExplicitFinish();
-
- let aboutNewTabService = Components.classes["@mozilla.org/browser/aboutnewtab-service;1"]
- .getService(Components.interfaces.nsIAboutNewTabService);
- let newTabURL;
- let testURL = "http://example.com/";
- let defaultURL = aboutNewTabService.newTabURL;
- let mode;
-
- function doTest(aIsPrivateMode, aWindow, aCallback) {
- openNewTab(aWindow, function() {
- if (aIsPrivateMode) {
- mode = "per window private browsing";
- newTabURL = "about:privatebrowsing";
- } else {
- mode = "normal";
- newTabURL = "about:newtab";
- }
-
- // Check the new tab opened while in normal/private mode
- is(aWindow.gBrowser.selectedBrowser.currentURI.spec, newTabURL,
- "URL of NewTab should be " + newTabURL + " in " + mode + " mode");
- // Set the custom newtab url
- aboutNewTabService.newTabURL = testURL;
- is(aboutNewTabService.newTabURL, testURL, "Custom newtab url is set");
-
- // Open a newtab after setting the custom newtab url
- openNewTab(aWindow, function() {
- is(aWindow.gBrowser.selectedBrowser.currentURI.spec, testURL,
- "URL of NewTab should be the custom url");
-
- // Clear the custom url.
- aboutNewTabService.resetNewTabURL();
- is(aboutNewTabService.newTabURL, defaultURL, "No custom newtab url is set");
-
- aWindow.gBrowser.removeTab(aWindow.gBrowser.selectedTab);
- aWindow.gBrowser.removeTab(aWindow.gBrowser.selectedTab);
- aWindow.close();
- aCallback();
- });
- });
- }
-
- function testOnWindow(aIsPrivate, aCallback) {
- whenNewWindowLoaded({private: aIsPrivate}, function(win) {
- executeSoon(() => aCallback(win));
- });
- }
-
- // check whether any custom new tab url has been configured
- ok(!aboutNewTabService.overridden, "No custom newtab url is set");
-
- // test normal mode
- testOnWindow(false, function(aWindow) {
- doTest(false, aWindow, function() {
- // test private mode
- testOnWindow(true, function(aWindow2) {
- doTest(true, aWindow2, function() {
- finish();
- });
- });
- });
- });
-}
-
-function openNewTab(aWindow, aCallback) {
- // Open a new tab
- aWindow.BrowserOpenTab();
-
- let browser = aWindow.gBrowser.selectedBrowser;
- if (browser.contentDocument.readyState === "complete") {
- executeSoon(aCallback);
- return;
- }
-
- browser.addEventListener("load", function onLoad() {
- browser.removeEventListener("load", onLoad, true);
- executeSoon(aCallback);
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_bug817947.js b/browser/base/content/test/general/browser_bug817947.js
deleted file mode 100644
index 3a76e36d3..000000000
--- a/browser/base/content/test/general/browser_bug817947.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-const URL = "http://mochi.test:8888/browser/";
-const PREF = "browser.sessionstore.restore_on_demand";
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref(PREF, true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF);
- });
-
- preparePendingTab(function (aTab) {
- let win = gBrowser.replaceTabWithWindow(aTab);
-
- whenDelayedStartupFinished(win, function () {
- let [tab] = win.gBrowser.tabs;
-
- whenLoaded(tab.linkedBrowser, function () {
- is(tab.linkedBrowser.currentURI.spec, URL, "correct url should be loaded");
- ok(!tab.hasAttribute("pending"), "tab should not be pending");
-
- win.close();
- finish();
- });
- });
- });
-}
-
-function preparePendingTab(aCallback) {
- let tab = gBrowser.addTab(URL);
-
- whenLoaded(tab.linkedBrowser, function () {
- BrowserTestUtils.removeTab(tab).then(() => {
- let [{state}] = JSON.parse(SessionStore.getClosedTabData(window));
-
- tab = gBrowser.addTab("about:blank");
- whenLoaded(tab.linkedBrowser, function () {
- SessionStore.setTabState(tab, JSON.stringify(state));
- ok(tab.hasAttribute("pending"), "tab should be pending");
- aCallback(tab);
- });
- });
- });
-}
-
-function whenLoaded(aElement, aCallback) {
- aElement.addEventListener("load", function onLoad() {
- aElement.removeEventListener("load", onLoad, true);
- executeSoon(aCallback);
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_bug822367.js b/browser/base/content/test/general/browser_bug822367.js
deleted file mode 100644
index 0d60c05cd..000000000
--- a/browser/base/content/test/general/browser_bug822367.js
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * User Override Mixed Content Block - Tests for Bug 822367
- */
-
-
-const PREF_DISPLAY = "security.mixed_content.block_display_content";
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-
-// We alternate for even and odd test cases to simulate different hosts
-const gHttpTestRoot = "https://example.com/browser/browser/base/content/test/general/";
-const gHttpTestRoot2 = "https://test1.example.com/browser/browser/base/content/test/general/";
-
-var gTestBrowser = null;
-
-add_task(function* test() {
- yield SpecialPowers.pushPrefEnv({ set: [[ PREF_DISPLAY, true ],
- [ PREF_ACTIVE, true ]] });
-
- var newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
- newTab.linkedBrowser.stop()
-
- // Mixed Script Test
- var url = gHttpTestRoot + "file_bug822367_1.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-// Mixed Script Test
-add_task(function* MixedTest1A() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest1B() {
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("p1").innerHTML == "hello",
- "Waited too long for mixed script to run in Test 1");
- });
-});
-
-// Mixed Display Test - Doorhanger should not appear
-add_task(function* MixedTest2() {
- var url = gHttpTestRoot2 + "file_bug822367_2.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: false});
-});
-
-// Mixed Script and Display Test - User Override should cause both the script and the image to load.
-add_task(function* MixedTest3() {
- var url = gHttpTestRoot + "file_bug822367_3.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest3A() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest3B() {
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let p1 = ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("p1").innerHTML == "hello",
- "Waited too long for mixed script to run in Test 3");
- let p2 = ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("p2").innerHTML == "bye",
- "Waited too long for mixed image to load in Test 3");
- yield Promise.all([ p1, p2 ]);
- });
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: true});
-});
-
-// Location change - User override on one page doesn't propogate to another page after location change.
-add_task(function* MixedTest4() {
- var url = gHttpTestRoot2 + "file_bug822367_4.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest4A() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest4B() {
- let url = gHttpTestRoot + "file_bug822367_4B.html";
- yield ContentTask.spawn(gTestBrowser, url, function* (wantedUrl) {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.location == wantedUrl,
- "Waited too long for mixed script to run in Test 4");
- });
-});
-
-add_task(function* MixedTest4C() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("p1").innerHTML == "",
- "Mixed script loaded in test 4 after location change!");
- });
-});
-
-// Mixed script attempts to load in a document.open()
-add_task(function* MixedTest5() {
- var url = gHttpTestRoot + "file_bug822367_5.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest5A() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest5B() {
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("p1").innerHTML == "hello",
- "Waited too long for mixed script to run in Test 5");
- });
-});
-
-// Mixed script attempts to load in a document.open() that is within an iframe.
-add_task(function* MixedTest6() {
- var url = gHttpTestRoot2 + "file_bug822367_6.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest6A() {
- gTestBrowser.removeEventListener("load", MixedTest6A, true);
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
-
- yield BrowserTestUtils.waitForCondition(
- () => gIdentityHandler._identityBox.classList.contains("mixedActiveBlocked"),
- "Waited too long for control center to get mixed active blocked state");
-});
-
-add_task(function* MixedTest6B() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
-
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* MixedTest6C() {
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- function test() {
- try {
- return content.document.getElementById("f1").contentDocument.getElementById("p1").innerHTML == "hello";
- } catch (e) {
- return false;
- }
- }
-
- yield ContentTaskUtils.waitForCondition(test, "Waited too long for mixed script to run in Test 6");
- });
-});
-
-add_task(function* MixedTest6D() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
-});
-
-add_task(function* cleanup() {
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug832435.js b/browser/base/content/test/general/browser_bug832435.js
deleted file mode 100644
index 6be2604cd..000000000
--- a/browser/base/content/test/general/browser_bug832435.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
- ok(true, "Starting up");
-
- gBrowser.selectedBrowser.focus();
- gURLBar.addEventListener("focus", function onFocus() {
- gURLBar.removeEventListener("focus", onFocus);
- ok(true, "Invoked onfocus handler");
- EventUtils.synthesizeKey("VK_RETURN", { shiftKey: true });
-
- // javscript: URIs are evaluated async.
- SimpleTest.executeSoon(function() {
- ok(true, "Evaluated without crashing");
- finish();
- });
- });
- gURLBar.inputField.value = "javascript: var foo = '11111111'; ";
- gURLBar.focus();
-}
diff --git a/browser/base/content/test/general/browser_bug839103.js b/browser/base/content/test/general/browser_bug839103.js
deleted file mode 100644
index 5240c92ed..000000000
--- a/browser/base/content/test/general/browser_bug839103.js
+++ /dev/null
@@ -1,120 +0,0 @@
-const gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-
-add_task(function* test() {
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (browser) {
- yield ContentTask.spawn(browser, gTestRoot, testBody);
- });
-});
-
-// This function runs entirely in the content process. It doesn't have access
-// any free variables in this file.
-function* testBody(testRoot) {
- const gStyleSheet = "bug839103.css";
-
- let loaded = ContentTaskUtils.waitForEvent(this, "load", true);
- content.location = testRoot + "test_bug839103.html";
-
- yield loaded;
- function unexpectedContentEvent(event) {
- ok(false, "Received a " + event.type + " event on content");
- }
-
- // We've seen the original stylesheet in the document.
- // Now add a stylesheet on the fly and make sure we see it.
- let doc = content.document;
- doc.styleSheetChangeEventsEnabled = true;
- doc.addEventListener("StyleSheetAdded", unexpectedContentEvent);
- doc.addEventListener("StyleSheetRemoved", unexpectedContentEvent);
- doc.addEventListener("StyleSheetApplicableStateChanged", unexpectedContentEvent);
- doc.defaultView.addEventListener("StyleSheetAdded", unexpectedContentEvent);
- doc.defaultView.addEventListener("StyleSheetRemoved", unexpectedContentEvent);
- doc.defaultView.addEventListener("StyleSheetApplicableStateChanged", unexpectedContentEvent);
-
- let link = doc.createElement("link");
- link.setAttribute("rel", "stylesheet");
- link.setAttribute("type", "text/css");
- link.setAttribute("href", testRoot + gStyleSheet);
-
- let sheetAdded =
- ContentTaskUtils.waitForEvent(this, "StyleSheetAdded", true);
- let stateChanged =
- ContentTaskUtils.waitForEvent(this, "StyleSheetApplicableStateChanged", true);
- doc.body.appendChild(link);
-
- let evt = yield sheetAdded;
- info("received dynamic style sheet event");
- is(evt.type, "StyleSheetAdded", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- ok(evt.stylesheet, "evt.stylesheet is defined");
- ok(evt.stylesheet.toString().includes("CSSStyleSheet"), "evt.stylesheet is a stylesheet");
- ok(evt.documentSheet, "style sheet is a document sheet");
-
- evt = yield stateChanged;
- info("received dynamic style sheet applicable state change event");
- is(evt.type, "StyleSheetApplicableStateChanged", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- is(evt.stylesheet, link.sheet, "evt.stylesheet has the right value");
- is(evt.applicable, true, "evt.applicable has the right value");
-
- stateChanged =
- ContentTaskUtils.waitForEvent(this, "StyleSheetApplicableStateChanged", true);
- link.disabled = true;
-
- evt = yield stateChanged;
- is(evt.type, "StyleSheetApplicableStateChanged", "evt.type has expected value");
- info("received dynamic style sheet applicable state change event after media=\"\" changed");
- is(evt.target, doc, "event targets correct document");
- is(evt.stylesheet, link.sheet, "evt.stylesheet has the right value");
- is(evt.applicable, false, "evt.applicable has the right value");
-
- let sheetRemoved =
- ContentTaskUtils.waitForEvent(this, "StyleSheetRemoved", true);
- doc.body.removeChild(link);
-
- evt = yield sheetRemoved;
- info("received dynamic style sheet removal");
- is(evt.type, "StyleSheetRemoved", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- ok(evt.stylesheet, "evt.stylesheet is defined");
- ok(evt.stylesheet.toString().includes("CSSStyleSheet"), "evt.stylesheet is a stylesheet");
- ok(evt.stylesheet.href.includes(gStyleSheet), "evt.stylesheet is the removed stylesheet");
-
- let ruleAdded =
- ContentTaskUtils.waitForEvent(this, "StyleRuleAdded", true);
- doc.querySelector("style").sheet.insertRule("*{color:black}", 0);
-
- evt = yield ruleAdded;
- info("received style rule added event");
- is(evt.type, "StyleRuleAdded", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- ok(evt.stylesheet, "evt.stylesheet is defined");
- ok(evt.stylesheet.toString().includes("CSSStyleSheet"), "evt.stylesheet is a stylesheet");
- ok(evt.rule, "evt.rule is defined");
- is(evt.rule.cssText, "* { color: black; }", "evt.rule.cssText has expected value");
-
- let ruleChanged =
- ContentTaskUtils.waitForEvent(this, "StyleRuleChanged", true);
- evt.rule.style.cssText = "color:green";
-
- evt = yield ruleChanged;
- ok(true, "received style rule changed event");
- is(evt.type, "StyleRuleChanged", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- ok(evt.stylesheet, "evt.stylesheet is defined");
- ok(evt.stylesheet.toString().includes("CSSStyleSheet"), "evt.stylesheet is a stylesheet");
- ok(evt.rule, "evt.rule is defined");
- is(evt.rule.cssText, "* { color: green; }", "evt.rule.cssText has expected value");
-
- let ruleRemoved =
- ContentTaskUtils.waitForEvent(this, "StyleRuleRemoved", true);
- evt.stylesheet.deleteRule(0);
-
- evt = yield ruleRemoved;
- info("received style rule removed event");
- is(evt.type, "StyleRuleRemoved", "evt.type has expected value");
- is(evt.target, doc, "event targets correct document");
- ok(evt.stylesheet, "evt.stylesheet is defined");
- ok(evt.stylesheet.toString().includes("CSSStyleSheet"), "evt.stylesheet is a stylesheet");
- ok(evt.rule, "evt.rule is defined");
-}
diff --git a/browser/base/content/test/general/browser_bug882977.js b/browser/base/content/test/general/browser_bug882977.js
deleted file mode 100644
index ed958e06b..000000000
--- a/browser/base/content/test/general/browser_bug882977.js
+++ /dev/null
@@ -1,29 +0,0 @@
-"use strict";
-
-/**
- * Tests that the identity-box shows the chromeUI styling
- * when viewing about:home in a new window.
- */
-add_task(function*() {
- let homepage = "about:home";
- yield SpecialPowers.pushPrefEnv({
- "set": [
- ["browser.startup.homepage", homepage],
- ["browser.startup.page", 1],
- ]
- });
-
- let win = OpenBrowserWindow();
- yield BrowserTestUtils.firstBrowserLoaded(win, false);
-
- let browser = win.gBrowser.selectedBrowser;
- is(browser.currentURI.spec, homepage, "Loaded the correct homepage");
- checkIdentityMode(win);
-
- yield BrowserTestUtils.closeWindow(win);
-});
-
-function checkIdentityMode(win) {
- let identityMode = win.document.getElementById("identity-box").className;
- is(identityMode, "chromeUI", "Identity state should be chromeUI for about:home in a new window");
-}
diff --git a/browser/base/content/test/general/browser_bug902156.js b/browser/base/content/test/general/browser_bug902156.js
deleted file mode 100644
index 74969ead4..000000000
--- a/browser/base/content/test/general/browser_bug902156.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Description of the Tests for
- * - Bug 902156: Persist "disable protection" option for Mixed Content Blocker
- *
- * 1. Navigate to the same domain via document.location
- * - Load a html page which has mixed content
- * - Control Center button to disable protection appears - we disable it
- * - Load a new page from the same origin using document.location
- * - Control Center button should not appear anymore!
- *
- * 2. Navigate to the same domain via simulateclick for a link on the page
- * - Load a html page which has mixed content
- * - Control Center button to disable protection appears - we disable it
- * - Load a new page from the same origin simulating a click
- * - Control Center button should not appear anymore!
- *
- * 3. Navigate to a differnet domain and show the content is still blocked
- * - Load a different html page which has mixed content
- * - Control Center button to disable protection should appear again because
- * we navigated away from html page where we disabled the protection.
- *
- * Note, for all tests we set gHttpTestRoot to use 'https'.
- */
-
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-
-// We alternate for even and odd test cases to simulate different hosts
-const gHttpTestRoot1 = "https://test1.example.com/browser/browser/base/content/test/general/";
-const gHttpTestRoot2 = "https://test2.example.com/browser/browser/base/content/test/general/";
-
-var origBlockActive;
-var gTestBrowser = null;
-
-registerCleanupFunction(function() {
- // Set preferences back to their original values
- Services.prefs.setBoolPref(PREF_ACTIVE, origBlockActive);
-});
-
-function cleanUpAfterTests() {
- gBrowser.removeCurrentTab();
- window.focus();
- finish();
-}
-
-// ------------------------ Test 1 ------------------------------
-
-function test1A() {
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test1B);
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- // Disable Mixed Content Protection for the page (and reload)
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
-}
-
-function test1B() {
- var expected = "Mixed Content Blocker disabled";
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test1C, "Error: Waited too long for mixed script to run in Test 1B");
-}
-
-function test1C() {
- var actual = content.document.getElementById('mctestdiv').innerHTML;
- is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 1C");
-
- // The Script loaded after we disabled the page, now we are going to reload the
- // page and see if our decision is persistent
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test1D);
-
- var url = gHttpTestRoot1 + "file_bug902156_2.html";
- gTestBrowser.loadURI(url);
-}
-
-function test1D() {
- // The Control Center button should appear but isMixedContentBlocked should be NOT true,
- // because our decision of disabling the mixed content blocker is persistent.
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
-
- var actual = content.document.getElementById('mctestdiv').innerHTML;
- is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 1D");
-
- // move on to Test 2
- test2();
-}
-
-// ------------------------ Test 2 ------------------------------
-
-function test2() {
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test2A);
- var url = gHttpTestRoot2 + "file_bug902156_2.html";
- gTestBrowser.loadURI(url);
-}
-
-function test2A() {
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test2B);
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- // Disable Mixed Content Protection for the page (and reload)
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
-}
-
-function test2B() {
- var expected = "Mixed Content Blocker disabled";
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test2C, "Error: Waited too long for mixed script to run in Test 2B");
-}
-
-function test2C() {
- var actual = content.document.getElementById('mctestdiv').innerHTML;
- is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 2C");
-
- // The Script loaded after we disabled the page, now we are going to reload the
- // page and see if our decision is persistent
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test2D);
-
- // reload the page using the provided link in the html file
- var mctestlink = content.document.getElementById("mctestlink");
- mctestlink.click();
-}
-
-function test2D() {
- // The Control Center button should appear but isMixedContentBlocked should be NOT true,
- // because our decision of disabling the mixed content blocker is persistent.
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
-
- var actual = content.document.getElementById('mctestdiv').innerHTML;
- is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 2D");
-
- // move on to Test 3
- test3();
-}
-
-// ------------------------ Test 3 ------------------------------
-
-function test3() {
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test3A);
- var url = gHttpTestRoot1 + "file_bug902156_3.html";
- gTestBrowser.loadURI(url);
-}
-
-function test3A() {
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- // We are done with tests, clean up
- cleanUpAfterTests();
-}
-
-// ------------------------------------------------------
-
-function test() {
- // Performing async calls, e.g. 'onload', we have to wait till all of them finished
- waitForExplicitFinish();
-
- // Store original preferences so we can restore settings after testing
- origBlockActive = Services.prefs.getBoolPref(PREF_ACTIVE);
-
- Services.prefs.setBoolPref(PREF_ACTIVE, true);
-
- // Not really sure what this is doing
- var newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
- newTab.linkedBrowser.stop()
-
- // Starting Test Number 1:
- BrowserTestUtils.browserLoaded(gTestBrowser).then(test1A);
- var url = gHttpTestRoot1 + "file_bug902156_1.html";
- gTestBrowser.loadURI(url);
-}
diff --git a/browser/base/content/test/general/browser_bug906190.js b/browser/base/content/test/general/browser_bug906190.js
deleted file mode 100644
index 613f50efd..000000000
--- a/browser/base/content/test/general/browser_bug906190.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the persistence of the "disable protection" option for Mixed Content
- * Blocker in child tabs (bug 906190).
- */
-
-requestLongerTimeout(2);
-
-// We use the different urls for testing same origin checks before allowing
-// mixed content on child tabs.
-const gHttpTestRoot1 = "https://test1.example.com/browser/browser/base/content/test/general/";
-const gHttpTestRoot2 = "https://test2.example.com/browser/browser/base/content/test/general/";
-
-/**
- * For all tests, we load the pages over HTTPS and test both:
- * - |CTRL+CLICK|
- * - |RIGHT CLICK -> OPEN LINK IN TAB|
- */
-function* doTest(parentTabSpec, childTabSpec, testTaskFn, waitForMetaRefresh) {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: parentTabSpec,
- }, function* (browser) {
- // As a sanity check, test that active content has been blocked as expected.
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: false, activeBlocked: true, passiveLoaded: false,
- });
-
- // Disable the Mixed Content Blocker for the page, which reloads it.
- let promiseReloaded = BrowserTestUtils.browserLoaded(browser);
- gIdentityHandler.disableMixedContentProtection();
- yield promiseReloaded;
-
- // Wait for the script in the page to update the contents of the test div.
- let testDiv = content.document.getElementById('mctestdiv');
- yield promiseWaitForCondition(
- () => testDiv.innerHTML == "Mixed Content Blocker disabled");
-
- // Add the link for the child tab to the page.
- let mainDiv = content.document.createElement("div");
- mainDiv.innerHTML =
- '<p><a id="linkToOpenInNewTab" href="' + childTabSpec + '">Link</a></p>';
- content.document.body.appendChild(mainDiv);
-
- // Execute the test in the child tabs with the two methods to open it.
- for (let openFn of [simulateCtrlClick, simulateContextMenuOpenInTab]) {
- let promiseTabLoaded = waitForSomeTabToLoad();
- openFn(browser);
- yield promiseTabLoaded;
- gBrowser.selectTabAtIndex(2);
-
- if (waitForMetaRefresh) {
- yield waitForSomeTabToLoad();
- }
-
- yield testTaskFn();
-
- gBrowser.removeCurrentTab();
- }
- });
-}
-
-function simulateCtrlClick(browser) {
- BrowserTestUtils.synthesizeMouseAtCenter("#linkToOpenInNewTab",
- { ctrlKey: true, metaKey: true },
- browser);
-}
-
-function simulateContextMenuOpenInTab(browser) {
- BrowserTestUtils.waitForEvent(document, "popupshown", false, event => {
- // These are operations that must be executed synchronously with the event.
- document.getElementById("context-openlinkintab").doCommand();
- event.target.hidePopup();
- return true;
- });
- BrowserTestUtils.synthesizeMouseAtCenter("#linkToOpenInNewTab",
- { type: "contextmenu", button: 2 },
- browser);
-}
-
-// Waits for a load event somewhere in the browser but ignore events coming
-// from <xul:browser>s without a tab assigned. That are most likely browsers
-// that preload the new tab page.
-function waitForSomeTabToLoad() {
- return new Promise(resolve => {
- gBrowser.addEventListener("load", function onLoad(event) {
- let tab = gBrowser._getTabForContentWindow(event.target.defaultView.top);
- if (tab) {
- gBrowser.removeEventListener("load", onLoad, true);
- resolve();
- }
- }, true);
- });
-}
-
-/**
- * Ensure the Mixed Content Blocker is enabled.
- */
-add_task(function* test_initialize() {
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({
- "set": [["security.mixed_content.block_active_content", true]],
- }, resolve));
-});
-
-/**
- * 1. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a subpage from the same origin in a new tab simulating a click
- * - Doorhanger should >> NOT << appear anymore!
- */
-add_task(function* test_same_origin() {
- yield doTest(gHttpTestRoot1 + "file_bug906190_1.html",
- gHttpTestRoot1 + "file_bug906190_2.html", function* () {
- // The doorhanger should appear but activeBlocked should be >> NOT << true,
- // because our decision of disabling the mixed content blocker is persistent
- // across tabs.
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: true, activeBlocked: false, passiveLoaded: false,
- });
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker disabled", "OK: Executed mixed script");
- });
-});
-
-/**
- * 2. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a new page from a different origin in a new tab simulating a click
- * - Doorhanger >> SHOULD << appear again!
- */
-add_task(function* test_different_origin() {
- yield doTest(gHttpTestRoot1 + "file_bug906190_2.html",
- gHttpTestRoot2 + "file_bug906190_2.html", function* () {
- // The doorhanger should appear and activeBlocked should be >> TRUE <<,
- // because our decision of disabling the mixed content blocker should only
- // persist if pages are from the same domain.
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: false, activeBlocked: true, passiveLoaded: false,
- });
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker enabled", "OK: Blocked mixed script");
- });
-});
-
-/**
- * 3. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a new page from the same origin in a new tab simulating a click
- * - Redirect to another page from the same origin using meta-refresh
- * - Doorhanger should >> NOT << appear again!
- */
-add_task(function* test_same_origin_metarefresh_same_origin() {
- // file_bug906190_3_4.html redirects to page test1.example.com/* using meta-refresh
- yield doTest(gHttpTestRoot1 + "file_bug906190_1.html",
- gHttpTestRoot1 + "file_bug906190_3_4.html", function* () {
- // The doorhanger should appear but activeBlocked should be >> NOT << true!
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: true, activeBlocked: false, passiveLoaded: false,
- });
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker disabled", "OK: Executed mixed script");
- }, true);
-});
-
-/**
- * 4. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a new page from the same origin in a new tab simulating a click
- * - Redirect to another page from a different origin using meta-refresh
- * - Doorhanger >> SHOULD << appear again!
- */
-add_task(function* test_same_origin_metarefresh_different_origin() {
- yield doTest(gHttpTestRoot2 + "file_bug906190_1.html",
- gHttpTestRoot2 + "file_bug906190_3_4.html", function* () {
- // The doorhanger should appear and activeBlocked should be >> TRUE <<.
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: false, activeBlocked: true, passiveLoaded: false,
- });
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker enabled", "OK: Blocked mixed script");
- }, true);
-});
-
-/**
- * 5. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a new page from the same origin in a new tab simulating a click
- * - Redirect to another page from the same origin using 302 redirect
- */
-add_task(function* test_same_origin_302redirect_same_origin() {
- // the sjs files returns a 302 redirect- note, same origins
- yield doTest(gHttpTestRoot1 + "file_bug906190_1.html",
- gHttpTestRoot1 + "file_bug906190.sjs", function* () {
- // The doorhanger should appear but activeBlocked should be >> NOT << true.
- // Currently it is >> TRUE << - see follow up bug 914860
- ok(!gIdentityHandler._identityBox.classList.contains("mixedActiveBlocked"),
- "OK: Mixed Content is NOT being blocked");
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker disabled", "OK: Executed mixed script");
- });
-});
-
-/**
- * 6. - Load a html page which has mixed content
- * - Doorhanger to disable protection appears - we disable it
- * - Load a new page from the same origin in a new tab simulating a click
- * - Redirect to another page from a different origin using 302 redirect
- */
-add_task(function* test_same_origin_302redirect_different_origin() {
- // the sjs files returns a 302 redirect - note, different origins
- yield doTest(gHttpTestRoot2 + "file_bug906190_1.html",
- gHttpTestRoot2 + "file_bug906190.sjs", function* () {
- // The doorhanger should appear and activeBlocked should be >> TRUE <<.
- yield assertMixedContentBlockingState(gBrowser, {
- activeLoaded: false, activeBlocked: true, passiveLoaded: false,
- });
-
- is(content.document.getElementById('mctestdiv').innerHTML,
- "Mixed Content Blocker enabled", "OK: Blocked mixed script");
- });
-});
-
-/**
- * 7. - Test memory leak issue on redirection error. See Bug 1269426.
- */
-add_task(function* test_bad_redirection() {
- // the sjs files returns a 302 redirect - note, different origins
- yield doTest(gHttpTestRoot2 + "file_bug906190_1.html",
- gHttpTestRoot2 + "file_bug906190.sjs?bad-redirection=1", function* () {
- // Nothing to do. Just see if memory leak is reported in the end.
- ok(true, "Nothing to do");
- });
-});
diff --git a/browser/base/content/test/general/browser_bug963945.js b/browser/base/content/test/general/browser_bug963945.js
deleted file mode 100644
index 4531964b0..000000000
--- a/browser/base/content/test/general/browser_bug963945.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* 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/. */
-
-/*
- * This test ensures the about:addons tab is only
- * opened one time when in private browsing.
- */
-
-add_task(function* test() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- let tab = win.gBrowser.selectedTab = win.gBrowser.addTab("about:addons");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield promiseWaitForFocus(win);
-
- EventUtils.synthesizeKey("a", { ctrlKey: true, shiftKey: true }, win);
-
- is(win.gBrowser.tabs.length, 2, "about:addons tab was re-focused.");
- is(win.gBrowser.currentURI.spec, "about:addons", "Addons tab was opened.");
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/base/content/test/general/browser_bug970746.js b/browser/base/content/test/general/browser_bug970746.js
deleted file mode 100644
index 623623e55..000000000
--- a/browser/base/content/test/general/browser_bug970746.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/* Make sure context menu includes option to search hyperlink text on search engine */
-
-add_task(function *() {
- const url = "http://mochi.test:8888/browser/browser/base/content/test/general/browser_bug970746.xhtml";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- const ellipsis = "\u2026";
-
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
-
- // Tests if the "Search <engine> for '<some terms>'" context menu item is shown for the
- // given query string of an element. Tests to make sure label includes the proper search terms.
- //
- // Each test:
- //
- // id: The id of the element to test.
- // isSelected: Flag to enable selecting (text highlight) the contents of the element
- // shouldBeShown: The display state of the menu item
- // expectedLabelContents: The menu item label should contain a portion of this string.
- // Will only be tested if shouldBeShown is true.
- let tests = [
- {
- id: "link",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "I'm a link!",
- },
- {
- id: "link",
- isSelected: false,
- shouldBeShown: true,
- expectedLabelContents: "I'm a link!",
- },
- {
- id: "longLink",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "I'm a really lo" + ellipsis,
- },
- {
- id: "longLink",
- isSelected: false,
- shouldBeShown: true,
- expectedLabelContents: "I'm a really lo" + ellipsis,
- },
- {
- id: "plainText",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "Right clicking " + ellipsis,
- },
- {
- id: "plainText",
- isSelected: false,
- shouldBeShown: false,
- },
- {
- id: "mixedContent",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "I'm some text, " + ellipsis,
- },
- {
- id: "mixedContent",
- isSelected: false,
- shouldBeShown: false,
- },
- {
- id: "partialLink",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "link selection",
- },
- {
- id: "partialLink",
- isSelected: false,
- shouldBeShown: true,
- expectedLabelContents: "A partial link " + ellipsis,
- },
- {
- id: "surrogatePair",
- isSelected: true,
- shouldBeShown: true,
- expectedLabelContents: "This character\uD83D\uDD25" + ellipsis,
- }
- ];
-
- for (let test of tests) {
- yield ContentTask.spawn(gBrowser.selectedBrowser,
- { selectElement: test.isSelected ? test.id : null },
- function* (arg) {
- let selection = content.getSelection();
- selection.removeAllRanges();
-
- if (arg.selectElement) {
- selection.selectAllChildren(content.document.getElementById(arg.selectElement));
- }
- });
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter("#" + test.id,
- { type: "contextmenu", button: 2}, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- let menuItem = document.getElementById("context-searchselect");
- is(menuItem.hidden, !test.shouldBeShown,
- "search context menu item is shown for '#" + test.id + "' and selected is '" + test.isSelected + "'");
-
- if (test.shouldBeShown) {
- ok(menuItem.label.includes(test.expectedLabelContents),
- "Menu item text '" + menuItem.label + "' contains the correct search terms '" + test.expectedLabelContents + "'");
- }
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
- }
-
- // cleanup
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_bug970746.xhtml b/browser/base/content/test/general/browser_bug970746.xhtml
deleted file mode 100644
index 9d78d7147..000000000
--- a/browser/base/content/test/general/browser_bug970746.xhtml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<html xmlns="http://www.w3.org/1999/xhtml">
- <body>
- <a href="http://mozilla.org" id="link">I'm a link!</a>
- <a href="http://mozilla.org" id="longLink">I'm a really long link and I should be truncated.</a>
-
- <span id="plainText">
- Right clicking me when I'm selected should show the menu item.
- </span>
- <span id="mixedContent">
- I'm some text, and <a href="http://mozilla.org">I'm a link!</a>
- </span>
-
- <a href="http://mozilla.org">A partial <span id="partialLink">link selection</span></a>
-
- <span id="surrogatePair">
- This character🔥 shouldn't be truncated.
- </span>
- </body>
-</html>
diff --git a/browser/base/content/test/general/browser_clipboard.js b/browser/base/content/test/general/browser_clipboard.js
deleted file mode 100644
index 33c6de52d..000000000
--- a/browser/base/content/test/general/browser_clipboard.js
+++ /dev/null
@@ -1,174 +0,0 @@
-// This test is used to check copy and paste in editable areas to ensure that non-text
-// types (html and images) are copied to and pasted from the clipboard properly.
-
-var testPage = "<body style='margin: 0'>" +
- " <img id='img' tabindex='1' src='http://example.org/browser/browser/base/content/test/general/moz.png'>" +
- " <div id='main' contenteditable='true'>Test <b>Bold</b> After Text</div>" +
- "</body>";
-
-add_task(function*() {
- let tab = gBrowser.addTab();
- let browser = gBrowser.getBrowserForTab(tab);
-
- gBrowser.selectedTab = tab;
-
- yield promiseTabLoadEvent(tab, "data:text/html," + escape(testPage));
- yield SimpleTest.promiseFocus(browser.contentWindowAsCPOW);
-
- const modifier = (navigator.platform.indexOf("Mac") >= 0) ?
- Components.interfaces.nsIDOMWindowUtils.MODIFIER_META :
- Components.interfaces.nsIDOMWindowUtils.MODIFIER_CONTROL;
-
- // On windows, HTML clipboard includes extra data.
- // The values are from widget/windows/nsDataObj.cpp.
- const htmlPrefix = (navigator.platform.indexOf("Win") >= 0) ? "<html><body>\n<!--StartFragment-->" : "";
- const htmlPostfix = (navigator.platform.indexOf("Win") >= 0) ? "<!--EndFragment-->\n</body>\n</html>" : "";
-
- yield ContentTask.spawn(browser, { modifier, htmlPrefix, htmlPostfix }, function* (arg) {
- var doc = content.document;
- var main = doc.getElementById("main");
- main.focus();
-
- const utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
- function sendKey(key) {
- if (utils.sendKeyEvent("keydown", key, 0, arg.modifier)) {
- utils.sendKeyEvent("keypress", key, key.charCodeAt(0), arg.modifier);
- }
- utils.sendKeyEvent("keyup", key, 0, arg.modifier);
- }
-
- // Select an area of the text.
- let selection = doc.getSelection();
- selection.modify("move", "left", "line");
- selection.modify("move", "right", "character");
- selection.modify("move", "right", "character");
- selection.modify("move", "right", "character");
- selection.modify("extend", "right", "word");
- selection.modify("extend", "right", "word");
-
- yield new Promise((resolve, reject) => {
- addEventListener("copy", function copyEvent(event) {
- removeEventListener("copy", copyEvent, true);
- // The data is empty as the selection is copied during the event default phase.
- Assert.equal(event.clipboardData.mozItemCount, 0, "Zero items on clipboard");
- resolve();
- }, true)
-
- sendKey("c");
- });
-
- selection.modify("move", "right", "line");
-
- yield new Promise((resolve, reject) => {
- addEventListener("paste", function copyEvent(event) {
- removeEventListener("paste", copyEvent, true);
- let clipboardData = event.clipboardData;
- Assert.equal(clipboardData.mozItemCount, 1, "One item on clipboard");
- Assert.equal(clipboardData.types.length, 2, "Two types on clipboard");
- Assert.equal(clipboardData.types[0], "text/html", "text/html on clipboard");
- Assert.equal(clipboardData.types[1], "text/plain", "text/plain on clipboard");
- Assert.equal(clipboardData.getData("text/html"), arg.htmlPrefix +
- "t <b>Bold</b>" + arg.htmlPostfix, "text/html value");
- Assert.equal(clipboardData.getData("text/plain"), "t Bold", "text/plain value");
- resolve();
- }, true)
- sendKey("v");
- });
-
- Assert.equal(main.innerHTML, "Test <b>Bold</b> After Textt <b>Bold</b>", "Copy and paste html");
-
- selection.modify("extend", "left", "word");
- selection.modify("extend", "left", "word");
- selection.modify("extend", "left", "character");
-
- yield new Promise((resolve, reject) => {
- addEventListener("cut", function copyEvent(event) {
- removeEventListener("cut", copyEvent, true);
- event.clipboardData.setData("text/plain", "Some text");
- event.clipboardData.setData("text/html", "<i>Italic</i> ");
- selection.deleteFromDocument();
- event.preventDefault();
- resolve();
- }, true)
- sendKey("x");
- });
-
- selection.modify("move", "left", "line");
-
- yield new Promise((resolve, reject) => {
- addEventListener("paste", function copyEvent(event) {
- removeEventListener("paste", copyEvent, true);
- let clipboardData = event.clipboardData;
- Assert.equal(clipboardData.mozItemCount, 1, "One item on clipboard 2");
- Assert.equal(clipboardData.types.length, 2, "Two types on clipboard 2");
- Assert.equal(clipboardData.types[0], "text/html", "text/html on clipboard 2");
- Assert.equal(clipboardData.types[1], "text/plain", "text/plain on clipboard 2");
- Assert.equal(clipboardData.getData("text/html"), arg.htmlPrefix +
- "<i>Italic</i> " + arg.htmlPostfix, "text/html value 2");
- Assert.equal(clipboardData.getData("text/plain"), "Some text", "text/plain value 2");
- resolve();
- }, true)
- sendKey("v");
- });
-
- Assert.equal(main.innerHTML, "<i>Italic</i> Test <b>Bold</b> After<b></b>",
- "Copy and paste html 2");
- });
-
- // Next, check that the Copy Image command works.
-
- // The context menu needs to be opened to properly initialize for the copy
- // image command to run.
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let contextMenuShown = promisePopupShown(contextMenu);
- BrowserTestUtils.synthesizeMouseAtCenter("#img", { type: "contextmenu", button: 2 }, gBrowser.selectedBrowser);
- yield contextMenuShown;
-
- document.getElementById("context-copyimage-contents").doCommand();
-
- contextMenu.hidePopup();
- yield promisePopupHidden(contextMenu);
-
- // Focus the content again
- yield SimpleTest.promiseFocus(browser.contentWindowAsCPOW);
-
- yield ContentTask.spawn(browser, { modifier, htmlPrefix, htmlPostfix }, function* (arg) {
- var doc = content.document;
- var main = doc.getElementById("main");
- main.focus();
-
- yield new Promise((resolve, reject) => {
- addEventListener("paste", function copyEvent(event) {
- removeEventListener("paste", copyEvent, true);
- let clipboardData = event.clipboardData;
-
- // DataTransfer doesn't support the image types yet, so only text/html
- // will be present.
- if (clipboardData.getData("text/html") !== arg.htmlPrefix +
- '<img id="img" tabindex="1" src="http://example.org/browser/browser/base/content/test/general/moz.png">' +
- arg.htmlPostfix) {
- reject('Clipboard Data did not contain an image, was ' + clipboardData.getData("text/html"));
- }
- resolve();
- }, true)
-
- const utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
-
- if (utils.sendKeyEvent("keydown", "v", 0, arg.modifier)) {
- utils.sendKeyEvent("keypress", "v", "v".charCodeAt(0), arg.modifier);
- }
- utils.sendKeyEvent("keyup", "v", 0, arg.modifier);
- });
-
- // The new content should now include an image.
- Assert.equal(main.innerHTML, '<i>Italic</i> <img id="img" tabindex="1" ' +
- 'src="http://example.org/browser/browser/base/content/test/general/moz.png">' +
- 'Test <b>Bold</b> After<b></b>', "Paste after copy image");
- });
-
- gBrowser.removeCurrentTab();
-});
-
diff --git a/browser/base/content/test/general/browser_clipboard_pastefile.js b/browser/base/content/test/general/browser_clipboard_pastefile.js
deleted file mode 100644
index fe87284f3..000000000
--- a/browser/base/content/test/general/browser_clipboard_pastefile.js
+++ /dev/null
@@ -1,62 +0,0 @@
-// This test is used to check that pasting files removes all non-file data from
-// event.clipboardData.
-
-add_task(function*() {
- var textbox = document.createElement("textbox");
- document.documentElement.appendChild(textbox);
-
- textbox.focus();
- textbox.value = "Text";
- textbox.select();
-
- yield new Promise((resolve, reject) => {
- textbox.addEventListener("copy", function copyEvent(event) {
- textbox.removeEventListener("copy", copyEvent, true);
- event.clipboardData.setData("text/plain", "Alternate");
- // For this test, it doesn't matter that the file isn't actually a file.
- event.clipboardData.setData("application/x-moz-file", "Sample");
- event.preventDefault();
- resolve();
- }, true)
-
- EventUtils.synthesizeKey("c", { accelKey: true });
- });
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "https://example.com/browser/browser/base/content/test/general/clipboard_pastefile.html");
- let browser = tab.linkedBrowser;
-
- yield ContentTask.spawn(browser, { }, function* (arg) {
- content.document.getElementById("input").focus();
- });
-
- yield BrowserTestUtils.synthesizeKey("v", { accelKey: true }, browser);
-
- let output = yield ContentTask.spawn(browser, { }, function* (arg) {
- return content.document.getElementById("output").textContent;
- });
- is (output, "Passed", "Paste file");
-
- textbox.focus();
-
- yield new Promise((resolve, reject) => {
- textbox.addEventListener("paste", function copyEvent(event) {
- textbox.removeEventListener("paste", copyEvent, true);
-
- let dt = event.clipboardData;
- is(dt.types.length, 3, "number of types");
- ok(dt.types.includes("text/plain"), "text/plain exists in types");
- ok(dt.mozTypesAt(0).contains("text/plain"), "text/plain exists in mozTypesAt");
- is(dt.getData("text/plain"), "Alternate", "text/plain returned in getData");
- is(dt.mozGetDataAt("text/plain", 0), "Alternate", "text/plain returned in mozGetDataAt");
-
- resolve();
- }, true);
-
- EventUtils.synthesizeKey("v", { accelKey: true });
- });
-
- document.documentElement.removeChild(textbox);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_contentAltClick.js b/browser/base/content/test/general/browser_contentAltClick.js
deleted file mode 100644
index 1a3b0fccc..000000000
--- a/browser/base/content/test/general/browser_contentAltClick.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* 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/. */
-
-/**
- * Test for Bug 1109146.
- * The tests opens a new tab and alt + clicks to download files
- * and confirms those files are on the download list.
- *
- * The difference between this and the test "browser_contentAreaClick.js" is that
- * the code path in e10s uses ContentClick.jsm instead of browser.js::contentAreaClick() util.
- */
-"use strict";
-
-XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
- "resource://gre/modules/Downloads.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-function setup() {
- gPrefService.setBoolPref("browser.altClickSave", true);
-
- let testPage =
- 'data:text/html,' +
- '<p><a id="commonlink" href="http://mochi.test/moz/">Common link</a></p>' +
- '<p><math id="mathxlink" xmlns="http://www.w3.org/1998/Math/MathML" xlink:type="simple" xlink:href="http://mochi.test/moz/"><mtext>MathML XLink</mtext></math></p>' +
- '<p><svg id="svgxlink" xmlns="http://www.w3.org/2000/svg" width="100px" height="50px" version="1.1"><a xlink:type="simple" xlink:href="http://mochi.test/moz/"><text transform="translate(10, 25)">SVG XLink</text></a></svg></p>';
-
- return BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
-}
-
-function* clean_up() {
- // Remove downloads.
- let downloadList = yield Downloads.getList(Downloads.ALL);
- let downloads = yield downloadList.getAll();
- for (let download of downloads) {
- yield downloadList.remove(download);
- yield download.finalize(true);
- }
- // Remove download history.
- yield PlacesTestUtils.clearHistory();
-
- gPrefService.clearUserPref("browser.altClickSave");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-}
-
-add_task(function* test_alt_click()
-{
- yield setup();
-
- let downloadList = yield Downloads.getList(Downloads.ALL);
- let downloads = [];
- let downloadView;
- // When 1 download has been attempted then resolve the promise.
- let finishedAllDownloads = new Promise( (resolve) => {
- downloadView = {
- onDownloadAdded: function (aDownload) {
- downloads.push(aDownload);
- resolve();
- },
- };
- });
- yield downloadList.addView(downloadView);
- yield BrowserTestUtils.synthesizeMouseAtCenter("#commonlink", {altKey: true}, gBrowser.selectedBrowser);
-
- // Wait for all downloads to be added to the download list.
- yield finishedAllDownloads;
- yield downloadList.removeView(downloadView);
-
- is(downloads.length, 1, "1 downloads");
- is(downloads[0].source.url, "http://mochi.test/moz/", "Downloaded #commonlink element");
-
- yield* clean_up();
-});
-
-add_task(function* test_alt_click_on_xlinks()
-{
- yield setup();
-
- let downloadList = yield Downloads.getList(Downloads.ALL);
- let downloads = [];
- let downloadView;
- // When all 2 downloads have been attempted then resolve the promise.
- let finishedAllDownloads = new Promise( (resolve) => {
- downloadView = {
- onDownloadAdded: function (aDownload) {
- downloads.push(aDownload);
- if (downloads.length == 2) {
- resolve();
- }
- },
- };
- });
- yield downloadList.addView(downloadView);
- yield BrowserTestUtils.synthesizeMouseAtCenter("#mathxlink", {altKey: true}, gBrowser.selectedBrowser);
- yield BrowserTestUtils.synthesizeMouseAtCenter("#svgxlink", {altKey: true}, gBrowser.selectedBrowser);
-
- // Wait for all downloads to be added to the download list.
- yield finishedAllDownloads;
- yield downloadList.removeView(downloadView);
-
- is(downloads.length, 2, "2 downloads");
- is(downloads[0].source.url, "http://mochi.test/moz/", "Downloaded #mathxlink element");
- is(downloads[1].source.url, "http://mochi.test/moz/", "Downloaded #svgxlink element");
-
- yield* clean_up();
-});
diff --git a/browser/base/content/test/general/browser_contentAreaClick.js b/browser/base/content/test/general/browser_contentAreaClick.js
deleted file mode 100644
index facdfb498..000000000
--- a/browser/base/content/test/general/browser_contentAreaClick.js
+++ /dev/null
@@ -1,307 +0,0 @@
-/* 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/. */
-
-/**
- * Test for bug 549340.
- * Test for browser.js::contentAreaClick() util.
- *
- * The test opens a new browser window, then replaces browser.js methods invoked
- * by contentAreaClick with a mock function that tracks which methods have been
- * called.
- * Each sub-test synthesizes a mouse click event on links injected in content,
- * the event is collected by a click handler that ensures that contentAreaClick
- * correctly prevent default events, and follows the correct code path.
- */
-
-var gTests = [
-
- {
- desc: "Simple left click",
- setup: function() {},
- clean: function() {},
- event: {},
- targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ],
- expectedInvokedMethods: [],
- preventDefault: false,
- },
-
- {
- desc: "Ctrl/Cmd left click",
- setup: function() {},
- clean: function() {},
- event: { ctrlKey: true,
- metaKey: true },
- targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ],
- expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ],
- preventDefault: true,
- },
-
- // The next test was once handling feedService.forcePreview(). Now it should
- // just be like Alt click.
- {
- desc: "Shift+Alt left click",
- setup: function() {
- gPrefService.setBoolPref("browser.altClickSave", true);
- },
- clean: function() {
- gPrefService.clearUserPref("browser.altClickSave");
- },
- event: { shiftKey: true,
- altKey: true },
- targets: [ "commonlink", "maplink" ],
- expectedInvokedMethods: [ "gatherTextUnder", "saveURL" ],
- preventDefault: true,
- },
-
- {
- desc: "Shift+Alt left click on XLinks",
- setup: function() {
- gPrefService.setBoolPref("browser.altClickSave", true);
- },
- clean: function() {
- gPrefService.clearUserPref("browser.altClickSave");
- },
- event: { shiftKey: true,
- altKey: true },
- targets: [ "mathxlink", "svgxlink"],
- expectedInvokedMethods: [ "saveURL" ],
- preventDefault: true,
- },
-
- {
- desc: "Shift click",
- setup: function() {},
- clean: function() {},
- event: { shiftKey: true },
- targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ],
- expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ],
- preventDefault: true,
- },
-
- {
- desc: "Alt click",
- setup: function() {
- gPrefService.setBoolPref("browser.altClickSave", true);
- },
- clean: function() {
- gPrefService.clearUserPref("browser.altClickSave");
- },
- event: { altKey: true },
- targets: [ "commonlink", "maplink" ],
- expectedInvokedMethods: [ "gatherTextUnder", "saveURL" ],
- preventDefault: true,
- },
-
- {
- desc: "Alt click on XLinks",
- setup: function() {
- gPrefService.setBoolPref("browser.altClickSave", true);
- },
- clean: function() {
- gPrefService.clearUserPref("browser.altClickSave");
- },
- event: { altKey: true },
- targets: [ "mathxlink", "svgxlink" ],
- expectedInvokedMethods: [ "saveURL" ],
- preventDefault: true,
- },
-
- {
- desc: "Panel click",
- setup: function() {},
- clean: function() {},
- event: {},
- targets: [ "panellink" ],
- expectedInvokedMethods: [ "urlSecurityCheck", "loadURI" ],
- preventDefault: true,
- },
-
- {
- desc: "Simple middle click opentab",
- setup: function() {},
- clean: function() {},
- event: { button: 1 },
- targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ],
- expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ],
- preventDefault: true,
- },
-
- {
- desc: "Simple middle click openwin",
- setup: function() {
- gPrefService.setBoolPref("browser.tabs.opentabfor.middleclick", false);
- },
- clean: function() {
- gPrefService.clearUserPref("browser.tabs.opentabfor.middleclick");
- },
- event: { button: 1 },
- targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ],
- expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ],
- preventDefault: true,
- },
-
- {
- desc: "Middle mouse paste",
- setup: function() {
- gPrefService.setBoolPref("middlemouse.contentLoadURL", true);
- gPrefService.setBoolPref("general.autoScroll", false);
- },
- clean: function() {
- gPrefService.clearUserPref("middlemouse.contentLoadURL");
- gPrefService.clearUserPref("general.autoScroll");
- },
- event: { button: 1 },
- targets: [ "emptylink" ],
- expectedInvokedMethods: [ "middleMousePaste" ],
- preventDefault: true,
- },
-
-];
-
-// Array of method names that will be replaced in the new window.
-var gReplacedMethods = [
- "middleMousePaste",
- "urlSecurityCheck",
- "loadURI",
- "gatherTextUnder",
- "saveURL",
- "openLinkIn",
- "getShortcutOrURIAndPostData",
-];
-
-// Reference to the new window.
-var gTestWin = null;
-
-// List of methods invoked by a specific call to contentAreaClick.
-var gInvokedMethods = [];
-
-// The test currently running.
-var gCurrentTest = null;
-
-function test() {
- waitForExplicitFinish();
-
- gTestWin = openDialog(location, "", "chrome,all,dialog=no", "about:blank");
- whenDelayedStartupFinished(gTestWin, function () {
- info("Browser window opened");
- waitForFocus(function() {
- info("Browser window focused");
- waitForFocus(function() {
- info("Setting up browser...");
- setupTestBrowserWindow();
- info("Running tests...");
- executeSoon(runNextTest);
- }, gTestWin.content, true);
- }, gTestWin);
- });
-}
-
-// Click handler used to steal click events.
-var gClickHandler = {
- handleEvent: function (event) {
- let linkId = event.target.id || event.target.localName;
- is(event.type, "click",
- gCurrentTest.desc + ":Handler received a click event on " + linkId);
-
- let isPanelClick = linkId == "panellink";
- gTestWin.contentAreaClick(event, isPanelClick);
- let prevent = event.defaultPrevented;
- is(prevent, gCurrentTest.preventDefault,
- gCurrentTest.desc + ": event.defaultPrevented is correct (" + prevent + ")")
-
- // Check that all required methods have been called.
- gCurrentTest.expectedInvokedMethods.forEach(function(aExpectedMethodName) {
- isnot(gInvokedMethods.indexOf(aExpectedMethodName), -1,
- gCurrentTest.desc + ":" + aExpectedMethodName + " was invoked");
- });
-
- if (gInvokedMethods.length != gCurrentTest.expectedInvokedMethods.length) {
- ok(false, "Wrong number of invoked methods");
- gInvokedMethods.forEach(method => info(method + " was invoked"));
- }
-
- event.preventDefault();
- event.stopPropagation();
-
- executeSoon(runNextTest);
- }
-}
-
-// Wraps around the methods' replacement mock function.
-function wrapperMethod(aInvokedMethods, aMethodName) {
- return function () {
- aInvokedMethods.push(aMethodName);
- // At least getShortcutOrURIAndPostData requires to return url
- return (aMethodName == "getShortcutOrURIAndPostData") ? arguments.url : arguments[0];
- }
-}
-
-function setupTestBrowserWindow() {
- // Steal click events and don't propagate them.
- gTestWin.addEventListener("click", gClickHandler, true);
-
- // Replace methods.
- gReplacedMethods.forEach(function (aMethodName) {
- gTestWin["old_" + aMethodName] = gTestWin[aMethodName];
- gTestWin[aMethodName] = wrapperMethod(gInvokedMethods, aMethodName);
- });
-
- // Inject links in content.
- let doc = gTestWin.content.document;
- let mainDiv = doc.createElement("div");
- mainDiv.innerHTML =
- '<p><a id="commonlink" href="http://mochi.test/moz/">Common link</a></p>' +
- '<p><a id="panellink" href="http://mochi.test/moz/">Panel link</a></p>' +
- '<p><a id="emptylink">Empty link</a></p>' +
- '<p><math id="mathxlink" xmlns="http://www.w3.org/1998/Math/MathML" xlink:type="simple" xlink:href="http://mochi.test/moz/"><mtext>MathML XLink</mtext></math></p>' +
- '<p><svg id="svgxlink" xmlns="http://www.w3.org/2000/svg" width="100px" height="50px" version="1.1"><a xlink:type="simple" xlink:href="http://mochi.test/moz/"><text transform="translate(10, 25)">SVG XLink</text></a></svg></p>' +
- '<p><map name="map" id="map"><area href="http://mochi.test/moz/" shape="rect" coords="0,0,128,128" /></map><img id="maplink" usemap="#map" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAIAAABMXPacAAAABGdBTUEAALGPC%2FxhBQAAAOtJREFUeF7t0IEAAAAAgKD9qRcphAoDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGDAgAEDBgwYMGBgwIAAAT0N51AAAAAASUVORK5CYII%3D"/></p>'
- doc.body.appendChild(mainDiv);
-}
-
-function runNextTest() {
- if (!gCurrentTest) {
- gCurrentTest = gTests.shift();
- gCurrentTest.setup();
- }
-
- if (gCurrentTest.targets.length == 0) {
- info(gCurrentTest.desc + ": cleaning up...")
- gCurrentTest.clean();
-
- if (gTests.length > 0) {
- gCurrentTest = gTests.shift();
- gCurrentTest.setup();
- }
- else {
- finishTest();
- return;
- }
- }
-
- // Move to next target.
- gInvokedMethods.length = 0;
- let target = gCurrentTest.targets.shift();
-
- info(gCurrentTest.desc + ": testing " + target);
-
- // Fire click event.
- let targetElt = gTestWin.content.document.getElementById(target);
- ok(targetElt, gCurrentTest.desc + ": target is valid (" + targetElt.id + ")");
- EventUtils.synthesizeMouseAtCenter(targetElt, gCurrentTest.event, gTestWin.content);
-}
-
-function finishTest() {
- info("Restoring browser...");
- gTestWin.removeEventListener("click", gClickHandler, true);
-
- // Restore original methods.
- gReplacedMethods.forEach(function (aMethodName) {
- gTestWin[aMethodName] = gTestWin["old_" + aMethodName];
- delete gTestWin["old_" + aMethodName];
- });
-
- gTestWin.close();
- finish();
-}
diff --git a/browser/base/content/test/general/browser_contentSearchUI.js b/browser/base/content/test/general/browser_contentSearchUI.js
deleted file mode 100644
index 003f80aff..000000000
--- a/browser/base/content/test/general/browser_contentSearchUI.js
+++ /dev/null
@@ -1,771 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const TEST_PAGE_BASENAME = "contentSearchUI.html";
-const TEST_CONTENT_SCRIPT_BASENAME = "contentSearchUI.js";
-const TEST_ENGINE_PREFIX = "browser_searchSuggestionEngine";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-const TEST_ENGINE_2_BASENAME = "searchSuggestionEngine2.xml";
-
-const TEST_MSG = "ContentSearchUIControllerTest";
-
-requestLongerTimeout(2);
-
-add_task(function* emptyInput() {
- yield setUp();
-
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_BACK_SPACE");
- checkState(state, "", [], -1);
-
- yield msg("reset");
-});
-
-add_task(function* blur() {
- yield setUp();
-
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("blur");
- checkState(state, "x", [], -1);
-
- yield msg("reset");
-});
-
-add_task(function* upDownKeys() {
- yield setUp();
-
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- // Cycle down the suggestions starting from no selection.
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "x", ["xfoo", "xbar"], 2);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "x", ["xfoo", "xbar"], 3);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- // Cycle up starting from no selection.
- state = yield msg("key", "VK_UP");
- checkState(state, "x", ["xfoo", "xbar"], 3);
-
- state = yield msg("key", "VK_UP");
- checkState(state, "x", ["xfoo", "xbar"], 2);
-
- state = yield msg("key", "VK_UP");
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- state = yield msg("key", "VK_UP");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0);
-
- state = yield msg("key", "VK_UP");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- yield msg("reset");
-});
-
-add_task(function* rightLeftKeys() {
- yield setUp();
-
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_LEFT");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_LEFT");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_RIGHT");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_RIGHT");
- checkState(state, "x", [], -1);
-
- state = yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0);
-
- // This should make the xfoo suggestion sticky. To make sure it sticks,
- // trigger suggestions again and cycle through them by pressing Down until
- // nothing is selected again.
- state = yield msg("key", "VK_RIGHT");
- checkState(state, "xfoo", [], -1);
-
- state = yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
- checkState(state, "xfoo", ["xfoofoo", "xfoobar"], -1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoofoo", ["xfoofoo", "xfoobar"], 0);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoobar", ["xfoofoo", "xfoobar"], 1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoofoo", "xfoobar"], 2);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoofoo", "xfoobar"], 3);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoofoo", "xfoobar"], -1);
-
- yield msg("reset");
-});
-
-add_task(function* tabKey() {
- yield setUp();
- yield msg("key", { key: "x", waitForSuggestions: true });
-
- let state = yield msg("key", "VK_TAB");
- checkState(state, "x", ["xfoo", "xbar"], 2);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "x", ["xfoo", "xbar"], 3);
-
- state = yield msg("key", { key: "VK_TAB", modifiers: { shiftKey: true }});
- checkState(state, "x", ["xfoo", "xbar"], 2);
-
- state = yield msg("key", { key: "VK_TAB", modifiers: { shiftKey: true }});
- checkState(state, "x", [], -1);
-
- yield setUp();
-
- yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
-
- for (let i = 0; i < 3; ++i) {
- state = yield msg("key", "VK_TAB");
- }
- checkState(state, "x", [], -1);
-
- yield setUp();
-
- yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0, 0);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xfoo", ["xfoo", "xbar"], 0, 1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("key", "VK_DOWN");
- checkState(state, "x", ["xfoo", "xbar"], 2);
-
- state = yield msg("key", "VK_UP");
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 0);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xbar", [], -1);
-
- yield msg("reset");
-});
-
-add_task(function* cycleSuggestions() {
- yield setUp();
- yield msg("key", { key: "x", waitForSuggestions: true });
-
- let cycle = Task.async(function* (aSelectedButtonIndex) {
- let modifiers = {
- shiftKey: true,
- accelKey: true,
- };
-
- let state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex);
- });
-
- yield cycle();
-
- // Repeat with a one-off selected.
- let state = yield msg("key", "VK_TAB");
- checkState(state, "x", ["xfoo", "xbar"], 2);
- yield cycle(0);
-
- // Repeat with the settings button selected.
- state = yield msg("key", "VK_TAB");
- checkState(state, "x", ["xfoo", "xbar"], 3);
- yield cycle(1);
-
- yield msg("reset");
-});
-
-add_task(function* cycleOneOffs() {
- yield setUp();
- yield msg("key", { key: "x", waitForSuggestions: true });
-
- yield msg("addDuplicateOneOff");
-
- let state = yield msg("key", "VK_DOWN");
- state = yield msg("key", "VK_DOWN");
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- let modifiers = {
- altKey: true,
- };
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 0);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 0);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1);
-
- // If the settings button is selected, pressing alt+up/down should select the
- // last/first one-off respectively (and deselect the settings button).
- yield msg("key", "VK_TAB");
- yield msg("key", "VK_TAB");
- state = yield msg("key", "VK_TAB"); // Settings button selected.
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 2);
-
- state = yield msg("key", { key: "VK_UP", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("key", "VK_TAB");
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 2);
-
- state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers });
- checkState(state, "xbar", ["xfoo", "xbar"], 1, 0);
-
- yield msg("removeLastOneOff");
- yield msg("reset");
-});
-
-add_task(function* mouse() {
- yield setUp();
-
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("mousemove", 0);
- checkState(state, "x", ["xfoo", "xbar"], 0);
-
- state = yield msg("mousemove", 1);
- checkState(state, "x", ["xfoo", "xbar"], 1);
-
- state = yield msg("mousemove", 2);
- checkState(state, "x", ["xfoo", "xbar"], 1, 0);
-
- state = yield msg("mousemove", 3);
- checkState(state, "x", ["xfoo", "xbar"], 1, 1);
-
- state = yield msg("mousemove", -1);
- checkState(state, "x", ["xfoo", "xbar"], 1);
-
- yield msg("reset");
- yield setUp();
-
- state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- state = yield msg("mousemove", 0);
- checkState(state, "x", ["xfoo", "xbar"], 0);
-
- state = yield msg("mousemove", 2);
- checkState(state, "x", ["xfoo", "xbar"], 0, 0);
-
- state = yield msg("mousemove", -1);
- checkState(state, "x", ["xfoo", "xbar"], 0);
-
- yield msg("reset");
-});
-
-add_task(function* formHistory() {
- yield setUp();
-
- // Type an X and add it to form history.
- let state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
- // Wait for Satchel to say it's been added to form history.
- let deferred = Promise.defer();
- Services.obs.addObserver(function onAdd(subj, topic, data) {
- if (data == "formhistory-add") {
- Services.obs.removeObserver(onAdd, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
- yield Promise.all([msg("addInputValueToFormHistory"), deferred.promise]);
-
- // Reset the input.
- state = yield msg("reset");
- checkState(state, "", [], -1);
-
- // Type an X again. The form history entry should appear.
- state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", [{ str: "x", type: "formHistory" }, "xfoo", "xbar"],
- -1);
-
- // Select the form history entry and delete it.
- state = yield msg("key", "VK_DOWN");
- checkState(state, "x", [{ str: "x", type: "formHistory" }, "xfoo", "xbar"],
- 0);
-
- // Wait for Satchel.
- deferred = Promise.defer();
- Services.obs.addObserver(function onRemove(subj, topic, data) {
- if (data == "formhistory-remove") {
- Services.obs.removeObserver(onRemove, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
-
- state = yield msg("key", "VK_DELETE");
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- yield deferred.promise;
-
- // Reset the input.
- state = yield msg("reset");
- checkState(state, "", [], -1);
-
- // Type an X again. The form history entry should still be gone.
- state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- yield msg("reset");
-});
-
-add_task(function* cycleEngines() {
- yield setUp();
- yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
-
- let promiseEngineChange = function(newEngineName) {
- let deferred = Promise.defer();
- Services.obs.addObserver(function resolver(subj, topic, data) {
- if (data != "engine-current") {
- return;
- }
- SimpleTest.is(subj.name, newEngineName, "Engine cycled correctly");
- Services.obs.removeObserver(resolver, "browser-search-engine-modified");
- deferred.resolve();
- }, "browser-search-engine-modified", false);
- return deferred.promise;
- }
-
- let p = promiseEngineChange(TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME);
- yield msg("key", { key: "VK_DOWN", modifiers: { accelKey: true }});
- yield p;
-
- p = promiseEngineChange(TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME);
- yield msg("key", { key: "VK_UP", modifiers: { accelKey: true }});
- yield p;
-
- yield msg("reset");
-});
-
-add_task(function* search() {
- yield setUp();
-
- let modifiers = {};
- ["altKey", "ctrlKey", "metaKey", "shiftKey"].forEach(k => modifiers[k] = true);
-
- // Test typing a query and pressing enter.
- let p = msg("waitForSearch");
- yield msg("key", { key: "x", waitForSuggestions: true });
- yield msg("key", { key: "VK_RETURN", modifiers: modifiers });
- let mesg = yield p;
- let eventData = {
- engineName: TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME,
- searchString: "x",
- healthReportKey: "test",
- searchPurpose: "test",
- originalEvent: modifiers,
- };
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test typing a query, then selecting a suggestion and pressing enter.
- p = msg("waitForSearch");
- yield msg("key", { key: "x", waitForSuggestions: true });
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_DOWN");
- yield msg("key", { key: "VK_RETURN", modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "xfoo";
- eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME;
- eventData.selection = {
- index: 1,
- kind: "key",
- }
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test typing a query, then selecting a one-off button and pressing enter.
- p = msg("waitForSearch");
- yield msg("key", { key: "x", waitForSuggestions: true });
- yield msg("key", "VK_UP");
- yield msg("key", "VK_UP");
- yield msg("key", { key: "VK_RETURN", modifiers: modifiers });
- mesg = yield p;
- delete eventData.selection;
- eventData.searchString = "x";
- eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME;
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test typing a query and clicking the search engine header.
- p = msg("waitForSearch");
- modifiers.button = 0;
- yield msg("key", { key: "x", waitForSuggestions: true });
- yield msg("mousemove", -1);
- yield msg("click", { eltIdx: -1, modifiers: modifiers });
- mesg = yield p;
- eventData.originalEvent = modifiers;
- eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME;
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test typing a query and then clicking a suggestion.
- yield msg("key", { key: "x", waitForSuggestions: true });
- p = msg("waitForSearch");
- yield msg("mousemove", 1);
- yield msg("click", { eltIdx: 1, modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "xfoo";
- eventData.selection = {
- index: 1,
- kind: "mouse",
- };
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test typing a query and then clicking a one-off button.
- yield msg("key", { key: "x", waitForSuggestions: true });
- p = msg("waitForSearch");
- yield msg("mousemove", 3);
- yield msg("click", { eltIdx: 3, modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "x";
- eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME;
- delete eventData.selection;
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test selecting a suggestion, then clicking a one-off without deselecting the
- // suggestion.
- yield msg("key", { key: "x", waitForSuggestions: true });
- p = msg("waitForSearch");
- yield msg("mousemove", 1);
- yield msg("mousemove", 3);
- yield msg("click", { eltIdx: 3, modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "xfoo"
- eventData.selection = {
- index: 1,
- kind: "mouse",
- };
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Same as above, but with the keyboard.
- delete modifiers.button;
- yield msg("key", { key: "x", waitForSuggestions: true });
- p = msg("waitForSearch");
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_TAB");
- yield msg("key", { key: "VK_RETURN", modifiers: modifiers });
- mesg = yield p;
- eventData.selection = {
- index: 1,
- kind: "key",
- };
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Test searching when using IME composition.
- let state = yield msg("startComposition", { data: "" });
- checkState(state, "", [], -1);
- state = yield msg("changeComposition", { data: "x", waitForSuggestions: true });
- checkState(state, "x", [{ str: "x", type: "formHistory" },
- { str: "xfoo", type: "formHistory" }, "xbar"], -1);
- yield msg("commitComposition");
- delete modifiers.button;
- p = msg("waitForSearch");
- yield msg("key", { key: "VK_RETURN", modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "x"
- eventData.originalEvent = modifiers;
- eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME;
- delete eventData.selection;
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- state = yield msg("startComposition", { data: "" });
- checkState(state, "", [], -1);
- state = yield msg("changeComposition", { data: "x", waitForSuggestions: true });
- checkState(state, "x", [{ str: "x", type: "formHistory" },
- { str: "xfoo", type: "formHistory" }, "xbar"], -1);
-
- // Mouse over the first suggestion.
- state = yield msg("mousemove", 0);
- checkState(state, "x", [{ str: "x", type: "formHistory" },
- { str: "xfoo", type: "formHistory" }, "xbar"], 0);
-
- // Mouse over the second suggestion.
- state = yield msg("mousemove", 1);
- checkState(state, "x", [{ str: "x", type: "formHistory" },
- { str: "xfoo", type: "formHistory" }, "xbar"], 1);
-
- modifiers.button = 0;
- p = msg("waitForSearch");
- yield msg("click", { eltIdx: 1, modifiers: modifiers });
- mesg = yield p;
- eventData.searchString = "xfoo";
- eventData.originalEvent = modifiers;
- eventData.selection = {
- index: 1,
- kind: "mouse",
- };
- SimpleTest.isDeeply(eventData, mesg, "Search event data");
-
- yield promiseTab();
- yield setUp();
-
- // Remove form history entries.
- // Wait for Satchel.
- let deferred = Promise.defer();
- let historyCount = 2;
- Services.obs.addObserver(function onRemove(subj, topic, data) {
- if (data == "formhistory-remove") {
- if (--historyCount) {
- return;
- }
- Services.obs.removeObserver(onRemove, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
-
- yield msg("key", { key: "x", waitForSuggestions: true });
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_DELETE");
- yield msg("key", "VK_DOWN");
- yield msg("key", "VK_DELETE");
- yield deferred.promise;
-
- yield msg("reset");
- state = yield msg("key", { key: "x", waitForSuggestions: true });
- checkState(state, "x", ["xfoo", "xbar"], -1);
-
- yield promiseTab();
- yield setUp();
- yield msg("reset");
-});
-
-add_task(function* settings() {
- yield setUp();
- yield msg("key", { key: "VK_DOWN", waitForSuggestions: true });
- yield msg("key", "VK_UP");
- let p = msg("waitForSearchSettings");
- yield msg("key", "VK_RETURN");
- yield p;
-
- yield msg("reset");
-});
-
-var gDidInitialSetUp = false;
-
-function setUp(aNoEngine) {
- return Task.spawn(function* () {
- if (!gDidInitialSetUp) {
- Cu.import("resource:///modules/ContentSearch.jsm");
- let originalOnMessageSearch = ContentSearch._onMessageSearch;
- let originalOnMessageManageEngines = ContentSearch._onMessageManageEngines;
- ContentSearch._onMessageSearch = () => {};
- ContentSearch._onMessageManageEngines = () => {};
- registerCleanupFunction(() => {
- ContentSearch._onMessageSearch = originalOnMessageSearch;
- ContentSearch._onMessageManageEngines = originalOnMessageManageEngines;
- });
- yield setUpEngines();
- yield promiseTab();
- gDidInitialSetUp = true;
- }
- yield msg("focus");
- });
-}
-
-function msg(type, data=null) {
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: type,
- data: data,
- });
- let deferred = Promise.defer();
- gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) {
- if (msgObj.data.type != type) {
- return;
- }
- gMsgMan.removeMessageListener(TEST_MSG, onMsg);
- deferred.resolve(msgObj.data.data);
- });
- return deferred.promise;
-}
-
-function checkState(actualState, expectedInputVal, expectedSuggestions,
- expectedSelectedIdx, expectedSelectedButtonIdx) {
- expectedSuggestions = expectedSuggestions.map(sugg => {
- return typeof(sugg) == "object" ? sugg : {
- str: sugg,
- type: "remote",
- };
- });
-
- if (expectedSelectedIdx == -1 && expectedSelectedButtonIdx != undefined) {
- expectedSelectedIdx = expectedSuggestions.length + expectedSelectedButtonIdx;
- }
-
- let expectedState = {
- selectedIndex: expectedSelectedIdx,
- numSuggestions: expectedSuggestions.length,
- suggestionAtIndex: expectedSuggestions.map(s => s.str),
- isFormHistorySuggestionAtIndex:
- expectedSuggestions.map(s => s.type == "formHistory"),
-
- tableHidden: expectedSuggestions.length == 0,
-
- inputValue: expectedInputVal,
- ariaExpanded: expectedSuggestions.length == 0 ? "false" : "true",
- };
- if (expectedSelectedButtonIdx != undefined) {
- expectedState.selectedButtonIndex = expectedSelectedButtonIdx;
- }
- else if (expectedSelectedIdx < expectedSuggestions.length) {
- expectedState.selectedButtonIndex = -1;
- }
- else {
- expectedState.selectedButtonIndex = expectedSelectedIdx - expectedSuggestions.length;
- }
-
- SimpleTest.isDeeply(actualState, expectedState, "State");
-}
-
-var gMsgMan;
-
-function* promiseTab() {
- let deferred = Promise.defer();
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- registerCleanupFunction(() => BrowserTestUtils.removeTab(tab));
- let pageURL = getRootDirectory(gTestPath) + TEST_PAGE_BASENAME;
- tab.linkedBrowser.addEventListener("load", function onLoad(event) {
- tab.linkedBrowser.removeEventListener("load", onLoad, true);
- gMsgMan = tab.linkedBrowser.messageManager;
- gMsgMan.sendAsyncMessage("ContentSearch", {
- type: "AddToWhitelist",
- data: [pageURL],
- });
- promiseMsg("ContentSearch", "AddToWhitelistAck", gMsgMan).then(() => {
- let jsURL = getRootDirectory(gTestPath) + TEST_CONTENT_SCRIPT_BASENAME;
- gMsgMan.loadFrameScript(jsURL, false);
- deferred.resolve(msg("init"));
- });
- }, true, true);
- openUILinkIn(pageURL, "current");
- return deferred.promise;
-}
-
-function promiseMsg(name, type, msgMan) {
- let deferred = Promise.defer();
- info("Waiting for " + name + " message " + type + "...");
- msgMan.addMessageListener(name, function onMsg(msgObj) {
- info("Received " + name + " message " + msgObj.data.type + "\n");
- if (msgObj.data.type == type) {
- msgMan.removeMessageListener(name, onMsg);
- deferred.resolve(msgObj);
- }
- });
- return deferred.promise;
-}
-
-function setUpEngines() {
- return Task.spawn(function* () {
- info("Removing default search engines");
- let currentEngineName = Services.search.currentEngine.name;
- let currentEngines = Services.search.getVisibleEngines();
- info("Adding test search engines");
- let engine1 = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- yield promiseNewSearchEngine(TEST_ENGINE_2_BASENAME);
- Services.search.currentEngine = engine1;
- for (let engine of currentEngines) {
- Services.search.removeEngine(engine);
- }
- registerCleanupFunction(() => {
- Services.search.restoreDefaultEngines();
- Services.search.currentEngine = Services.search.getEngineByName(currentEngineName);
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_contextmenu.js b/browser/base/content/test/general/browser_contextmenu.js
deleted file mode 100644
index 3e0135848..000000000
--- a/browser/base/content/test/general/browser_contextmenu.js
+++ /dev/null
@@ -1,996 +0,0 @@
-"use strict";
-
-let contextMenu;
-let LOGIN_FILL_ITEMS = [
- "---", null,
- "fill-login", null,
- [
- "fill-login-no-logins", false,
- "---", null,
- "fill-login-saved-passwords", true
- ], null,
-];
-let hasPocket = Services.prefs.getBoolPref("extensions.pocket.enabled");
-let hasContainers = Services.prefs.getBoolPref("privacy.userContext.enabled");
-
-const example_base = "http://example.com/browser/browser/base/content/test/general/";
-const chrome_base = "chrome://mochitests/content/browser/browser/base/content/test/general/";
-
-Services.scriptloader.loadSubScript(chrome_base + "contextmenu_common.js", this);
-
-// Below are test cases for XUL element
-add_task(function* test_xul_text_link_label() {
- let url = chrome_base + "subtst_contextmenu_xul.xul";
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- yield test_contextmenu("#test-xul-text-link-label",
- ["context-openlinkintab", true,
- ...(hasContainers ? ["context-openlinkinusercontext-menu", true] : []),
- // We need a blank entry here because the containers submenu is
- // dynamically generated with no ids.
- ...(hasContainers ? ["", null] : []),
- "context-openlink", true,
- "context-openlinkprivate", true,
- "---", null,
- "context-bookmarklink", true,
- "context-savelink", true,
- ...(hasPocket ? ["context-savelinktopocket", true] : []),
- "context-copylink", true,
- "context-searchselect", true
- ]
- );
-
- // Clean up so won't affect HTML element test cases
- lastElementSelector = null;
- gBrowser.removeCurrentTab();
-});
-
-// Below are test cases for HTML element
-
-add_task(function* test_setup_html() {
- let url = example_base + "subtst_contextmenu.html";
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let videoIframe = doc.querySelector("#test-video-in-iframe");
- let video = videoIframe.contentDocument.querySelector("video");
- let awaitPause = ContentTaskUtils.waitForEvent(video, "pause");
- video.pause();
- yield awaitPause;
-
- let audioIframe = doc.querySelector("#test-audio-in-iframe");
- // media documents always use a <video> tag.
- let audio = audioIframe.contentDocument.querySelector("video");
- awaitPause = ContentTaskUtils.waitForEvent(audio, "pause");
- audio.pause();
- yield awaitPause;
- });
-});
-
-let plainTextItems;
-add_task(function* test_plaintext() {
- plainTextItems = ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ];
- yield test_contextmenu("#test-text", plainTextItems);
-});
-
-add_task(function* test_link() {
- yield test_contextmenu("#test-link",
- ["context-openlinkintab", true,
- ...(hasContainers ? ["context-openlinkinusercontext-menu", true] : []),
- // We need a blank entry here because the containers submenu is
- // dynamically generated with no ids.
- ...(hasContainers ? ["", null] : []),
- "context-openlink", true,
- "context-openlinkprivate", true,
- "---", null,
- "context-bookmarklink", true,
- "context-savelink", true,
- ...(hasPocket ? ["context-savelinktopocket", true] : []),
- "context-copylink", true,
- "context-searchselect", true
- ]
- );
-});
-
-add_task(function* test_mailto() {
- yield test_contextmenu("#test-mailto",
- ["context-copyemail", true,
- "context-searchselect", true
- ]
- );
-});
-
-add_task(function* test_image() {
- yield test_contextmenu("#test-image",
- ["context-viewimage", true,
- "context-copyimage-contents", true,
- "context-copyimage", true,
- "---", null,
- "context-saveimage", true,
- "context-sendimage", true,
- "context-setDesktopBackground", true,
- "context-viewimageinfo", true
- ]
- );
-});
-
-add_task(function* test_canvas() {
- yield test_contextmenu("#test-canvas",
- ["context-viewimage", true,
- "context-saveimage", true,
- "context-selectall", true
- ]
- );
-});
-
-add_task(function* test_video_ok() {
- yield test_contextmenu("#test-video-ok",
- ["context-media-play", true,
- "context-media-mute", true,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", true,
- "context-media-playbackrate-100x", true,
- "context-media-playbackrate-125x", true,
- "context-media-playbackrate-150x", true,
- "context-media-playbackrate-200x", true], null,
- "context-media-loop", true,
- "context-media-hidecontrols", true,
- "context-video-fullscreen", true,
- "---", null,
- "context-viewvideo", true,
- "context-copyvideourl", true,
- "---", null,
- "context-savevideo", true,
- "context-video-saveimage", true,
- "context-sendvideo", true,
- "context-castvideo", null,
- [], null
- ]
- );
-});
-
-add_task(function* test_audio_in_video() {
- yield test_contextmenu("#test-audio-in-video",
- ["context-media-play", true,
- "context-media-mute", true,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", true,
- "context-media-playbackrate-100x", true,
- "context-media-playbackrate-125x", true,
- "context-media-playbackrate-150x", true,
- "context-media-playbackrate-200x", true], null,
- "context-media-loop", true,
- "context-media-showcontrols", true,
- "---", null,
- "context-copyaudiourl", true,
- "---", null,
- "context-saveaudio", true,
- "context-sendaudio", true
- ]
- );
-});
-
-add_task(function* test_video_bad() {
- yield test_contextmenu("#test-video-bad",
- ["context-media-play", false,
- "context-media-mute", false,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", false,
- "context-media-playbackrate-100x", false,
- "context-media-playbackrate-125x", false,
- "context-media-playbackrate-150x", false,
- "context-media-playbackrate-200x", false], null,
- "context-media-loop", true,
- "context-media-hidecontrols", false,
- "context-video-fullscreen", false,
- "---", null,
- "context-viewvideo", true,
- "context-copyvideourl", true,
- "---", null,
- "context-savevideo", true,
- "context-video-saveimage", false,
- "context-sendvideo", true,
- "context-castvideo", null,
- [], null
- ]
- );
-});
-
-add_task(function* test_video_bad2() {
- yield test_contextmenu("#test-video-bad2",
- ["context-media-play", false,
- "context-media-mute", false,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", false,
- "context-media-playbackrate-100x", false,
- "context-media-playbackrate-125x", false,
- "context-media-playbackrate-150x", false,
- "context-media-playbackrate-200x", false], null,
- "context-media-loop", true,
- "context-media-hidecontrols", false,
- "context-video-fullscreen", false,
- "---", null,
- "context-viewvideo", false,
- "context-copyvideourl", false,
- "---", null,
- "context-savevideo", false,
- "context-video-saveimage", false,
- "context-sendvideo", false,
- "context-castvideo", null,
- [], null
- ]
- );
-});
-
-add_task(function* test_iframe() {
- yield test_contextmenu("#test-iframe",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "frame", null,
- ["context-showonlythisframe", true,
- "context-openframeintab", true,
- "context-openframe", true,
- "---", null,
- "context-reloadframe", true,
- "---", null,
- "context-bookmarkframe", true,
- "context-saveframe", true,
- "---", null,
- "context-printframe", true,
- "---", null,
- "context-viewframesource", true,
- "context-viewframeinfo", true], null,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ]
- );
-});
-
-add_task(function* test_video_in_iframe() {
- yield test_contextmenu("#test-video-in-iframe",
- ["context-media-play", true,
- "context-media-mute", true,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", true,
- "context-media-playbackrate-100x", true,
- "context-media-playbackrate-125x", true,
- "context-media-playbackrate-150x", true,
- "context-media-playbackrate-200x", true], null,
- "context-media-loop", true,
- "context-media-hidecontrols", true,
- "context-video-fullscreen", true,
- "---", null,
- "context-viewvideo", true,
- "context-copyvideourl", true,
- "---", null,
- "context-savevideo", true,
- "context-video-saveimage", true,
- "context-sendvideo", true,
- "context-castvideo", null,
- [], null,
- "frame", null,
- ["context-showonlythisframe", true,
- "context-openframeintab", true,
- "context-openframe", true,
- "---", null,
- "context-reloadframe", true,
- "---", null,
- "context-bookmarkframe", true,
- "context-saveframe", true,
- "---", null,
- "context-printframe", true,
- "---", null,
- "context-viewframeinfo", true], null]
- );
-});
-
-add_task(function* test_audio_in_iframe() {
- yield test_contextmenu("#test-audio-in-iframe",
- ["context-media-play", true,
- "context-media-mute", true,
- "context-media-playbackrate", null,
- ["context-media-playbackrate-050x", true,
- "context-media-playbackrate-100x", true,
- "context-media-playbackrate-125x", true,
- "context-media-playbackrate-150x", true,
- "context-media-playbackrate-200x", true], null,
- "context-media-loop", true,
- "---", null,
- "context-copyaudiourl", true,
- "---", null,
- "context-saveaudio", true,
- "context-sendaudio", true,
- "frame", null,
- ["context-showonlythisframe", true,
- "context-openframeintab", true,
- "context-openframe", true,
- "---", null,
- "context-reloadframe", true,
- "---", null,
- "context-bookmarkframe", true,
- "context-saveframe", true,
- "---", null,
- "context-printframe", true,
- "---", null,
- "context-viewframeinfo", true], null]
- );
-});
-
-add_task(function* test_image_in_iframe() {
- yield test_contextmenu("#test-image-in-iframe",
- ["context-viewimage", true,
- "context-copyimage-contents", true,
- "context-copyimage", true,
- "---", null,
- "context-saveimage", true,
- "context-sendimage", true,
- "context-setDesktopBackground", true,
- "context-viewimageinfo", true,
- "frame", null,
- ["context-showonlythisframe", true,
- "context-openframeintab", true,
- "context-openframe", true,
- "---", null,
- "context-reloadframe", true,
- "---", null,
- "context-bookmarkframe", true,
- "context-saveframe", true,
- "---", null,
- "context-printframe", true,
- "---", null,
- "context-viewframeinfo", true], null]
- );
-});
-
-add_task(function* test_textarea() {
- // Disabled since this is seeing spell-check-enabled
- // instead of spell-add-dictionaries-main
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-textarea",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null,
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-add-dictionaries-main", true,
- ],
- {
- skipFocusChange: true,
- }
- );
- */
-});
-
-add_task(function* test_textarea_spellcheck() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-textarea",
- ["*chubbiness", true, // spelling suggestion
- "spell-add-to-dictionary", true,
- "---", null,
- "context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null
- ],
- {
- waitForSpellCheck: true,
- offsetX: 6,
- offsetY: 6,
- postCheckContextMenuFn() {
- document.getElementById("spell-add-to-dictionary").doCommand();
- }
- }
- );
- */
-});
-
-add_task(function* test_plaintext2() {
- yield test_contextmenu("#test-text", plainTextItems);
-});
-
-add_task(function* test_undo_add_to_dictionary() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-textarea",
- ["spell-undo-add-to-dictionary", true,
- "---", null,
- "context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null
- ],
- {
- waitForSpellCheck: true,
- postCheckContextMenuFn() {
- document.getElementById("spell-undo-add-to-dictionary")
- .doCommand();
- }
- }
- );
- */
-});
-
-add_task(function* test_contenteditable() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-contenteditable",
- ["spell-no-suggestions", false,
- "spell-add-to-dictionary", true,
- "---", null,
- "context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null
- ],
- {waitForSpellCheck: true}
- );
- */
-});
-
-add_task(function* test_copylinkcommand() {
- yield test_contextmenu("#test-link", null, {
- postCheckContextMenuFn: function*() {
- document.commandDispatcher
- .getControllerForCommand("cmd_copyLink")
- .doCommand("cmd_copyLink");
-
- // The easiest way to check the clipboard is to paste the contents
- // into a textbox.
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let input = doc.getElementById("test-input");
- input.focus();
- input.value = "";
- });
- document.commandDispatcher
- .getControllerForCommand("cmd_paste")
- .doCommand("cmd_paste");
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let input = doc.getElementById("test-input");
- Assert.equal(input.value, "http://mozilla.com/", "paste for command cmd_paste");
- });
- }
- });
-});
-
-add_task(function* test_pagemenu() {
- yield test_contextmenu("#test-pagemenu",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "+Plain item", {type: "", icon: "", checked: false, disabled: false},
- "+Disabled item", {type: "", icon: "", checked: false, disabled: true},
- "+Item w/ textContent", {type: "", icon: "", checked: false, disabled: false},
- "---", null,
- "+Checkbox", {type: "checkbox", icon: "", checked: true, disabled: false},
- "---", null,
- "+Radio1", {type: "checkbox", icon: "", checked: true, disabled: false},
- "+Radio2", {type: "checkbox", icon: "", checked: false, disabled: false},
- "+Radio3", {type: "checkbox", icon: "", checked: false, disabled: false},
- "---", null,
- "+Item w/ icon", {type: "", icon: "favicon.ico", checked: false, disabled: false},
- "+Item w/ bad icon", {type: "", icon: "", checked: false, disabled: false},
- "---", null,
- "generated-submenu-1", true,
- ["+Radio1", {type: "checkbox", icon: "", checked: false, disabled: false},
- "+Radio2", {type: "checkbox", icon: "", checked: true, disabled: false},
- "+Radio3", {type: "checkbox", icon: "", checked: false, disabled: false},
- "---", null,
- "+Checkbox", {type: "checkbox", icon: "", checked: false, disabled: false}], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ],
- {postCheckContextMenuFn: function*() {
- let item = contextMenu.getElementsByAttribute("generateditemid", "1")[0];
- ok(item, "Got generated XUL menu item");
- item.doCommand();
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let pagemenu = content.document.getElementById("test-pagemenu");
- Assert.ok(!pagemenu.hasAttribute("hopeless"), "attribute got removed");
- });
- }
- });
-});
-
-add_task(function* test_dom_full_screen() {
- yield test_contextmenu("#test-dom-full-screen",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-leave-dom-fullscreen", true,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ],
- {
- shiftkey: true,
- *preCheckContextMenuFn() {
- yield pushPrefs(["full-screen-api.allow-trusted-requests-only", false],
- ["full-screen-api.transition-duration.enter", "0 0"],
- ["full-screen-api.transition-duration.leave", "0 0"])
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let win = doc.defaultView;
- let full_screen_element = doc.getElementById("test-dom-full-screen");
- let awaitFullScreenChange =
- ContentTaskUtils.waitForEvent(win, "fullscreenchange");
- full_screen_element.requestFullscreen();
- yield awaitFullScreenChange;
- });
- },
- *postCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let win = content.document.defaultView;
- let awaitFullScreenChange =
- ContentTaskUtils.waitForEvent(win, "fullscreenchange");
- content.document.exitFullscreen();
- yield awaitFullScreenChange;
- });
- }
- }
- );
-});
-
-add_task(function* test_pagemenu2() {
- yield test_contextmenu("#test-text",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ],
- {shiftkey: true}
- );
-});
-
-add_task(function* test_select_text() {
- yield test_contextmenu("#test-select-text",
- ["context-copy", true,
- "context-selectall", true,
- "---", null,
- "context-searchselect", true,
- "context-viewpartialsource-selection", true
- ],
- {
- offsetX: 6,
- offsetY: 6,
- *preCheckContextMenuFn() {
- yield selectText("#test-select-text");
- }
- }
- );
-});
-
-add_task(function* test_select_text_link() {
- yield test_contextmenu("#test-select-text-link",
- ["context-openlinkincurrent", true,
- "context-openlinkintab", true,
- ...(hasContainers ? ["context-openlinkinusercontext-menu", true] : []),
- // We need a blank entry here because the containers submenu is
- // dynamically generated with no ids.
- ...(hasContainers ? ["", null] : []),
- "context-openlink", true,
- "context-openlinkprivate", true,
- "---", null,
- "context-bookmarklink", true,
- "context-savelink", true,
- "context-copy", true,
- "context-selectall", true,
- "---", null,
- "context-searchselect", true,
- "context-viewpartialsource-selection", true
- ],
- {
- offsetX: 6,
- offsetY: 6,
- *preCheckContextMenuFn() {
- yield selectText("#test-select-text-link");
- },
- *postCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let win = content.document.defaultView;
- win.getSelection().removeAllRanges();
- });
- }
- }
- );
-});
-
-add_task(function* test_imagelink() {
- yield test_contextmenu("#test-image-link",
- ["context-openlinkintab", true,
- ...(hasContainers ? ["context-openlinkinusercontext-menu", true] : []),
- // We need a blank entry here because the containers submenu is
- // dynamically generated with no ids.
- ...(hasContainers ? ["", null] : []),
- "context-openlink", true,
- "context-openlinkprivate", true,
- "---", null,
- "context-bookmarklink", true,
- "context-savelink", true,
- ...(hasPocket ? ["context-savelinktopocket", true] : []),
- "context-copylink", true,
- "---", null,
- "context-viewimage", true,
- "context-copyimage-contents", true,
- "context-copyimage", true,
- "---", null,
- "context-saveimage", true,
- "context-sendimage", true,
- "context-setDesktopBackground", true,
- "context-viewimageinfo", true
- ]
- );
-});
-
-add_task(function* test_select_input_text() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-select-input-text",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", true,
- "---", null,
- "context-selectall", true,
- "context-searchselect", true,
- "---", null,
- "spell-check-enabled", true
- ].concat(LOGIN_FILL_ITEMS),
- {
- *preCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let win = doc.defaultView;
- win.getSelection().removeAllRanges();
- let element = doc.querySelector("#test-select-input-text");
- element.select();
- });
- }
- }
- );
- */
-});
-
-add_task(function* test_select_input_text_password() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-select-input-text-type-password",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", true,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- // spell checker is shown on input[type="password"] on this testcase
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null
- ].concat(LOGIN_FILL_ITEMS),
- {
- *preCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let win = doc.defaultView;
- win.getSelection().removeAllRanges();
- let element = doc.querySelector("#test-select-input-text-type-password");
- element.select();
- });
- },
- *postCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let win = content.document.defaultView;
- win.getSelection().removeAllRanges();
- });
- }
- }
- );
- */
-});
-
-add_task(function* test_click_to_play_blocked_plugin() {
- yield test_contextmenu("#test-plugin",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-ctp-play", true,
- "context-ctp-hide", true,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ],
- {
- preCheckContextMenuFn: function*() {
- pushPrefs(["plugins.click_to_play", true]);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
- },
- postCheckContextMenuFn: function*() {
- getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED;
- }
- }
- );
-});
-
-add_task(function* test_longdesc() {
- yield test_contextmenu("#test-longdesc",
- ["context-viewimage", true,
- "context-copyimage-contents", true,
- "context-copyimage", true,
- "---", null,
- "context-saveimage", true,
- "context-sendimage", true,
- "context-setDesktopBackground", true,
- "context-viewimageinfo", true,
- "context-viewimagedesc", true
- ]
- );
-});
-
-add_task(function* test_srcdoc() {
- yield test_contextmenu("#test-srcdoc",
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "frame", null,
- ["context-reloadframe", true,
- "---", null,
- "context-saveframe", true,
- "---", null,
- "context-printframe", true,
- "---", null,
- "context-viewframesource", true,
- "context-viewframeinfo", true], null,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ]
- );
-});
-
-add_task(function* test_input_spell_false() {
- todo(false, "spell checker tests are failing, bug 1246296");
- return;
-
- /*
- yield test_contextmenu("#test-contenteditable-spellcheck-false",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- ]
- );
- */
-});
-
-const remoteClientsFixture = [ { id: 1, name: "Foo"}, { id: 2, name: "Bar"} ];
-
-add_task(function* test_plaintext_sendpagetodevice() {
- if (!gFxAccounts.sendTabToDeviceEnabled) {
- return;
- }
- const oldGetter = setupRemoteClientsFixture(remoteClientsFixture);
-
- let plainTextItemsWithSendPage =
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-sendpagetodevice", true,
- ["*Foo", true,
- "*Bar", true,
- "---", null,
- "*All Devices", true], null,
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", true,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true
- ];
- yield test_contextmenu("#test-text", plainTextItemsWithSendPage, {
- *onContextMenuShown() {
- yield openMenuItemSubmenu("context-sendpagetodevice");
- }
- });
-
- restoreRemoteClients(oldGetter);
-});
-
-add_task(function* test_link_sendlinktodevice() {
- if (!gFxAccounts.sendTabToDeviceEnabled) {
- return;
- }
- const oldGetter = setupRemoteClientsFixture(remoteClientsFixture);
-
- yield test_contextmenu("#test-link",
- ["context-openlinkintab", true,
- ...(hasContainers ? ["context-openlinkinusercontext-menu", true] : []),
- // We need a blank entry here because the containers submenu is
- // dynamically generated with no ids.
- ...(hasContainers ? ["", null] : []),
- "context-openlink", true,
- "context-openlinkprivate", true,
- "---", null,
- "context-bookmarklink", true,
- "context-savelink", true,
- ...(hasPocket ? ["context-savelinktopocket", true] : []),
- "context-copylink", true,
- "context-searchselect", true,
- "---", null,
- "context-sendlinktodevice", true,
- ["*Foo", true,
- "*Bar", true,
- "---", null,
- "*All Devices", true], null,
- ],
- {
- *onContextMenuShown() {
- yield openMenuItemSubmenu("context-sendlinktodevice");
- }
- });
-
- restoreRemoteClients(oldGetter);
-});
-
-add_task(function* test_cleanup_html() {
- gBrowser.removeCurrentTab();
-});
-
-/**
- * Selects the text of the element that matches the provided `selector`
- *
- * @param {String} selector
- * A selector passed to querySelector to find
- * the element that will be referenced.
- */
-function* selectText(selector) {
- yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(contentSelector) {
- info(`Selecting text of ${contentSelector}`);
- let doc = content.document;
- let win = doc.defaultView;
- win.getSelection().removeAllRanges();
- let div = doc.createRange();
- let element = doc.querySelector(contentSelector);
- Assert.ok(element, "Found element to select text from");
- div.setStartBefore(element);
- div.setEndAfter(element);
- win.getSelection().addRange(div);
- });
-}
diff --git a/browser/base/content/test/general/browser_contextmenu_childprocess.js b/browser/base/content/test/general/browser_contextmenu_childprocess.js
deleted file mode 100644
index 3d52be9ab..000000000
--- a/browser/base/content/test/general/browser_contextmenu_childprocess.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const gBaseURL = "https://example.com/browser/browser/base/content/test/general/";
-
-add_task(function *() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gBaseURL + "subtst_contextmenu.html");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
-
- // Get the point of the element with the page menu (test-pagemenu) and
- // synthesize a right mouse click there.
- let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouse("#test-pagemenu", 5, 5, { type : "contextmenu", button : 2 }, tab.linkedBrowser);
- yield popupShownPromise;
-
- checkMenu(contextMenu);
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- contextMenu.hidePopup();
- yield popupHiddenPromise;
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-function checkItems(menuitem, arr)
-{
- for (let i = 0; i < arr.length; i += 2) {
- let str = arr[i];
- let details = arr[i + 1];
- if (str == "---") {
- is(menuitem.localName, "menuseparator", "menuseparator");
- }
- else if ("children" in details) {
- is(menuitem.localName, "menu", "submenu");
- is(menuitem.getAttribute("label"), str, str + " label");
- checkItems(menuitem.firstChild.firstChild, details.children);
- }
- else {
- is(menuitem.localName, "menuitem", str + " menuitem");
-
- is(menuitem.getAttribute("label"), str, str + " label");
- is(menuitem.getAttribute("type"), details.type, str + " type");
- is(menuitem.getAttribute("image"), details.icon ? gBaseURL + details.icon : "", str + " icon");
-
- if (details.checked)
- is(menuitem.getAttribute("checked"), "true", str + " checked");
- else
- ok(!menuitem.hasAttribute("checked"), str + " checked");
-
- if (details.disabled)
- is(menuitem.getAttribute("disabled"), "true", str + " disabled");
- else
- ok(!menuitem.hasAttribute("disabled"), str + " disabled");
- }
-
- menuitem = menuitem.nextSibling;
- }
-}
-
-function checkMenu(contextMenu)
-{
- let items = [ "Plain item", {type: "", icon: "", checked: false, disabled: false},
- "Disabled item", {type: "", icon: "", checked: false, disabled: true},
- "Item w/ textContent", {type: "", icon: "", checked: false, disabled: false},
- "---", null,
- "Checkbox", {type: "checkbox", icon: "", checked: true, disabled: false},
- "---", null,
- "Radio1", {type: "checkbox", icon: "", checked: true, disabled: false},
- "Radio2", {type: "checkbox", icon: "", checked: false, disabled: false},
- "Radio3", {type: "checkbox", icon: "", checked: false, disabled: false},
- "---", null,
- "Item w/ icon", {type: "", icon: "favicon.ico", checked: false, disabled: false},
- "Item w/ bad icon", {type: "", icon: "", checked: false, disabled: false},
- "---", null,
- "Submenu", { children:
- ["Radio1", {type: "checkbox", icon: "", checked: false, disabled: false},
- "Radio2", {type: "checkbox", icon: "", checked: true, disabled: false},
- "Radio3", {type: "checkbox", icon: "", checked: false, disabled: false},
- "---", null,
- "Checkbox", {type: "checkbox", icon: "", checked: false, disabled: false}] }
- ];
- checkItems(contextMenu.childNodes[2], items);
-}
diff --git a/browser/base/content/test/general/browser_contextmenu_input.js b/browser/base/content/test/general/browser_contextmenu_input.js
deleted file mode 100644
index cfc7b7529..000000000
--- a/browser/base/content/test/general/browser_contextmenu_input.js
+++ /dev/null
@@ -1,243 +0,0 @@
-"use strict";
-
-let contextMenu;
-let hasPocket = Services.prefs.getBoolPref("extensions.pocket.enabled");
-
-add_task(function* test_setup() {
- const example_base = "http://example.com/browser/browser/base/content/test/general/";
- const url = example_base + "subtst_contextmenu_input.html";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- const chrome_base = "chrome://mochitests/content/browser/browser/base/content/test/general/";
- const contextmenu_common = chrome_base + "contextmenu_common.js";
- Services.scriptloader.loadSubScript(contextmenu_common, this);
-});
-
-add_task(function* test_text_input() {
- yield test_contextmenu("#input_text",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", false,
- "---", null,
- "spell-check-enabled", true]);
-});
-
-add_task(function* test_text_input_spellcheck() {
- yield test_contextmenu("#input_spellcheck_no_value",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", false,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null],
- {
- waitForSpellCheck: true,
- // Need to dynamically add/remove the "password" type or LoginManager
- // will think that the form inputs on the page are part of a login
- // and will add fill-login context menu items.
- *preCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let input = doc.getElementById("input_spellcheck_no_value");
- input.setAttribute("spellcheck", "true");
- input.clientTop; // force layout flush
- });
- },
- }
- );
-});
-
-add_task(function* test_text_input_spellcheckwrong() {
- yield test_contextmenu("#input_spellcheck_incorrect",
- ["*prodigality", true, // spelling suggestion
- "spell-add-to-dictionary", true,
- "---", null,
- "context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null],
- {waitForSpellCheck: true}
- );
-});
-
-add_task(function* test_text_input_spellcheckcorrect() {
- yield test_contextmenu("#input_spellcheck_correct",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true,
- "spell-dictionaries", true,
- ["spell-check-dictionary-en-US", true,
- "---", null,
- "spell-add-dictionaries", true], null],
- {waitForSpellCheck: true}
- );
-});
-
-add_task(function* test_text_input_disabled() {
- yield test_contextmenu("#input_disabled",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", true,
- "---", null,
- "spell-check-enabled", true],
- {skipFocusChange: true}
- );
-});
-
-add_task(function* test_password_input() {
- todo(false, "context-selectall is enabled on osx-e10s, and windows when" +
- " it should be disabled");
- yield test_contextmenu("#input_password",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", null,
- "---", null,
- "fill-login", null,
- ["fill-login-no-logins", false,
- "---", null,
- "fill-login-saved-passwords", true], null],
- {
- skipFocusChange: true,
- // Need to dynamically add/remove the "password" type or LoginManager
- // will think that the form inputs on the page are part of a login
- // and will add fill-login context menu items.
- *preCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let input = doc.getElementById("input_password");
- input.type = "password";
- input.clientTop; // force layout flush
- });
- },
- *postCheckContextMenuFn() {
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- let doc = content.document;
- let input = doc.getElementById("input_password");
- input.type = "text";
- input.clientTop; // force layout flush
- });
- },
- }
- );
-});
-
-add_task(function* test_tel_email_url_number_input() {
- todo(false, "context-selectall is enabled on osx-e10s, and windows when" +
- " it should be disabled");
- for (let selector of ["#input_email", "#input_url", "#input_tel", "#input_number"]) {
- yield test_contextmenu(selector,
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", null],
- {skipFocusChange: true}
- );
- }
-});
-
-add_task(function* test_date_time_color_range_month_week_datetimelocal_input() {
- for (let selector of ["#input_date", "#input_time", "#input_color",
- "#input_range", "#input_month", "#input_week",
- "#input_datetime-local"]) {
- yield test_contextmenu(selector,
- ["context-navigation", null,
- ["context-back", false,
- "context-forward", false,
- "context-reload", true,
- "context-bookmarkpage", true], null,
- "---", null,
- "context-savepage", true,
- ...(hasPocket ? ["context-pocket", true] : []),
- "---", null,
- "context-viewbgimage", false,
- "context-selectall", null,
- "---", null,
- "context-viewsource", true,
- "context-viewinfo", true],
- {skipFocusChange: true}
- );
- }
-});
-
-add_task(function* test_search_input() {
- todo(false, "context-selectall is enabled on osx-e10s, and windows when" +
- " it should be disabled");
- yield test_contextmenu("#input_search",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", null,
- "---", null,
- "spell-check-enabled", true],
- {skipFocusChange: true}
- );
-});
-
-add_task(function* test_text_input_readonly() {
- todo(false, "context-selectall is enabled on osx-e10s, and windows when" +
- " it should be disabled");
- todo(false, "spell-check should not be enabled for input[readonly]. see bug 1246296");
- yield test_contextmenu("#input_readonly",
- ["context-undo", false,
- "---", null,
- "context-cut", true,
- "context-copy", true,
- "context-paste", null, // ignore clipboard state
- "context-delete", false,
- "---", null,
- "context-selectall", null],
- {skipFocusChange: true}
- );
-});
-
-add_task(function* test_cleanup() {
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_csp_block_all_mixedcontent.js b/browser/base/content/test/general/browser_csp_block_all_mixedcontent.js
deleted file mode 100644
index 00a06f53e..000000000
--- a/browser/base/content/test/general/browser_csp_block_all_mixedcontent.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Description of the Test:
- * We load an https page which uses a CSP including block-all-mixed-content.
- * The page tries to load a script over http. We make sure the UI is not
- * influenced when blocking the mixed content. In particular the page
- * should still appear fully encrypted with a green lock.
- */
-
-const PRE_PATH = "https://example.com/browser/browser/base/content/test/general/";
-var gTestBrowser = null;
-
-// ------------------------------------------------------
-function cleanUpAfterTests() {
- gBrowser.removeCurrentTab();
- window.focus();
- finish();
-}
-
-// ------------------------------------------------------
-function verifyUInotDegraded() {
- // make sure that not mixed content is loaded and also not blocked
- assertMixedContentBlockingState(
- gTestBrowser,
- { activeLoaded: false,
- activeBlocked: false,
- passiveLoaded: false
- }
- );
- // clean up and finish test
- cleanUpAfterTests();
-}
-
-// ------------------------------------------------------
-function runTests() {
- var newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
- newTab.linkedBrowser.stop();
-
- // Starting the test
- BrowserTestUtils.browserLoaded(gTestBrowser).then(verifyUInotDegraded);
- var url = PRE_PATH + "file_csp_block_all_mixedcontent.html";
- gTestBrowser.loadURI(url);
-}
-
-// ------------------------------------------------------
-function test() {
- // Performing async calls, e.g. 'onload', we have to wait till all of them finished
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- { 'set': [["security.mixed_content.block_active_content", true]] },
- function() { runTests(); }
- );
-}
diff --git a/browser/base/content/test/general/browser_ctrlTab.js b/browser/base/content/test/general/browser_ctrlTab.js
deleted file mode 100644
index d16aaeca4..000000000
--- a/browser/base/content/test/general/browser_ctrlTab.js
+++ /dev/null
@@ -1,185 +0,0 @@
-add_task(function* () {
- gPrefService.setBoolPref("browser.ctrlTab.previews", true);
-
- gBrowser.addTab();
- gBrowser.addTab();
- gBrowser.addTab();
-
- checkTabs(4);
-
- yield ctrlTabTest([2], 1, 0);
- yield ctrlTabTest([2, 3, 1], 2, 2);
- yield ctrlTabTest([], 4, 2);
-
- {
- let selectedIndex = gBrowser.tabContainer.selectedIndex;
- yield pressCtrlTab();
- yield pressCtrlTab(true);
- yield releaseCtrl();
- is(gBrowser.tabContainer.selectedIndex, selectedIndex,
- "Ctrl+Tab -> Ctrl+Shift+Tab keeps the selected tab");
- }
-
- { // test for bug 445369
- let tabs = gBrowser.tabs.length;
- yield pressCtrlTab();
- yield synthesizeCtrlW();
- is(gBrowser.tabs.length, tabs - 1, "Ctrl+Tab -> Ctrl+W removes one tab");
- yield releaseCtrl();
- }
-
- { // test for bug 667314
- let tabs = gBrowser.tabs.length;
- yield pressCtrlTab();
- yield pressCtrlTab(true);
- yield synthesizeCtrlW();
- is(gBrowser.tabs.length, tabs - 1, "Ctrl+Tab -> Ctrl+W removes the selected tab");
- yield releaseCtrl();
- }
-
- gBrowser.addTab();
- checkTabs(3);
- yield ctrlTabTest([2, 1, 0], 7, 1);
-
- { // test for bug 1292049
- let tabToClose = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:buildconfig");
- checkTabs(4);
- selectTabs([0, 1, 2, 3]);
-
- yield BrowserTestUtils.removeTab(tabToClose);
- checkTabs(3);
- undoCloseTab();
- checkTabs(4);
- is(gBrowser.tabContainer.selectedIndex, 3, "tab is selected after closing and restoring it");
-
- yield ctrlTabTest([], 1, 2);
- }
-
- { // test for bug 445369
- checkTabs(4);
- selectTabs([1, 2, 0]);
-
- let selectedTab = gBrowser.selectedTab;
- let tabToRemove = gBrowser.tabs[1];
-
- yield pressCtrlTab();
- yield pressCtrlTab();
- yield synthesizeCtrlW();
- ok(!tabToRemove.parentNode,
- "Ctrl+Tab*2 -> Ctrl+W removes the second most recently selected tab");
-
- yield pressCtrlTab(true);
- yield pressCtrlTab(true);
- yield releaseCtrl();
- ok(selectedTab.selected,
- "Ctrl+Tab*2 -> Ctrl+W -> Ctrl+Shift+Tab*2 keeps the selected tab");
- }
- gBrowser.removeTab(gBrowser.tabContainer.lastChild);
- checkTabs(2);
-
- yield ctrlTabTest([1], 1, 0);
-
- gBrowser.removeTab(gBrowser.tabContainer.lastChild);
- checkTabs(1);
-
- { // test for bug 445768
- let focusedWindow = document.commandDispatcher.focusedWindow;
- let eventConsumed = true;
- let detectKeyEvent = function (event) {
- eventConsumed = event.defaultPrevented;
- };
- document.addEventListener("keypress", detectKeyEvent, false);
- yield pressCtrlTab();
- document.removeEventListener("keypress", detectKeyEvent, false);
- ok(eventConsumed, "Ctrl+Tab consumed by the tabbed browser if one tab is open");
- is(focusedWindow, document.commandDispatcher.focusedWindow,
- "Ctrl+Tab doesn't change focus if one tab is open");
- }
-
- // cleanup
- if (gPrefService.prefHasUserValue("browser.ctrlTab.previews"))
- gPrefService.clearUserPref("browser.ctrlTab.previews");
-
- /* private utility functions */
-
- function* pressCtrlTab(aShiftKey) {
- let promise;
- if (!isOpen() && canOpen()) {
- promise = BrowserTestUtils.waitForEvent(ctrlTab.panel, "popupshown");
- } else {
- promise = BrowserTestUtils.waitForEvent(document, "keyup");
- }
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true, shiftKey: !!aShiftKey });
- return promise;
- }
-
- function* releaseCtrl() {
- let promise;
- if (isOpen()) {
- promise = BrowserTestUtils.waitForEvent(ctrlTab.panel, "popuphidden");
- } else {
- promise = BrowserTestUtils.waitForEvent(document, "keyup");
- }
- EventUtils.synthesizeKey("VK_CONTROL", { type: "keyup" });
- return promise;
- }
-
- function* synthesizeCtrlW() {
- let promise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabClose");
- EventUtils.synthesizeKey("w", { ctrlKey: true });
- return promise;
- }
-
- function isOpen() {
- return ctrlTab.isOpen;
- }
-
- function canOpen() {
- return gPrefService.getBoolPref("browser.ctrlTab.previews") && gBrowser.tabs.length > 2;
- }
-
- function checkTabs(aTabs) {
- is(gBrowser.tabs.length, aTabs, "number of open tabs should be " + aTabs);
- }
-
- function selectTabs(tabs) {
- tabs.forEach(function (index) {
- gBrowser.selectedTab = gBrowser.tabs[index];
- });
- }
-
- function* ctrlTabTest(tabsToSelect, tabTimes, expectedIndex) {
- selectTabs(tabsToSelect);
-
- var indexStart = gBrowser.tabContainer.selectedIndex;
- var tabCount = gBrowser.tabs.length;
- var normalized = tabTimes % tabCount;
- var where = normalized == 1 ? "back to the previously selected tab" :
- normalized + " tabs back in most-recently-selected order";
-
- for (let i = 0; i < tabTimes; i++) {
- yield pressCtrlTab();
-
- if (tabCount > 2)
- is(gBrowser.tabContainer.selectedIndex, indexStart,
- "Selected tab doesn't change while tabbing");
- }
-
- if (tabCount > 2) {
- ok(isOpen(),
- "With " + tabCount + " tabs open, Ctrl+Tab opens the preview panel");
-
- yield releaseCtrl();
-
- ok(!isOpen(),
- "Releasing Ctrl closes the preview panel");
- } else {
- ok(!isOpen(),
- "With " + tabCount + " tabs open, Ctrl+Tab doesn't open the preview panel");
- }
-
- is(gBrowser.tabContainer.selectedIndex, expectedIndex,
- "With "+ tabCount +" tabs open and tab " + indexStart
- + " selected, Ctrl+Tab*" + tabTimes + " goes " + where);
- }
-});
diff --git a/browser/base/content/test/general/browser_datachoices_notification.js b/browser/base/content/test/general/browser_datachoices_notification.js
deleted file mode 100644
index 360728b4c..000000000
--- a/browser/base/content/test/general/browser_datachoices_notification.js
+++ /dev/null
@@ -1,221 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Pass an empty scope object to the import to prevent "leaked window property"
-// errors in tests.
-var Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-var TelemetryReportingPolicy =
- Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm", {}).TelemetryReportingPolicy;
-
-const PREF_BRANCH = "datareporting.policy.";
-const PREF_BYPASS_NOTIFICATION = PREF_BRANCH + "dataSubmissionPolicyBypassNotification";
-const PREF_CURRENT_POLICY_VERSION = PREF_BRANCH + "currentPolicyVersion";
-const PREF_ACCEPTED_POLICY_VERSION = PREF_BRANCH + "dataSubmissionPolicyAcceptedVersion";
-const PREF_ACCEPTED_POLICY_DATE = PREF_BRANCH + "dataSubmissionPolicyNotifiedTime";
-
-const TEST_POLICY_VERSION = 37;
-
-function fakeShowPolicyTimeout(set, clear) {
- let reportingPolicy =
- Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm", {}).Policy;
- reportingPolicy.setShowInfobarTimeout = set;
- reportingPolicy.clearShowInfobarTimeout = clear;
-}
-
-function sendSessionRestoredNotification() {
- let reportingPolicyImpl =
- Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm", {}).TelemetryReportingPolicyImpl;
- reportingPolicyImpl.observe(null, "sessionstore-windows-restored", null);
-}
-
-/**
- * Wait for a tick.
- */
-function promiseNextTick() {
- return new Promise(resolve => executeSoon(resolve));
-}
-
-/**
- * Wait for a notification to be shown in a notification box.
- * @param {Object} aNotificationBox The notification box.
- * @return {Promise} Resolved when the notification is displayed.
- */
-function promiseWaitForAlertActive(aNotificationBox) {
- let deferred = PromiseUtils.defer();
- aNotificationBox.addEventListener("AlertActive", function onActive() {
- aNotificationBox.removeEventListener("AlertActive", onActive, true);
- deferred.resolve();
- });
- return deferred.promise;
-}
-
-/**
- * Wait for a notification to be closed.
- * @param {Object} aNotification The notification.
- * @return {Promise} Resolved when the notification is closed.
- */
-function promiseWaitForNotificationClose(aNotification) {
- let deferred = PromiseUtils.defer();
- waitForNotificationClose(aNotification, deferred.resolve);
- return deferred.promise;
-}
-
-function triggerInfoBar(expectedTimeoutMs) {
- let showInfobarCallback = null;
- let timeoutMs = null;
- fakeShowPolicyTimeout((callback, timeout) => {
- showInfobarCallback = callback;
- timeoutMs = timeout;
- }, () => {});
- sendSessionRestoredNotification();
- Assert.ok(!!showInfobarCallback, "Must have a timer callback.");
- if (expectedTimeoutMs !== undefined) {
- Assert.equal(timeoutMs, expectedTimeoutMs, "Timeout should match");
- }
- showInfobarCallback();
-}
-
-var checkInfobarButton = Task.async(function* (aNotification) {
- // Check that the button on the data choices infobar does the right thing.
- let buttons = aNotification.getElementsByTagName("button");
- Assert.equal(buttons.length, 1, "There is 1 button in the data reporting notification.");
- let button = buttons[0];
-
- // Add an observer to ensure the "advanced" pane opened (but don't bother
- // closing it - we close the entire window when done.)
- let paneLoadedPromise = promiseTopicObserved("advanced-pane-loaded");
-
- // Click on the button.
- button.click();
-
- // Wait for the preferences panel to open.
- yield paneLoadedPromise;
- yield promiseNextTick();
-});
-
-add_task(function* setup() {
- const bypassNotification = Preferences.get(PREF_BYPASS_NOTIFICATION, true);
- const currentPolicyVersion = Preferences.get(PREF_CURRENT_POLICY_VERSION, 1);
-
- // Register a cleanup function to reset our preferences.
- registerCleanupFunction(() => {
- Preferences.set(PREF_BYPASS_NOTIFICATION, bypassNotification);
- Preferences.set(PREF_CURRENT_POLICY_VERSION, currentPolicyVersion);
-
- return closeAllNotifications();
- });
-
- // Don't skip the infobar visualisation.
- Preferences.set(PREF_BYPASS_NOTIFICATION, false);
- // Set the current policy version.
- Preferences.set(PREF_CURRENT_POLICY_VERSION, TEST_POLICY_VERSION);
-});
-
-function clearAcceptedPolicy() {
- // Reset the accepted policy.
- Preferences.reset(PREF_ACCEPTED_POLICY_VERSION);
- Preferences.reset(PREF_ACCEPTED_POLICY_DATE);
-}
-
-add_task(function* test_single_window() {
- clearAcceptedPolicy();
-
- // Close all the notifications, then try to trigger the data choices infobar.
- yield closeAllNotifications();
-
- let notificationBox = document.getElementById("global-notificationbox");
-
- // Make sure that we have a coherent initial state.
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_VERSION, 0), 0,
- "No version should be set on init.");
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_DATE, 0), 0,
- "No date should be set on init.");
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "User not notified about datareporting policy.");
-
- let alertShownPromise = promiseWaitForAlertActive(notificationBox);
- Assert.ok(!TelemetryReportingPolicy.canUpload(),
- "User should not be allowed to upload.");
-
- // Wait for the infobar to be displayed.
- triggerInfoBar(10 * 1000);
- yield alertShownPromise;
-
- Assert.equal(notificationBox.allNotifications.length, 1, "Notification Displayed.");
- Assert.ok(TelemetryReportingPolicy.canUpload(), "User should be allowed to upload now.");
-
- yield promiseNextTick();
- let promiseClosed = promiseWaitForNotificationClose(notificationBox.currentNotification);
- yield checkInfobarButton(notificationBox.currentNotification);
- yield promiseClosed;
-
- Assert.equal(notificationBox.allNotifications.length, 0, "No notifications remain.");
-
- // Check that we are still clear to upload and that the policy data is saved.
- Assert.ok(TelemetryReportingPolicy.canUpload());
- Assert.equal(TelemetryReportingPolicy.testIsUserNotified(), true,
- "User notified about datareporting policy.");
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_VERSION, 0), TEST_POLICY_VERSION,
- "Version pref set.");
- Assert.greater(parseInt(Preferences.get(PREF_ACCEPTED_POLICY_DATE, null), 10), -1,
- "Date pref set.");
-});
-
-add_task(function* test_multiple_windows() {
- clearAcceptedPolicy();
-
- // Close all the notifications, then try to trigger the data choices infobar.
- yield closeAllNotifications();
-
- // Ensure we see the notification on all windows and that action on one window
- // results in dismiss on every window.
- let otherWindow = yield BrowserTestUtils.openNewBrowserWindow();
-
- // Get the notification box for both windows.
- let notificationBoxes = [
- document.getElementById("global-notificationbox"),
- otherWindow.document.getElementById("global-notificationbox")
- ];
-
- Assert.ok(notificationBoxes[1], "2nd window has a global notification box.");
-
- // Make sure that we have a coherent initial state.
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_VERSION, 0), 0, "No version should be set on init.");
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_DATE, 0), 0, "No date should be set on init.");
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(), "User not notified about datareporting policy.");
-
- let showAlertPromises = [
- promiseWaitForAlertActive(notificationBoxes[0]),
- promiseWaitForAlertActive(notificationBoxes[1])
- ];
-
- Assert.ok(!TelemetryReportingPolicy.canUpload(),
- "User should not be allowed to upload.");
-
- // Wait for the infobars.
- triggerInfoBar(10 * 1000);
- yield Promise.all(showAlertPromises);
-
- // Both notification were displayed. Close one and check that both gets closed.
- let closeAlertPromises = [
- promiseWaitForNotificationClose(notificationBoxes[0].currentNotification),
- promiseWaitForNotificationClose(notificationBoxes[1].currentNotification)
- ];
- notificationBoxes[0].currentNotification.close();
- yield Promise.all(closeAlertPromises);
-
- // Close the second window we opened.
- yield BrowserTestUtils.closeWindow(otherWindow);
-
- // Check that we are clear to upload and that the policy data us saved.
- Assert.ok(TelemetryReportingPolicy.canUpload(), "User should be allowed to upload now.");
- Assert.equal(TelemetryReportingPolicy.testIsUserNotified(), true,
- "User notified about datareporting policy.");
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_VERSION, 0), TEST_POLICY_VERSION,
- "Version pref set.");
- Assert.greater(parseInt(Preferences.get(PREF_ACCEPTED_POLICY_DATE, null), 10), -1,
- "Date pref set.");
-});
diff --git a/browser/base/content/test/general/browser_decoderDoctor.js b/browser/base/content/test/general/browser_decoderDoctor.js
deleted file mode 100644
index a37972160..000000000
--- a/browser/base/content/test/general/browser_decoderDoctor.js
+++ /dev/null
@@ -1,122 +0,0 @@
-"use strict";
-
-function* test_decoder_doctor_notification(type, notificationMessage, options) {
- yield BrowserTestUtils.withNewTab({ gBrowser }, function*(browser) {
- let awaitNotificationBar =
- BrowserTestUtils.waitForNotificationBar(gBrowser, browser, "decoder-doctor-notification");
-
- yield ContentTask.spawn(browser, type, function*(aType) {
- Services.obs.notifyObservers(content.window,
- "decoder-doctor-notification",
- JSON.stringify({type: aType,
- isSolved: false,
- decoderDoctorReportId: "test",
- formats: "test"}));
- });
-
- let notification;
- try {
- notification = yield awaitNotificationBar;
- } catch (ex) {
- ok(false, ex);
- return;
- }
- ok(notification, "Got decoder-doctor-notification notification");
-
- is(notification.getAttribute("label"), notificationMessage,
- "notification message should match expectation");
- let button = notification.childNodes[0];
- if (options && options.noLearnMoreButton) {
- ok(!button, "There should not be a Learn More button");
- return;
- }
-
- is(button.getAttribute("label"), gNavigatorBundle.getString("decoder.noCodecs.button"),
- "notification button should be 'Learn more'");
- is(button.getAttribute("accesskey"), gNavigatorBundle.getString("decoder.noCodecs.accesskey"),
- "notification button should have accesskey");
-
- let baseURL = Services.urlFormatter.formatURLPref("app.support.baseURL");
- let url = baseURL + ((options && options.sumo) ||
- "fix-video-audio-problems-firefox-windows");
- let awaitNewTab = BrowserTestUtils.waitForNewTab(gBrowser, url);
- button.click();
- let sumoTab = yield awaitNewTab;
- yield BrowserTestUtils.removeTab(sumoTab);
- });
-}
-
-add_task(function* test_adobe_cdm_not_found() {
- // This is only sent on Windows.
- if (AppConstants.platform != "win") {
- return;
- }
-
- let message;
- if (AppConstants.isPlatformAndVersionAtMost("win", "5.9")) {
- message = gNavigatorBundle.getFormattedString("emeNotifications.drmContentDisabled.message", [""]);
- } else {
- message = gNavigatorBundle.getString("decoder.noCodecs.message");
- }
-
- yield test_decoder_doctor_notification("adobe-cdm-not-found", message);
-});
-
-add_task(function* test_adobe_cdm_not_activated() {
- // This is only sent on Windows.
- if (AppConstants.platform != "win") {
- return;
- }
-
- let message;
- if (AppConstants.isPlatformAndVersionAtMost("win", "5.9")) {
- message = gNavigatorBundle.getString("decoder.noCodecsXP.message");
- } else {
- message = gNavigatorBundle.getString("decoder.noCodecs.message");
- }
-
- yield test_decoder_doctor_notification("adobe-cdm-not-activated", message);
-});
-
-add_task(function* test_platform_decoder_not_found() {
- // Not sent on Windows XP.
- if (AppConstants.isPlatformAndVersionAtMost("win", "5.9")) {
- return;
- }
-
- let message;
- let isLinux = AppConstants.platform == "linux";
- if (isLinux) {
- message = gNavigatorBundle.getString("decoder.noCodecsLinux.message");
- } else {
- message = gNavigatorBundle.getString("decoder.noHWAcceleration.message");
- }
-
- yield test_decoder_doctor_notification("platform-decoder-not-found",
- message,
- {noLearnMoreButton: isLinux});
-});
-
-add_task(function* test_cannot_initialize_pulseaudio() {
- // This is only sent on Linux.
- if (AppConstants.platform != "linux") {
- return;
- }
-
- let message = gNavigatorBundle.getString("decoder.noPulseAudio.message");
- yield test_decoder_doctor_notification("cannot-initialize-pulseaudio",
- message,
- {sumo: "fix-common-audio-and-video-issues"});
-});
-
-add_task(function* test_unsupported_libavcodec() {
- // This is only sent on Linux.
- if (AppConstants.platform != "linux") {
- return;
- }
-
- let message = gNavigatorBundle.getString("decoder.unsupportedLibavcodec.message");
- yield test_decoder_doctor_notification("unsupported-libavcodec",
- message,
- {noLearnMoreButton: true});
-});
diff --git a/browser/base/content/test/general/browser_devedition.js b/browser/base/content/test/general/browser_devedition.js
deleted file mode 100644
index 06ee42e7e..000000000
--- a/browser/base/content/test/general/browser_devedition.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Testing changes for Developer Edition theme.
- * A special stylesheet should be added to the browser.xul document
- * when the firefox-devedition@mozilla.org lightweight theme
- * is applied.
- */
-
-const PREF_LWTHEME_USED_THEMES = "lightweightThemes.usedThemes";
-const PREF_DEVTOOLS_THEME = "devtools.theme";
-const {LightweightThemeManager} = Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", {});
-
-LightweightThemeManager.clearBuiltInThemes();
-LightweightThemeManager.addBuiltInTheme(dummyLightweightTheme("firefox-devedition@mozilla.org"));
-
-registerCleanupFunction(() => {
- // Set preferences back to their original values
- LightweightThemeManager.currentTheme = null;
- Services.prefs.clearUserPref(PREF_DEVTOOLS_THEME);
- Services.prefs.clearUserPref(PREF_LWTHEME_USED_THEMES);
-
- LightweightThemeManager.currentTheme = null;
- LightweightThemeManager.clearBuiltInThemes();
-});
-
-add_task(function* startTests() {
- Services.prefs.setCharPref(PREF_DEVTOOLS_THEME, "dark");
-
- info ("Setting the current theme to null");
- LightweightThemeManager.currentTheme = null;
- ok (!DevEdition.isStyleSheetEnabled, "There is no devedition style sheet when no lw theme is applied.");
-
- info ("Adding a lightweight theme.");
- LightweightThemeManager.currentTheme = dummyLightweightTheme("preview0");
- ok (!DevEdition.isStyleSheetEnabled, "The devedition stylesheet has been removed when a lightweight theme is applied.");
-
- info ("Applying the devedition lightweight theme.");
- let onAttributeAdded = waitForBrightTitlebarAttribute();
- LightweightThemeManager.currentTheme = LightweightThemeManager.getUsedTheme("firefox-devedition@mozilla.org");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet has been added when the devedition lightweight theme is applied");
- yield onAttributeAdded;
- is (document.documentElement.getAttribute("brighttitlebarforeground"), "true",
- "The brighttitlebarforeground attribute is set on the window.");
-
- info ("Unapplying all themes.");
- LightweightThemeManager.currentTheme = null;
- ok (!DevEdition.isStyleSheetEnabled, "There is no devedition style sheet when no lw theme is applied.");
-
- info ("Applying the devedition lightweight theme.");
- onAttributeAdded = waitForBrightTitlebarAttribute();
- LightweightThemeManager.currentTheme = LightweightThemeManager.getUsedTheme("firefox-devedition@mozilla.org");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet has been added when the devedition lightweight theme is applied");
- yield onAttributeAdded;
- ok (document.documentElement.hasAttribute("brighttitlebarforeground"),
- "The brighttitlebarforeground attribute is set on the window with dark devtools theme.");
-});
-
-add_task(function* testDevtoolsTheme() {
- info ("Checking stylesheet and :root attributes based on devtools theme.");
- Services.prefs.setCharPref(PREF_DEVTOOLS_THEME, "light");
- is (document.documentElement.getAttribute("devtoolstheme"), "light",
- "The documentElement has an attribute based on devtools theme.");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is still there with the light devtools theme.");
- ok (!document.documentElement.hasAttribute("brighttitlebarforeground"),
- "The brighttitlebarforeground attribute is not set on the window with light devtools theme.");
-
- Services.prefs.setCharPref(PREF_DEVTOOLS_THEME, "dark");
- is (document.documentElement.getAttribute("devtoolstheme"), "dark",
- "The documentElement has an attribute based on devtools theme.");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is still there with the dark devtools theme.");
- is (document.documentElement.getAttribute("brighttitlebarforeground"), "true",
- "The brighttitlebarforeground attribute is set on the window with dark devtools theme.");
-
- Services.prefs.setCharPref(PREF_DEVTOOLS_THEME, "foobar");
- is (document.documentElement.getAttribute("devtoolstheme"), "light",
- "The documentElement has 'light' as a default for the devtoolstheme attribute");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is still there with the foobar devtools theme.");
- ok (!document.documentElement.hasAttribute("brighttitlebarforeground"),
- "The brighttitlebarforeground attribute is not set on the window with light devtools theme.");
-});
-
-function dummyLightweightTheme(id) {
- return {
- id: id,
- name: id,
- headerURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.header.png",
- iconURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.icon.png",
- textcolor: "red",
- accentcolor: "blue"
- };
-}
-
-add_task(function* testLightweightThemePreview() {
- info ("Setting devedition to current and the previewing others");
- LightweightThemeManager.currentTheme = LightweightThemeManager.getUsedTheme("firefox-devedition@mozilla.org");
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is enabled.");
- LightweightThemeManager.previewTheme(dummyLightweightTheme("preview0"));
- ok (!DevEdition.isStyleSheetEnabled, "The devedition stylesheet is not enabled after a lightweight theme preview.");
- LightweightThemeManager.resetPreview();
- LightweightThemeManager.previewTheme(dummyLightweightTheme("preview1"));
- ok (!DevEdition.isStyleSheetEnabled, "The devedition stylesheet is not enabled after a second lightweight theme preview.");
- LightweightThemeManager.resetPreview();
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is enabled again after resetting the preview.");
- LightweightThemeManager.currentTheme = null;
- ok (!DevEdition.isStyleSheetEnabled, "The devedition stylesheet is gone after removing the current theme.");
-
- info ("Previewing the devedition theme");
- LightweightThemeManager.previewTheme(LightweightThemeManager.getUsedTheme("firefox-devedition@mozilla.org"));
- ok (DevEdition.isStyleSheetEnabled, "The devedition stylesheet is enabled.");
- LightweightThemeManager.previewTheme(dummyLightweightTheme("preview2"));
- LightweightThemeManager.resetPreview();
- ok (!DevEdition.isStyleSheetEnabled, "The devedition stylesheet is now disabled after resetting the preview.");
-});
-
-// Use a mutation observer to wait for the brighttitlebarforeground
-// attribute to change. Using this instead of waiting for the load
-// event on the DevEdition styleSheet.
-function waitForBrightTitlebarAttribute() {
- return new Promise((resolve, reject) => {
- let mutationObserver = new MutationObserver(function (mutations) {
- for (let mutation of mutations) {
- if (mutation.attributeName == "brighttitlebarforeground") {
- mutationObserver.disconnect();
- resolve();
- }
- }
- });
- mutationObserver.observe(document.documentElement, { attributes: true });
- });
-}
diff --git a/browser/base/content/test/general/browser_discovery.js b/browser/base/content/test/general/browser_discovery.js
deleted file mode 100644
index 23d44c6a9..000000000
--- a/browser/base/content/test/general/browser_discovery.js
+++ /dev/null
@@ -1,162 +0,0 @@
-var browser;
-
-function doc() {
- return browser.contentDocument;
-}
-
-function setHandlerFunc(aResultFunc) {
- gBrowser.addEventListener("DOMLinkAdded", function (event) {
- gBrowser.removeEventListener("DOMLinkAdded", arguments.callee, false);
- executeSoon(aResultFunc);
- }, false);
-}
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- browser = gBrowser.selectedBrowser;
- browser.addEventListener("load", function (event) {
- event.currentTarget.removeEventListener("load", arguments.callee, true);
- iconDiscovery();
- }, true);
- var rootDir = getRootDirectory(gTestPath);
- content.location = rootDir + "discovery.html";
-}
-
-var iconDiscoveryTests = [
- { text: "rel icon discovered" },
- { rel: "abcdefg icon qwerty", text: "rel may contain additional rels separated by spaces" },
- { rel: "ICON", text: "rel is case insensitive" },
- { rel: "shortcut-icon", pass: false, text: "rel shortcut-icon not discovered" },
- { href: "moz.png", text: "relative href works" },
- { href: "notthere.png", text: "404'd icon is removed properly" },
- { href: "data:image/x-icon,%00", type: "image/x-icon", text: "data: URIs work" },
- { type: "image/png; charset=utf-8", text: "type may have optional parameters (RFC2046)" }
-];
-
-function runIconDiscoveryTest() {
- var testCase = iconDiscoveryTests[0];
- var head = doc().getElementById("linkparent");
- var hasSrc = gBrowser.getIcon() != null;
- if (testCase.pass)
- ok(hasSrc, testCase.text);
- else
- ok(!hasSrc, testCase.text);
-
- head.removeChild(head.getElementsByTagName('link')[0]);
- iconDiscoveryTests.shift();
- iconDiscovery(); // Run the next test.
-}
-
-function iconDiscovery() {
- if (iconDiscoveryTests.length) {
- setHandlerFunc(runIconDiscoveryTest);
- gBrowser.setIcon(gBrowser.selectedTab, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- var testCase = iconDiscoveryTests[0];
- var head = doc().getElementById("linkparent");
- var link = doc().createElement("link");
-
- var rootDir = getRootDirectory(gTestPath);
- var rel = testCase.rel || "icon";
- var href = testCase.href || rootDir + "moz.png";
- var type = testCase.type || "image/png";
- if (testCase.pass == undefined)
- testCase.pass = true;
-
- link.rel = rel;
- link.href = href;
- link.type = type;
- head.appendChild(link);
- } else {
- searchDiscovery();
- }
-}
-
-var searchDiscoveryTests = [
- { text: "rel search discovered" },
- { rel: "SEARCH", text: "rel is case insensitive" },
- { rel: "-search-", pass: false, text: "rel -search- not discovered" },
- { rel: "foo bar baz search quux", text: "rel may contain additional rels separated by spaces" },
- { href: "https://not.mozilla.com", text: "HTTPS ok" },
- { href: "ftp://not.mozilla.com", text: "FTP ok" },
- { href: "data:text/foo,foo", pass: false, text: "data URI not permitted" },
- { href: "javascript:alert(0)", pass: false, text: "JS URI not permitted" },
- { type: "APPLICATION/OPENSEARCHDESCRIPTION+XML", text: "type is case insensitve" },
- { type: " application/opensearchdescription+xml ", text: "type may contain extra whitespace" },
- { type: "application/opensearchdescription+xml; charset=utf-8", text: "type may have optional parameters (RFC2046)" },
- { type: "aapplication/opensearchdescription+xml", pass: false, text: "type should not be loosely matched" },
- { rel: "search search search", count: 1, text: "only one engine should be added" }
-];
-
-function runSearchDiscoveryTest() {
- var testCase = searchDiscoveryTests[0];
- var title = testCase.title || searchDiscoveryTests.length;
- if (browser.engines) {
- var hasEngine = (testCase.count) ? (browser.engines[0].title == title &&
- browser.engines.length == testCase.count) :
- (browser.engines[0].title == title);
- ok(hasEngine, testCase.text);
- browser.engines = null;
- }
- else
- ok(!testCase.pass, testCase.text);
-
- searchDiscoveryTests.shift();
- searchDiscovery(); // Run the next test.
-}
-
-// This handler is called twice, once for each added link element.
-// Only want to check once the second link element has been added.
-var ranOnce = false;
-function runMultipleEnginesTestAndFinalize() {
- if (!ranOnce) {
- ranOnce = true;
- return;
- }
- ok(browser.engines, "has engines");
- is(browser.engines.length, 1, "only one engine");
- is(browser.engines[0].uri, "http://first.mozilla.com/search.xml", "first engine wins");
-
- gBrowser.removeCurrentTab();
- finish();
-}
-
-function searchDiscovery() {
- let head = doc().getElementById("linkparent");
-
- if (searchDiscoveryTests.length) {
- setHandlerFunc(runSearchDiscoveryTest);
- let testCase = searchDiscoveryTests[0];
- let link = doc().createElement("link");
-
- let rel = testCase.rel || "search";
- let href = testCase.href || "http://so.not.here.mozilla.com/search.xml";
- let type = testCase.type || "application/opensearchdescription+xml";
- let title = testCase.title || searchDiscoveryTests.length;
- if (testCase.pass == undefined)
- testCase.pass = true;
-
- link.rel = rel;
- link.href = href;
- link.type = type;
- link.title = title;
- head.appendChild(link);
- } else {
- setHandlerFunc(runMultipleEnginesTestAndFinalize);
- setHandlerFunc(runMultipleEnginesTestAndFinalize);
- // Test multiple engines with the same title
- let link = doc().createElement("link");
- link.rel = "search";
- link.href = "http://first.mozilla.com/search.xml";
- link.type = "application/opensearchdescription+xml";
- link.title = "Test Engine";
- let link2 = link.cloneNode(false);
- link2.href = "http://second.mozilla.com/search.xml";
-
- head.appendChild(link);
- head.appendChild(link2);
- }
-}
diff --git a/browser/base/content/test/general/browser_documentnavigation.js b/browser/base/content/test/general/browser_documentnavigation.js
deleted file mode 100644
index eb789d076..000000000
--- a/browser/base/content/test/general/browser_documentnavigation.js
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * This test checks that focus is adjusted properly in a browser when pressing F6 and Shift+F6.
- * There are additional tests in dom/tests/mochitest/chrome/test_focus_docnav.xul which test
- * non-browser cases.
- */
-
-var testPage1 = "data:text/html,<html id='html1'><body id='body1'><button id='button1'>Tab 1</button></body></html>";
-var testPage2 = "data:text/html,<html id='html2'><body id='body2'><button id='button2'>Tab 2</button></body></html>";
-var testPage3 = "data:text/html,<html id='html3'><body id='body3' contenteditable='true'><button id='button3'>Tab 3</button></body></html>";
-
-var fm = Services.focus;
-
-function* expectFocusOnF6(backward, expectedDocument, expectedElement, onContent, desc)
-{
- let focusChangedInChildResolver = null;
- let focusPromise = onContent ? new Promise(resolve => focusChangedInChildResolver = resolve) :
- BrowserTestUtils.waitForEvent(window, "focus", true);
-
- function focusChangedListener(msg) {
- let expected = expectedDocument;
- if (!expectedElement.startsWith("html")) {
- expected += "," + expectedElement;
- }
-
- is(msg.data.details, expected, desc + " child focus matches");
- focusChangedInChildResolver();
- }
-
- if (onContent) {
- messageManager.addMessageListener("BrowserTest:FocusChanged", focusChangedListener);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, { expectedElementId: expectedElement }, function* (arg) {
- let contentExpectedElement = content.document.getElementById(arg.expectedElementId);
- if (!contentExpectedElement) {
- // Element not found, so look in the child frames.
- for (let f = 0; f < content.frames.length; f++) {
- if (content.frames[f].document.getElementById(arg.expectedElementId)) {
- contentExpectedElement = content.frames[f].document;
- break;
- }
- }
- }
- else if (contentExpectedElement.localName == "html") {
- contentExpectedElement = contentExpectedElement.ownerDocument;
- }
-
- if (!contentExpectedElement) {
- sendSyncMessage("BrowserTest:FocusChanged",
- { details : "expected element " + arg.expectedElementId + " not found" });
- return;
- }
-
- contentExpectedElement.addEventListener("focus", function focusReceived() {
- contentExpectedElement.removeEventListener("focus", focusReceived, true);
-
- const contentFM = Components.classes["@mozilla.org/focus-manager;1"].
- getService(Components.interfaces.nsIFocusManager);
- let details = contentFM.focusedWindow.document.documentElement.id;
- if (contentFM.focusedElement) {
- details += "," + contentFM.focusedElement.id;
- }
-
- sendSyncMessage("BrowserTest:FocusChanged", { details : details });
- }, true);
- });
- }
-
- EventUtils.synthesizeKey("VK_F6", { shiftKey: backward });
- yield focusPromise;
-
- if (typeof expectedElement == "string") {
- expectedElement = fm.focusedWindow.document.getElementById(expectedElement);
- }
-
- if (gMultiProcessBrowser && onContent) {
- expectedDocument = "main-window";
- expectedElement = gBrowser.selectedBrowser;
- }
-
- is(fm.focusedWindow.document.documentElement.id, expectedDocument, desc + " document matches");
- is(fm.focusedElement, expectedElement, desc + " element matches");
-
- if (onContent) {
- messageManager.removeMessageListener("BrowserTest:FocusChanged", focusChangedListener);
- }
-}
-
-// Load a page and navigate between it and the chrome window.
-add_task(function* ()
-{
- let page1Promise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.selectedBrowser.loadURI(testPage1);
- yield page1Promise;
-
- // When the urlbar is focused, pressing F6 should focus the root of the content page.
- gURLBar.focus();
- yield* expectFocusOnF6(false, "html1", "html1",
- true, "basic focus content page");
-
- // When the content is focused, pressing F6 should focus the urlbar.
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "basic focus content page urlbar");
-
- // When a button in content is focused, pressing F6 should focus the urlbar.
- yield* expectFocusOnF6(false, "html1", "html1",
- true, "basic focus content page with button focused");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* () {
- return content.document.getElementById("button1").focus();
- });
-
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "basic focus content page with button focused urlbar");
-
- // The document root should be focused, not the button
- yield* expectFocusOnF6(false, "html1", "html1",
- true, "basic focus again content page with button focused");
-
- // Check to ensure that the root element is focused
- yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* () {
- Assert.ok(content.document.activeElement == content.document.documentElement,
- "basic focus again content page with button focused child root is focused");
- });
-});
-
-// Open a second tab. Document focus should skip the background tab.
-add_task(function* ()
-{
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage2);
-
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "basic focus content page and second tab urlbar");
- yield* expectFocusOnF6(false, "html2", "html2",
- true, "basic focus content page with second tab");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-// Shift+F6 should navigate backwards. There's only one document here so the effect
-// is the same.
-add_task(function* ()
-{
- gURLBar.focus();
- yield* expectFocusOnF6(true, "html1", "html1",
- true, "back focus content page");
- yield* expectFocusOnF6(true, "main-window", gURLBar.inputField,
- false, "back focus content page urlbar");
-});
-
-// Open the sidebar and navigate between the sidebar, content and top-level window
-add_task(function* ()
-{
- let sidebar = document.getElementById("sidebar");
-
- let loadPromise = BrowserTestUtils.waitForEvent(sidebar, "load", true);
- SidebarUI.toggle('viewBookmarksSidebar');
- yield loadPromise;
-
-
- gURLBar.focus();
- yield* expectFocusOnF6(false, "bookmarksPanel",
- sidebar.contentDocument.getElementById("search-box").inputField,
- false, "focus with sidebar open sidebar");
- yield* expectFocusOnF6(false, "html1", "html1",
- true, "focus with sidebar open content");
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "focus with sidebar urlbar");
-
- // Now go backwards
- yield* expectFocusOnF6(true, "html1", "html1",
- true, "back focus with sidebar open content");
- yield* expectFocusOnF6(true, "bookmarksPanel",
- sidebar.contentDocument.getElementById("search-box").inputField,
- false, "back focus with sidebar open sidebar");
- yield* expectFocusOnF6(true, "main-window", gURLBar.inputField,
- false, "back focus with sidebar urlbar");
-
- SidebarUI.toggle('viewBookmarksSidebar');
-});
-
-// Navigate when the downloads panel is open
-add_task(function* ()
-{
- yield pushPrefs(["accessibility.tabfocus", 7]);
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown", true);
- EventUtils.synthesizeMouseAtCenter(document.getElementById("downloads-button"), { });
- yield popupShownPromise;
-
- gURLBar.focus();
- yield* expectFocusOnF6(false, "main-window", document.getElementById("downloadsHistory"),
- false, "focus with downloads panel open panel");
- yield* expectFocusOnF6(false, "html1", "html1",
- true, "focus with downloads panel open");
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "focus downloads panel open urlbar");
-
- // Now go backwards
- yield* expectFocusOnF6(true, "html1", "html1",
- true, "back focus with downloads panel open");
- yield* expectFocusOnF6(true, "main-window", document.getElementById("downloadsHistory"),
- false, "back focus with downloads panel open");
- yield* expectFocusOnF6(true, "main-window", gURLBar.inputField,
- false, "back focus downloads panel open urlbar");
-
- let downloadsPopup = document.getElementById("downloadsPanel");
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(downloadsPopup, "popuphidden", true);
- downloadsPopup.hidePopup();
- yield popupHiddenPromise;
-});
-
-// Navigation with a contenteditable body
-add_task(function* ()
-{
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage3);
-
- // The body should be focused when it is editable, not the root.
- gURLBar.focus();
- yield* expectFocusOnF6(false, "html3", "body3",
- true, "focus with contenteditable body");
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "focus with contenteditable body urlbar");
-
- // Now go backwards
-
- yield* expectFocusOnF6(false, "html3", "body3",
- true, "back focus with contenteditable body");
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "back focus with contenteditable body urlbar");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-// Navigation with a frameset loaded
-add_task(function* ()
-{
- yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/base/content/test/general/file_documentnavigation_frameset.html");
-
- gURLBar.focus();
- yield* expectFocusOnF6(false, "htmlframe1", "htmlframe1",
- true, "focus on frameset frame 0");
- yield* expectFocusOnF6(false, "htmlframe2", "htmlframe2",
- true, "focus on frameset frame 1");
- yield* expectFocusOnF6(false, "htmlframe3", "htmlframe3",
- true, "focus on frameset frame 2");
- yield* expectFocusOnF6(false, "htmlframe4", "htmlframe4",
- true, "focus on frameset frame 3");
- yield* expectFocusOnF6(false, "main-window", gURLBar.inputField,
- false, "focus on frameset frame urlbar");
-
- yield* expectFocusOnF6(true, "htmlframe4", "htmlframe4",
- true, "back focus on frameset frame 3");
- yield* expectFocusOnF6(true, "htmlframe3", "htmlframe3",
- true, "back focus on frameset frame 2");
- yield* expectFocusOnF6(true, "htmlframe2", "htmlframe2",
- true, "back focus on frameset frame 1");
- yield* expectFocusOnF6(true, "htmlframe1", "htmlframe1",
- true, "back focus on frameset frame 0");
- yield* expectFocusOnF6(true, "main-window", gURLBar.inputField,
- false, "back focus on frameset frame urlbar");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-// XXXndeakin add tests for browsers inside of panels
diff --git a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js
deleted file mode 100644
index 054fb3cc0..000000000
--- a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js
+++ /dev/null
@@ -1,221 +0,0 @@
-"use strict";
-
-var gMessageManager;
-
-function frameScript() {
- addMessageListener("Test:RequestFullscreen", () => {
- content.document.body.requestFullscreen();
- });
- addMessageListener("Test:ExitFullscreen", () => {
- content.document.exitFullscreen();
- });
- addMessageListener("Test:QueryFullscreenState", () => {
- sendAsyncMessage("Test:FullscreenState", {
- inDOMFullscreen: !!content.document.fullscreenElement,
- inFullscreen: content.fullScreen
- });
- });
- content.document.addEventListener("fullscreenchange", () => {
- sendAsyncMessage("Test:FullscreenChanged", {
- inDOMFullscreen: !!content.document.fullscreenElement,
- inFullscreen: content.fullScreen
- });
- });
- function waitUntilActive() {
- let doc = content.document;
- if (doc.docShell.isActive && doc.hasFocus()) {
- sendAsyncMessage("Test:Activated");
- } else {
- setTimeout(waitUntilActive, 10);
- }
- }
- waitUntilActive();
-}
-
-function listenOneMessage(aMsg, aListener) {
- function listener({ data }) {
- gMessageManager.removeMessageListener(aMsg, listener);
- aListener(data);
- }
- gMessageManager.addMessageListener(aMsg, listener);
-}
-
-function listenOneEvent(aEvent, aListener) {
- function listener(evt) {
- removeEventListener(aEvent, listener);
- aListener(evt);
- }
- addEventListener(aEvent, listener);
-}
-
-function queryFullscreenState() {
- return new Promise(resolve => {
- listenOneMessage("Test:FullscreenState", resolve);
- gMessageManager.sendAsyncMessage("Test:QueryFullscreenState");
- });
-}
-
-function captureUnexpectedFullscreenChange() {
- ok(false, "catched an unexpected fullscreen change");
-}
-
-const FS_CHANGE_DOM = 1 << 0;
-const FS_CHANGE_SIZE = 1 << 1;
-const FS_CHANGE_BOTH = FS_CHANGE_DOM | FS_CHANGE_SIZE;
-
-function waitForFullscreenChanges(aFlags) {
- return new Promise(resolve => {
- let fullscreenData = null;
- let sizemodeChanged = false;
- function tryResolve() {
- if ((!(aFlags & FS_CHANGE_DOM) || fullscreenData) &&
- (!(aFlags & FS_CHANGE_SIZE) || sizemodeChanged)) {
- if (!fullscreenData) {
- queryFullscreenState().then(resolve);
- } else {
- resolve(fullscreenData);
- }
- }
- }
- if (aFlags & FS_CHANGE_SIZE) {
- listenOneEvent("sizemodechange", () => {
- sizemodeChanged = true;
- tryResolve();
- });
- }
- if (aFlags & FS_CHANGE_DOM) {
- gMessageManager.removeMessageListener(
- "Test:FullscreenChanged", captureUnexpectedFullscreenChange);
- listenOneMessage("Test:FullscreenChanged", data => {
- gMessageManager.addMessageListener(
- "Test:FullscreenChanged", captureUnexpectedFullscreenChange);
- fullscreenData = data;
- tryResolve();
- });
- }
- });
-}
-
-var gTests = [
- {
- desc: "document method",
- affectsFullscreenMode: false,
- exitFunc: () => {
- gMessageManager.sendAsyncMessage("Test:ExitFullscreen");
- }
- },
- {
- desc: "escape key",
- affectsFullscreenMode: false,
- exitFunc: () => {
- executeSoon(() => EventUtils.synthesizeKey("VK_ESCAPE", {}));
- }
- },
- {
- desc: "F11 key",
- affectsFullscreenMode: true,
- exitFunc: function () {
- executeSoon(() => EventUtils.synthesizeKey("VK_F11", {}));
- }
- }
-];
-
-function checkState(expectedStates, contentStates) {
- is(contentStates.inDOMFullscreen, expectedStates.inDOMFullscreen,
- "The DOM fullscreen state of the content should match");
- // TODO window.fullScreen is not updated as soon as the fullscreen
- // state flips in child process, hence checking it could cause
- // anonying intermittent failure. As we just want to confirm the
- // fullscreen state of the browser window, we can just check the
- // that on the chrome window below.
- // is(contentStates.inFullscreen, expectedStates.inFullscreen,
- // "The fullscreen state of the content should match");
- is(!!document.fullscreenElement, expectedStates.inDOMFullscreen,
- "The DOM fullscreen state of the chrome should match");
- is(window.fullScreen, expectedStates.inFullscreen,
- "The fullscreen state of the chrome should match");
-}
-
-const kPage = "http://example.org/browser/browser/" +
- "base/content/test/general/dummy_page.html";
-
-add_task(function* () {
- yield pushPrefs(
- ["full-screen-api.transition-duration.enter", "0 0"],
- ["full-screen-api.transition-duration.leave", "0 0"]);
-
- let tab = gBrowser.addTab(kPage);
- let browser = tab.linkedBrowser;
- gBrowser.selectedTab = tab;
- yield waitForDocLoadComplete();
-
- registerCleanupFunction(() => {
- if (browser.contentWindow.fullScreen) {
- BrowserFullScreen();
- }
- gBrowser.removeTab(tab);
- });
-
- gMessageManager = browser.messageManager;
- gMessageManager.loadFrameScript(
- "data:,(" + frameScript.toString() + ")();", false);
- gMessageManager.addMessageListener(
- "Test:FullscreenChanged", captureUnexpectedFullscreenChange);
-
- // Wait for the document being activated, so that
- // fullscreen request won't be denied.
- yield new Promise(resolve => listenOneMessage("Test:Activated", resolve));
-
- for (let test of gTests) {
- let contentStates;
- info("Testing exit DOM fullscreen via " + test.desc);
-
- contentStates = yield queryFullscreenState();
- checkState({inDOMFullscreen: false, inFullscreen: false}, contentStates);
-
- /* DOM fullscreen without fullscreen mode */
-
- info("> Enter DOM fullscreen");
- gMessageManager.sendAsyncMessage("Test:RequestFullscreen");
- contentStates = yield waitForFullscreenChanges(FS_CHANGE_BOTH);
- checkState({inDOMFullscreen: true, inFullscreen: true}, contentStates);
-
- info("> Exit DOM fullscreen");
- test.exitFunc();
- contentStates = yield waitForFullscreenChanges(FS_CHANGE_BOTH);
- checkState({inDOMFullscreen: false, inFullscreen: false}, contentStates);
-
- /* DOM fullscreen with fullscreen mode */
-
- info("> Enter fullscreen mode");
- // Need to be asynchronous because sizemodechange event could be
- // dispatched synchronously, which would cause the event listener
- // miss that event and wait infinitely.
- executeSoon(() => BrowserFullScreen());
- contentStates = yield waitForFullscreenChanges(FS_CHANGE_SIZE);
- checkState({inDOMFullscreen: false, inFullscreen: true}, contentStates);
-
- info("> Enter DOM fullscreen in fullscreen mode");
- gMessageManager.sendAsyncMessage("Test:RequestFullscreen");
- contentStates = yield waitForFullscreenChanges(FS_CHANGE_DOM);
- checkState({inDOMFullscreen: true, inFullscreen: true}, contentStates);
-
- info("> Exit DOM fullscreen in fullscreen mode");
- test.exitFunc();
- contentStates = yield waitForFullscreenChanges(
- test.affectsFullscreenMode ? FS_CHANGE_BOTH : FS_CHANGE_DOM);
- checkState({
- inDOMFullscreen: false,
- inFullscreen: !test.affectsFullscreenMode
- }, contentStates);
-
- /* Cleanup */
-
- // Exit fullscreen mode if we are still in
- if (window.fullScreen) {
- info("> Cleanup");
- executeSoon(() => BrowserFullScreen());
- yield waitForFullscreenChanges(FS_CHANGE_SIZE);
- }
- }
-});
diff --git a/browser/base/content/test/general/browser_double_close_tab.js b/browser/base/content/test/general/browser_double_close_tab.js
deleted file mode 100644
index 29242c3f9..000000000
--- a/browser/base/content/test/general/browser_double_close_tab.js
+++ /dev/null
@@ -1,80 +0,0 @@
-"use strict";
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/base/content/test/general/file_double_close_tab.html";
-var testTab;
-
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
-
-function waitForDialog(callback) {
- function onTabModalDialogLoaded(node) {
- Services.obs.removeObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded");
- callback(node);
- }
-
- // Listen for the dialog being created
- Services.obs.addObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded", false);
-}
-
-function waitForDialogDestroyed(node, callback) {
- // Now listen for the dialog going away again...
- let observer = new MutationObserver(function(muts) {
- if (!node.parentNode) {
- ok(true, "Dialog is gone");
- done();
- }
- });
- observer.observe(node.parentNode, {childList: true});
- let failureTimeout = setTimeout(function() {
- ok(false, "Dialog should have been destroyed");
- done();
- }, 10000);
-
- function done() {
- clearTimeout(failureTimeout);
- observer.disconnect();
- observer = null;
- callback();
- }
-}
-
-add_task(function*() {
- testTab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(testTab, TEST_PAGE);
- // XXXgijs the reason this has nesting and callbacks rather than promises is
- // that DOM promises resolve on the next tick. So they're scheduled
- // in an event queue. So when we spin a new event queue for a modal dialog...
- // everything gets messed up and the promise's .then callbacks never get
- // called, despite resolve() being called just fine.
- yield new Promise(resolveOuter => {
- waitForDialog(dialogNode => {
- waitForDialogDestroyed(dialogNode, () => {
- let doCompletion = () => setTimeout(resolveOuter, 0);
- info("Now checking if dialog is destroyed");
- ok(!dialogNode.parentNode, "onbeforeunload dialog should be gone.");
- if (dialogNode.parentNode) {
- // Failed to remove onbeforeunload dialog, so do it ourselves:
- let leaveBtn = dialogNode.ui.button0;
- waitForDialogDestroyed(dialogNode, doCompletion);
- EventUtils.synthesizeMouseAtCenter(leaveBtn, {});
- return;
- }
- doCompletion();
- });
- // Click again:
- document.getAnonymousElementByAttribute(testTab, "anonid", "close-button").click();
- });
- // Click once:
- document.getAnonymousElementByAttribute(testTab, "anonid", "close-button").click();
- });
- yield promiseWaitForCondition(() => !testTab.parentNode);
- ok(!testTab.parentNode, "Tab should be closed completely");
-});
-
-registerCleanupFunction(function() {
- if (testTab.parentNode) {
- // Remove the handler, or closing this tab will prove tricky:
- try {
- testTab.linkedBrowser.contentWindow.onbeforeunload = null;
- } catch (ex) {}
- gBrowser.removeTab(testTab);
- }
-});
diff --git a/browser/base/content/test/general/browser_drag.js b/browser/base/content/test/general/browser_drag.js
deleted file mode 100644
index 64ad19bde..000000000
--- a/browser/base/content/test/general/browser_drag.js
+++ /dev/null
@@ -1,45 +0,0 @@
-function test()
-{
- waitForExplicitFinish();
-
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- // ---- Test dragging the proxy icon ---
- var value = content.location.href;
- var urlString = value + "\n" + content.document.title;
- var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
- var expected = [ [
- { type : "text/x-moz-url",
- data : urlString },
- { type : "text/uri-list",
- data : value },
- { type : "text/plain",
- data : value },
- { type : "text/html",
- data : htmlString }
- ] ];
- // set the valid attribute so dropping is allowed
- var oldstate = gURLBar.getAttribute("pageproxystate");
- gURLBar.setAttribute("pageproxystate", "valid");
- var dt = EventUtils.synthesizeDragStart(document.getElementById("identity-box"), expected);
- is(dt, null, "drag on proxy icon");
- gURLBar.setAttribute("pageproxystate", oldstate);
- // Now, the identity information panel is opened by the proxy icon click.
- // We need to close it for next tests.
- EventUtils.synthesizeKey("VK_ESCAPE", {}, window);
-
- // now test dragging onto a tab
- var tab = gBrowser.addTab("about:blank", {skipAnimation: true});
- var browser = gBrowser.getBrowserForTab(tab);
-
- browser.addEventListener("load", function () {
- is(browser.contentWindow.location, "http://mochi.test:8888/", "drop on tab");
- gBrowser.removeTab(tab);
- finish();
- }, true);
-
- EventUtils.synthesizeDrop(tab, tab, [[{type: "text/uri-list", data: "http://mochi.test:8888/"}]], "copy", window);
-}
diff --git a/browser/base/content/test/general/browser_duplicateIDs.js b/browser/base/content/test/general/browser_duplicateIDs.js
deleted file mode 100644
index 38fc17820..000000000
--- a/browser/base/content/test/general/browser_duplicateIDs.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function test() {
- var ids = {};
- Array.forEach(document.querySelectorAll("[id]"), function (node) {
- var id = node.id;
- ok(!(id in ids), id + " should be unique");
- ids[id] = null;
- });
-}
diff --git a/browser/base/content/test/general/browser_e10s_about_process.js b/browser/base/content/test/general/browser_e10s_about_process.js
deleted file mode 100644
index 2b4816754..000000000
--- a/browser/base/content/test/general/browser_e10s_about_process.js
+++ /dev/null
@@ -1,114 +0,0 @@
-const CHROME_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-const CONTENT_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
-
-const CHROME = {
- id: "cb34538a-d9da-40f3-b61a-069f0b2cb9fb",
- path: "test-chrome",
- flags: 0,
-}
-const CANREMOTE = {
- id: "2480d3e1-9ce4-4b84-8ae3-910b9a95cbb3",
- path: "test-allowremote",
- flags: Ci.nsIAboutModule.URI_CAN_LOAD_IN_CHILD,
-}
-const MUSTREMOTE = {
- id: "f849cee5-e13e-44d2-981d-0fb3884aaead",
- path: "test-mustremote",
- flags: Ci.nsIAboutModule.URI_MUST_LOAD_IN_CHILD,
-}
-
-const TEST_MODULES = [
- CHROME,
- CANREMOTE,
- MUSTREMOTE
-]
-
-function AboutModule() {
-}
-
-AboutModule.prototype = {
- newChannel: function(aURI, aLoadInfo) {
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- },
-
- getURIFlags: function(aURI) {
- for (let module of TEST_MODULES) {
- if (aURI.path.startsWith(module.path)) {
- return module.flags;
- }
- }
-
- ok(false, "Called getURIFlags for an unknown page " + aURI.spec);
- return 0;
- },
-
- getIndexedDBOriginPostfix: function(aURI) {
- return null;
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule])
-};
-
-var AboutModuleFactory = {
- createInstance: function(aOuter, aIID) {
- if (aOuter)
- throw Components.results.NS_ERROR_NO_AGGREGATION;
- return new AboutModule().QueryInterface(aIID);
- },
-
- lockFactory: function(aLock) {
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory])
-};
-
-add_task(function* init() {
- let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
- for (let module of TEST_MODULES) {
- registrar.registerFactory(Components.ID(module.id), "",
- "@mozilla.org/network/protocol/about;1?what=" + module.path,
- AboutModuleFactory);
- }
-});
-
-registerCleanupFunction(() => {
- let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
- for (let module of TEST_MODULES) {
- registrar.unregisterFactory(Components.ID(module.id), AboutModuleFactory);
- }
-});
-
-function test_url(url, chromeResult, contentResult) {
- is(E10SUtils.canLoadURIInProcess(url, CHROME_PROCESS),
- chromeResult, "Check URL in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url, CONTENT_PROCESS),
- contentResult, "Check URL in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "#foo", CHROME_PROCESS),
- chromeResult, "Check URL with ref in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "#foo", CONTENT_PROCESS),
- contentResult, "Check URL with ref in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "?foo", CHROME_PROCESS),
- chromeResult, "Check URL with query in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "?foo", CONTENT_PROCESS),
- contentResult, "Check URL with query in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "?foo#bar", CHROME_PROCESS),
- chromeResult, "Check URL with query and ref in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "?foo#bar", CONTENT_PROCESS),
- contentResult, "Check URL with query and ref in content process.");
-}
-
-add_task(function* test_chrome() {
- test_url("about:" + CHROME.path, true, false);
-});
-
-add_task(function* test_any() {
- test_url("about:" + CANREMOTE.path, true, true);
-});
-
-add_task(function* test_remote() {
- test_url("about:" + MUSTREMOTE.path, false, true);
-});
diff --git a/browser/base/content/test/general/browser_e10s_chrome_process.js b/browser/base/content/test/general/browser_e10s_chrome_process.js
deleted file mode 100644
index 0726447ce..000000000
--- a/browser/base/content/test/general/browser_e10s_chrome_process.js
+++ /dev/null
@@ -1,150 +0,0 @@
-// Returns a function suitable for add_task which loads startURL, runs
-// transitionTask and waits for endURL to load, checking that the URLs were
-// loaded in the correct process.
-function makeTest(name, startURL, startProcessIsRemote, endURL, endProcessIsRemote, transitionTask) {
- return function*() {
- info("Running test " + name + ", " + transitionTask.name);
- let browser = gBrowser.selectedBrowser;
-
- // In non-e10s nothing should be remote
- if (!gMultiProcessBrowser) {
- startProcessIsRemote = false;
- endProcessIsRemote = false;
- }
-
- // Load the initial URL and make sure we are in the right initial process
- info("Loading initial URL");
- browser.loadURI(startURL);
- yield waitForDocLoadComplete();
-
- is(browser.currentURI.spec, startURL, "Shouldn't have been redirected");
- is(browser.isRemoteBrowser, startProcessIsRemote, "Should be displayed in the right process");
-
- let docLoadedPromise = waitForDocLoadComplete();
- let asyncTask = Task.async(transitionTask);
- let expectSyncChange = yield asyncTask(browser, endURL);
- if (expectSyncChange) {
- is(browser.isRemoteBrowser, endProcessIsRemote, "Should have switched to the right process synchronously");
- }
- yield docLoadedPromise;
-
- is(browser.currentURI.spec, endURL, "Should have made it to the final URL");
- is(browser.isRemoteBrowser, endProcessIsRemote, "Should be displayed in the right process");
- }
-}
-
-const CHROME_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-const CONTENT_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
-const PATH = (getRootDirectory(gTestPath) + "test_process_flags_chrome.html").replace("chrome://mochitests", "");
-
-const CHROME = "chrome://mochitests" + PATH;
-const CANREMOTE = "chrome://mochitests-any" + PATH;
-const MUSTREMOTE = "chrome://mochitests-content" + PATH;
-
-add_task(function* init() {
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
-});
-
-registerCleanupFunction(() => {
- gBrowser.removeCurrentTab();
-});
-
-function test_url(url, chromeResult, contentResult) {
- is(E10SUtils.canLoadURIInProcess(url, CHROME_PROCESS),
- chromeResult, "Check URL in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url, CONTENT_PROCESS),
- contentResult, "Check URL in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "#foo", CHROME_PROCESS),
- chromeResult, "Check URL with ref in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "#foo", CONTENT_PROCESS),
- contentResult, "Check URL with ref in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "?foo", CHROME_PROCESS),
- chromeResult, "Check URL with query in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "?foo", CONTENT_PROCESS),
- contentResult, "Check URL with query in content process.");
-
- is(E10SUtils.canLoadURIInProcess(url + "?foo#bar", CHROME_PROCESS),
- chromeResult, "Check URL with query and ref in chrome process.");
- is(E10SUtils.canLoadURIInProcess(url + "?foo#bar", CONTENT_PROCESS),
- contentResult, "Check URL with query and ref in content process.");
-}
-
-add_task(function* test_chrome() {
- test_url(CHROME, true, false);
-});
-
-add_task(function* test_any() {
- test_url(CANREMOTE, true, true);
-});
-
-add_task(function* test_remote() {
- test_url(MUSTREMOTE, false, true);
-});
-
-// The set of page transitions
-var TESTS = [
- [
- "chrome -> chrome",
- CHROME, false,
- CHROME, false,
- ],
- [
- "chrome -> canremote",
- CHROME, false,
- CANREMOTE, false,
- ],
- [
- "chrome -> mustremote",
- CHROME, false,
- MUSTREMOTE, true,
- ],
- [
- "remote -> chrome",
- MUSTREMOTE, true,
- CHROME, false,
- ],
- [
- "remote -> canremote",
- MUSTREMOTE, true,
- CANREMOTE, true,
- ],
- [
- "remote -> mustremote",
- MUSTREMOTE, true,
- MUSTREMOTE, true,
- ],
-];
-
-// The different ways to transition from one page to another
-var TRANSITIONS = [
-// Loads the new page by calling browser.loadURI directly
-function* loadURI(browser, uri) {
- info("Calling browser.loadURI");
- yield BrowserTestUtils.loadURI(browser, uri);
- return true;
-},
-
-// Loads the new page by finding a link with the right href in the document and
-// clicking it
-function* clickLink(browser, uri) {
- info("Clicking link");
-
- function frame_script(frameUri) {
- let link = content.document.querySelector("a[href='" + frameUri + "']");
- link.click();
- }
-
- browser.messageManager.loadFrameScript("data:,(" + frame_script.toString() + ")(" + JSON.stringify(uri) + ");", false);
-
- return false;
-},
-];
-
-// Creates a set of test tasks, one for each combination of TESTS and TRANSITIONS.
-for (let test of TESTS) {
- for (let transition of TRANSITIONS) {
- add_task(makeTest(...test, transition));
- }
-}
diff --git a/browser/base/content/test/general/browser_e10s_javascript.js b/browser/base/content/test/general/browser_e10s_javascript.js
deleted file mode 100644
index 90e847b09..000000000
--- a/browser/base/content/test/general/browser_e10s_javascript.js
+++ /dev/null
@@ -1,11 +0,0 @@
-const CHROME_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-const CONTENT_PROCESS = Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
-
-add_task(function*() {
- let url = "javascript:dosomething()";
-
- ok(E10SUtils.canLoadURIInProcess(url, CHROME_PROCESS),
- "Check URL in chrome process.");
- ok(E10SUtils.canLoadURIInProcess(url, CONTENT_PROCESS),
- "Check URL in content process.");
-});
diff --git a/browser/base/content/test/general/browser_e10s_switchbrowser.js b/browser/base/content/test/general/browser_e10s_switchbrowser.js
deleted file mode 100644
index e6134f749..000000000
--- a/browser/base/content/test/general/browser_e10s_switchbrowser.js
+++ /dev/null
@@ -1,261 +0,0 @@
-requestLongerTimeout(2);
-
-const DUMMY_PATH = "browser/browser/base/content/test/general/dummy_page.html";
-
-const gExpectedHistory = {
- index: -1,
- entries: []
-};
-
-function get_remote_history(browser) {
- function frame_script() {
- let webNav = docShell.QueryInterface(Components.interfaces.nsIWebNavigation);
- let sessionHistory = webNav.sessionHistory;
- let result = {
- index: sessionHistory.index,
- entries: []
- };
-
- for (let i = 0; i < sessionHistory.count; i++) {
- let entry = sessionHistory.getEntryAtIndex(i, false);
- result.entries.push({
- uri: entry.URI.spec,
- title: entry.title
- });
- }
-
- sendAsyncMessage("Test:History", result);
- }
-
- return new Promise(resolve => {
- browser.messageManager.addMessageListener("Test:History", function listener({data}) {
- browser.messageManager.removeMessageListener("Test:History", listener);
- resolve(data);
- });
-
- browser.messageManager.loadFrameScript("data:,(" + frame_script.toString() + ")();", true);
- });
-}
-
-var check_history = Task.async(function*() {
- let sessionHistory = yield get_remote_history(gBrowser.selectedBrowser);
-
- let count = sessionHistory.entries.length;
- is(count, gExpectedHistory.entries.length, "Should have the right number of history entries");
- is(sessionHistory.index, gExpectedHistory.index, "Should have the right history index");
-
- for (let i = 0; i < count; i++) {
- let entry = sessionHistory.entries[i];
- is(entry.uri, gExpectedHistory.entries[i].uri, "Should have the right URI");
- is(entry.title, gExpectedHistory.entries[i].title, "Should have the right title");
- }
-});
-
-function clear_history() {
- gExpectedHistory.index = -1;
- gExpectedHistory.entries = [];
-}
-
-// Waits for a load and updates the known history
-var waitForLoad = Task.async(function*(uri) {
- info("Loading " + uri);
- // Longwinded but this ensures we don't just shortcut to LoadInNewProcess
- gBrowser.selectedBrowser.webNavigation.loadURI(uri, Ci.nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
-
- yield waitForDocLoadComplete();
- gExpectedHistory.index++;
- gExpectedHistory.entries.push({
- uri: gBrowser.currentURI.spec,
- title: gBrowser.contentTitle
- });
-});
-
-// Waits for a load and updates the known history
-var waitForLoadWithFlags = Task.async(function*(uri, flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE) {
- info("Loading " + uri + " flags = " + flags);
- gBrowser.selectedBrowser.loadURIWithFlags(uri, flags, null, null, null);
-
- yield waitForDocLoadComplete();
- if (!(flags & Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY)) {
-
- if (flags & Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY) {
- gExpectedHistory.entries.pop();
- }
- else {
- gExpectedHistory.index++;
- }
-
- gExpectedHistory.entries.push({
- uri: gBrowser.currentURI.spec,
- title: gBrowser.contentTitle
- });
- }
-});
-
-var back = Task.async(function*() {
- info("Going back");
- gBrowser.goBack();
- yield waitForDocLoadComplete();
- gExpectedHistory.index--;
-});
-
-var forward = Task.async(function*() {
- info("Going forward");
- gBrowser.goForward();
- yield waitForDocLoadComplete();
- gExpectedHistory.index++;
-});
-
-// Tests that navigating from a page that should be in the remote process and
-// a page that should be in the main process works and retains history
-add_task(function* test_navigation() {
- let expectedRemote = gMultiProcessBrowser;
-
- info("1");
- // Create a tab and load a remote page in it
- gBrowser.selectedTab = gBrowser.addTab("about:blank", {skipAnimation: true});
- let {permanentKey} = gBrowser.selectedBrowser;
- yield waitForLoad("http://example.org/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- info("2");
- // Load another page
- yield waitForLoad("http://example.com/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("3");
- // Load a non-remote page
- yield waitForLoad("about:robots");
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("4");
- // Load a remote page
- yield waitForLoad("http://example.org/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("5");
- yield back();
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("6");
- yield back();
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("7");
- yield forward();
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("8");
- yield forward();
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("9");
- yield back();
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("10");
- // Load a new remote page, this should replace the last history entry
- gExpectedHistory.entries.splice(gExpectedHistory.entries.length - 1, 1);
- yield waitForLoad("http://example.com/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
- yield check_history();
-
- info("11");
- gBrowser.removeCurrentTab();
- clear_history();
-});
-
-// Tests that calling gBrowser.loadURI or browser.loadURI to load a page in a
-// different process updates the browser synchronously
-add_task(function* test_synchronous() {
- let expectedRemote = gMultiProcessBrowser;
-
- info("1");
- // Create a tab and load a remote page in it
- gBrowser.selectedTab = gBrowser.addTab("about:blank", {skipAnimation: true});
- let {permanentKey} = gBrowser.selectedBrowser;
- yield waitForLoad("http://example.org/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- info("2");
- // Load another page
- info("Loading about:robots");
- yield BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "about:robots");
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- yield waitForDocLoadComplete();
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- info("3");
- // Load the remote page again
- info("Loading http://example.org/" + DUMMY_PATH);
- yield BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "http://example.org/" + DUMMY_PATH);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- yield waitForDocLoadComplete();
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- is(gBrowser.selectedBrowser.permanentKey, permanentKey, "browser.permanentKey is still the same");
-
- info("4");
- gBrowser.removeCurrentTab();
- clear_history();
-});
-
-// Tests that load flags are correctly passed through to the child process with
-// normal loads
-add_task(function* test_loadflags() {
- let expectedRemote = gMultiProcessBrowser;
-
- info("1");
- // Create a tab and load a remote page in it
- gBrowser.selectedTab = gBrowser.addTab("about:blank", {skipAnimation: true});
- yield waitForLoadWithFlags("about:robots");
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- yield check_history();
-
- info("2");
- // Load a page in the remote process with some custom flags
- yield waitForLoadWithFlags("http://example.com/" + DUMMY_PATH, Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- yield check_history();
-
- info("3");
- // Load a non-remote page
- yield waitForLoadWithFlags("about:robots");
- is(gBrowser.selectedBrowser.isRemoteBrowser, false, "Remote attribute should be correct");
- yield check_history();
-
- info("4");
- // Load another remote page
- yield waitForLoadWithFlags("http://example.org/" + DUMMY_PATH, Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY);
- is(gBrowser.selectedBrowser.isRemoteBrowser, expectedRemote, "Remote attribute should be correct");
- yield check_history();
-
- is(gExpectedHistory.entries.length, 2, "Should end with the right number of history entries");
-
- info("5");
- gBrowser.removeCurrentTab();
- clear_history();
-});
diff --git a/browser/base/content/test/general/browser_favicon_change.js b/browser/base/content/test/general/browser_favicon_change.js
deleted file mode 100644
index f6b0a2a42..000000000
--- a/browser/base/content/test/general/browser_favicon_change.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const TEST_URL = "http://mochi.test:8888/browser/browser/base/content/test/general/file_favicon_change.html"
-
-add_task(function*() {
- let extraTab = gBrowser.selectedTab = gBrowser.addTab();
- extraTab.linkedBrowser.loadURI(TEST_URL);
- let tabLoaded = BrowserTestUtils.browserLoaded(extraTab.linkedBrowser);
- let expectedFavicon = "http://example.org/one-icon";
- let haveChanged = new Promise.defer();
- let observer = new MutationObserver(function(mutations) {
- for (let mut of mutations) {
- if (mut.attributeName != "image") {
- continue;
- }
- let imageVal = extraTab.getAttribute("image").replace(/#.*$/, "");
- if (!imageVal) {
- // The value gets removed because it doesn't load.
- continue;
- }
- is(imageVal, expectedFavicon, "Favicon image should correspond to expected image.");
- haveChanged.resolve();
- }
- });
- observer.observe(extraTab, {attributes: true});
- yield tabLoaded;
- yield haveChanged.promise;
- haveChanged = new Promise.defer();
- expectedFavicon = "http://example.org/other-icon";
- ContentTask.spawn(extraTab.linkedBrowser, null, function() {
- let ev = new content.CustomEvent("PleaseChangeFavicon", {});
- content.dispatchEvent(ev);
- });
- yield haveChanged.promise;
- observer.disconnect();
- gBrowser.removeTab(extraTab);
-});
-
diff --git a/browser/base/content/test/general/browser_favicon_change_not_in_document.js b/browser/base/content/test/general/browser_favicon_change_not_in_document.js
deleted file mode 100644
index d14a1da32..000000000
--- a/browser/base/content/test/general/browser_favicon_change_not_in_document.js
+++ /dev/null
@@ -1,34 +0,0 @@
-"use strict";
-
-const TEST_URL = "http://mochi.test:8888/browser/browser/base/content/test/general/file_favicon_change_not_in_document.html"
-
-add_task(function*() {
- let extraTab = gBrowser.selectedTab = gBrowser.addTab();
- let tabLoaded = promiseTabLoaded(extraTab);
- extraTab.linkedBrowser.loadURI(TEST_URL);
- let expectedFavicon = "http://example.org/one-icon";
- let haveChanged = new Promise.defer();
- let observer = new MutationObserver(function(mutations) {
- for (let mut of mutations) {
- if (mut.attributeName != "image") {
- continue;
- }
- let imageVal = extraTab.getAttribute("image").replace(/#.*$/, "");
- if (!imageVal) {
- // The value gets removed because it doesn't load.
- continue;
- }
- is(imageVal, expectedFavicon, "Favicon image should correspond to expected image.");
- haveChanged.resolve();
- }
- });
- observer.observe(extraTab, {attributes: true});
- yield tabLoaded;
- expectedFavicon = "http://example.org/yet-another-icon";
- haveChanged = new Promise.defer();
- yield haveChanged.promise;
- observer.disconnect();
- gBrowser.removeTab(extraTab);
-});
-
-
diff --git a/browser/base/content/test/general/browser_feed_discovery.js b/browser/base/content/test/general/browser_feed_discovery.js
deleted file mode 100644
index 73dcef755..000000000
--- a/browser/base/content/test/general/browser_feed_discovery.js
+++ /dev/null
@@ -1,33 +0,0 @@
-const URL = "http://mochi.test:8888/browser/browser/base/content/test/general/feed_discovery.html"
-
-/** Test for Bug 377611 **/
-
-add_task(function* () {
- // Open a new tab.
- gBrowser.selectedTab = gBrowser.addTab(URL);
- registerCleanupFunction(() => gBrowser.removeCurrentTab());
-
- let browser = gBrowser.selectedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- let discovered = browser.feeds;
- ok(discovered.length > 0, "some feeds should be discovered");
-
- let feeds = {};
- for (let aFeed of discovered) {
- feeds[aFeed.href] = true;
- }
-
- yield ContentTask.spawn(browser, feeds, function* (contentFeeds) {
- for (let aLink of content.document.getElementsByTagName("link")) {
- // ignore real stylesheets, and anything without an href property
- if (aLink.type != "text/css" && aLink.href) {
- if (/bogus/i.test(aLink.title)) {
- ok(!contentFeeds[aLink.href], "don't discover " + aLink.href);
- } else {
- ok(contentFeeds[aLink.href], "should discover " + aLink.href);
- }
- }
- }
- });
-})
diff --git a/browser/base/content/test/general/browser_findbarClose.js b/browser/base/content/test/general/browser_findbarClose.js
deleted file mode 100644
index 53503073c..000000000
--- a/browser/base/content/test/general/browser_findbarClose.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests find bar auto-close behavior
-
-var newTab;
-
-add_task(function* findbar_test() {
- waitForExplicitFinish();
- newTab = gBrowser.addTab("about:blank");
-
- let promise = ContentTask.spawn(newTab.linkedBrowser, null, function* () {
- yield ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", false);
- });
- newTab.linkedBrowser.loadURI("http://example.com/browser/" +
- "browser/base/content/test/general/test_bug628179.html");
- yield promise;
-
- gFindBar.open();
-
- yield new ContentTask.spawn(newTab.linkedBrowser, null, function* () {
- let iframe = content.document.getElementById("iframe");
- let awaitLoad = ContentTaskUtils.waitForEvent(iframe, "load", false);
- iframe.src = "http://example.org/";
- yield awaitLoad;
- });
-
- ok(!gFindBar.hidden, "the Find bar isn't hidden after the location of a " +
- "subdocument changes");
-
- gFindBar.close();
- gBrowser.removeTab(newTab);
- finish();
-});
-
diff --git a/browser/base/content/test/general/browser_focusonkeydown.js b/browser/base/content/test/general/browser_focusonkeydown.js
deleted file mode 100644
index 5b3337203..000000000
--- a/browser/base/content/test/general/browser_focusonkeydown.js
+++ /dev/null
@@ -1,26 +0,0 @@
-add_task(function *()
-{
- let keyUps = 0;
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/html,<body>");
-
- gURLBar.focus();
-
- window.addEventListener("keyup", function countKeyUps(event) {
- window.removeEventListener("keyup", countKeyUps, true);
- if (event.originalTarget == gURLBar.inputField) {
- keyUps++;
- }
- }, true);
-
- gURLBar.addEventListener("keydown", function redirectFocus(event) {
- gURLBar.removeEventListener("keydown", redirectFocus, true);
- gBrowser.selectedBrowser.focus();
- }, true);
-
- EventUtils.synthesizeKey("v", { });
-
- is(keyUps, 1, "Key up fired at url bar");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_fullscreen-window-open.js b/browser/base/content/test/general/browser_fullscreen-window-open.js
deleted file mode 100644
index 2624b754a..000000000
--- a/browser/base/content/test/general/browser_fullscreen-window-open.js
+++ /dev/null
@@ -1,347 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-const PREF_DISABLE_OPEN_NEW_WINDOW = "browser.link.open_newwindow.disabled_in_fullscreen";
-const isOSX = (Services.appinfo.OS === "Darwin");
-
-const TEST_FILE = "file_fullscreen-window-open.html";
-const gHttpTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/",
- "http://127.0.0.1:8888/");
-
-function test () {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, true);
-
- let newTab = gBrowser.addTab(gHttpTestRoot + TEST_FILE);
- gBrowser.selectedTab = newTab;
-
- whenTabLoaded(newTab, function () {
- // Enter browser fullscreen mode.
- BrowserFullScreen();
-
- runNextTest();
- });
-}
-
-registerCleanupFunction(function() {
- // Exit browser fullscreen mode.
- BrowserFullScreen();
-
- gBrowser.removeCurrentTab();
-
- Services.prefs.clearUserPref(PREF_DISABLE_OPEN_NEW_WINDOW);
-});
-
-var gTests = [
- test_open,
- test_open_with_size,
- test_open_with_pos,
- test_open_with_outerSize,
- test_open_with_innerSize,
- test_open_with_dialog,
- test_open_when_open_new_window_by_pref,
- test_open_with_pref_to_disable_in_fullscreen,
- test_open_from_chrome,
-];
-
-function runNextTest () {
- let testCase = gTests.shift();
- if (testCase) {
- executeSoon(testCase);
- }
- else {
- finish();
- }
-}
-
-
-// Test for window.open() with no feature.
-function test_open() {
- waitForTabOpen({
- message: {
- title: "test_open",
- param: "",
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open() with width/height.
-function test_open_with_size() {
- waitForTabOpen({
- message: {
- title: "test_open_with_size",
- param: "width=400,height=400",
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open() with top/left.
-function test_open_with_pos() {
- waitForTabOpen({
- message: {
- title: "test_open_with_pos",
- param: "top=200,left=200",
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open() with outerWidth/Height.
-function test_open_with_outerSize() {
- let [outerWidth, outerHeight] = [window.outerWidth, window.outerHeight];
- waitForTabOpen({
- message: {
- title: "test_open_with_outerSize",
- param: "outerWidth=200,outerHeight=200",
- },
- successFn: function () {
- is(window.outerWidth, outerWidth, "Don't change window.outerWidth.");
- is(window.outerHeight, outerHeight, "Don't change window.outerHeight.");
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open() with innerWidth/Height.
-function test_open_with_innerSize() {
- let [innerWidth, innerHeight] = [window.innerWidth, window.innerHeight];
- waitForTabOpen({
- message: {
- title: "test_open_with_innerSize",
- param: "innerWidth=200,innerHeight=200",
- },
- successFn: function () {
- is(window.innerWidth, innerWidth, "Don't change window.innerWidth.");
- is(window.innerHeight, innerHeight, "Don't change window.innerHeight.");
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open() with dialog.
-function test_open_with_dialog() {
- waitForTabOpen({
- message: {
- title: "test_open_with_dialog",
- param: "dialog=yes",
- },
- finalizeFn: function () {},
- });
-}
-
-// Test for window.open()
-// when "browser.link.open_newwindow" is nsIBrowserDOMWindow.OPEN_NEWWINDOW
-function test_open_when_open_new_window_by_pref() {
- const PREF_NAME = "browser.link.open_newwindow";
- Services.prefs.setIntPref(PREF_NAME, Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW);
- is(Services.prefs.getIntPref(PREF_NAME), Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW,
- PREF_NAME + " is nsIBrowserDOMWindow.OPEN_NEWWINDOW at this time");
-
- waitForTabOpen({
- message: {
- title: "test_open_when_open_new_window_by_pref",
- param: "width=400,height=400",
- },
- finalizeFn: function () {
- Services.prefs.clearUserPref(PREF_NAME);
- },
- });
-}
-
-// Test for the pref, "browser.link.open_newwindow.disabled_in_fullscreen"
-function test_open_with_pref_to_disable_in_fullscreen() {
- Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, false);
-
- waitForWindowOpen({
- message: {
- title: "test_open_with_pref_disabled_in_fullscreen",
- param: "width=400,height=400",
- },
- finalizeFn: function () {
- Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, true);
- },
- });
-}
-
-
-// Test for window.open() called from chrome context.
-function test_open_from_chrome() {
- waitForWindowOpenFromChrome({
- message: {
- title: "test_open_from_chrome",
- param: "",
- },
- finalizeFn: function () {}
- });
-}
-
-function waitForTabOpen(aOptions) {
- let message = aOptions.message;
-
- if (!message.title) {
- ok(false, "Can't get message.title.");
- aOptions.finalizeFn();
- runNextTest();
- return;
- }
-
- info("Running test: " + message.title);
-
- let onTabOpen = function onTabOpen(aEvent) {
- gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen, true);
-
- let tab = aEvent.target;
- whenTabLoaded(tab, function () {
- is(tab.linkedBrowser.contentTitle, message.title,
- "Opened Tab is expected: " + message.title);
-
- if (aOptions.successFn) {
- aOptions.successFn();
- }
-
- gBrowser.removeTab(tab);
- finalize();
- });
- }
- gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen, true);
-
- let finalize = function () {
- aOptions.finalizeFn();
- info("Finished: " + message.title);
- runNextTest();
- };
-
- const URI = "data:text/html;charset=utf-8,<!DOCTYPE html><html><head><title>"+
- message.title +
- "<%2Ftitle><%2Fhead><body><%2Fbody><%2Fhtml>";
-
- executeWindowOpenInContent({
- uri: URI,
- title: message.title,
- option: message.param,
- });
-}
-
-
-function waitForWindowOpen(aOptions) {
- let message = aOptions.message;
- let url = aOptions.url || "about:blank";
-
- if (!message.title) {
- ok(false, "Can't get message.title");
- aOptions.finalizeFn();
- runNextTest();
- return;
- }
-
- info("Running test: " + message.title);
-
- let onFinalize = function () {
- aOptions.finalizeFn();
-
- info("Finished: " + message.title);
- runNextTest();
- };
-
- let listener = new WindowListener(message.title, getBrowserURL(), {
- onSuccess: aOptions.successFn,
- onFinalize: onFinalize,
- });
- Services.wm.addListener(listener);
-
- executeWindowOpenInContent({
- uri: url,
- title: message.title,
- option: message.param,
- });
-}
-
-function executeWindowOpenInContent(aParam) {
- ContentTask.spawn(gBrowser.selectedBrowser, JSON.stringify(aParam), function* (dataTestParam) {
- let testElm = content.document.getElementById("test");
- testElm.setAttribute("data-test-param", dataTestParam);
- testElm.click();
- });
-}
-
-function waitForWindowOpenFromChrome(aOptions) {
- let message = aOptions.message;
- let url = aOptions.url || "about:blank";
-
- if (!message.title) {
- ok(false, "Can't get message.title");
- aOptions.finalizeFn();
- runNextTest();
- return;
- }
-
- info("Running test: " + message.title);
-
- let onFinalize = function () {
- aOptions.finalizeFn();
-
- info("Finished: " + message.title);
- runNextTest();
- };
-
- let listener = new WindowListener(message.title, getBrowserURL(), {
- onSuccess: aOptions.successFn,
- onFinalize: onFinalize,
- });
- Services.wm.addListener(listener);
-
- window.open(url, message.title, message.option);
-}
-
-function WindowListener(aTitle, aUrl, aCallBackObj) {
- this.test_title = aTitle;
- this.test_url = aUrl;
- this.callback_onSuccess = aCallBackObj.onSuccess;
- this.callBack_onFinalize = aCallBackObj.onFinalize;
-}
-WindowListener.prototype = {
-
- test_title: null,
- test_url: null,
- callback_onSuccess: null,
- callBack_onFinalize: null,
-
- onOpenWindow: function(aXULWindow) {
- Services.wm.removeListener(this);
-
- let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- let onLoad = aEvent => {
- is(domwindow.document.location.href, this.test_url,
- "Opened Window is expected: "+ this.test_title);
- if (this.callback_onSuccess) {
- this.callback_onSuccess();
- }
-
- domwindow.removeEventListener("load", onLoad, true);
-
- // wait for trasition to fullscreen on OSX Lion later
- if (isOSX) {
- setTimeout(function() {
- domwindow.close();
- executeSoon(this.callBack_onFinalize);
- }.bind(this), 3000);
- }
- else {
- domwindow.close();
- executeSoon(this.callBack_onFinalize);
- }
- };
- domwindow.addEventListener("load", onLoad, true);
- },
- onCloseWindow: function(aXULWindow) {},
- onWindowTitleChange: function(aXULWindow, aNewTitle) {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIWindowMediatorListener,
- Ci.nsISupports]),
-};
diff --git a/browser/base/content/test/general/browser_fxa_migrate.js b/browser/base/content/test/general/browser_fxa_migrate.js
deleted file mode 100644
index 2faf9fb10..000000000
--- a/browser/base/content/test/general/browser_fxa_migrate.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const STATE_CHANGED_TOPIC = "fxa-migration:state-changed";
-const NOTIFICATION_TITLE = "fxa-migration";
-
-var imports = {};
-Cu.import("resource://services-sync/FxaMigrator.jsm", imports);
-
-add_task(function* test() {
- // Fake the state where we saw an EOL notification.
- Services.obs.notifyObservers(null, STATE_CHANGED_TOPIC, null);
-
- let notificationBox = document.getElementById("global-notificationbox");
- Assert.ok(notificationBox.allNotifications.some(n => {
- return n.getAttribute("value") == NOTIFICATION_TITLE;
- }), "Disconnect notification should be present");
-});
diff --git a/browser/base/content/test/general/browser_fxa_oauth.html b/browser/base/content/test/general/browser_fxa_oauth.html
deleted file mode 100644
index b31e7ceb4..000000000
--- a/browser/base/content/test/general/browser_fxa_oauth.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>fxa_oauth_test</title>
-</head>
-<body>
-<script>
- window.onload = function() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- // Note: This intentionally sends an object instead of a string, to ensure both work
- // (see browser_fxa_oauth_with_keys.html for the other test)
- detail: {
- id: "oauth_client_id",
- message: {
- command: "oauth_complete",
- data: {
- state: "state",
- code: "code1",
- closeWindow: "signin",
- },
- },
- },
- });
-
- window.dispatchEvent(event);
- };
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/browser_fxa_oauth.js b/browser/base/content/test/general/browser_fxa_oauth.js
deleted file mode 100644
index 1f688bfa8..000000000
--- a/browser/base/content/test/general/browser_fxa_oauth.js
+++ /dev/null
@@ -1,327 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: this.docShell is null");
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsOAuthClient",
- "resource://gre/modules/FxAccountsOAuthClient.jsm");
-
-const HTTP_PATH = "http://example.com";
-const HTTP_ENDPOINT = "/browser/browser/base/content/test/general/browser_fxa_oauth.html";
-const HTTP_ENDPOINT_WITH_KEYS = "/browser/browser/base/content/test/general/browser_fxa_oauth_with_keys.html";
-
-var gTests = [
- {
- desc: "FxA OAuth - should open a new tab, complete OAuth flow",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
- let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html";
- let queryStrings = [
- "action=signin",
- "client_id=client_id",
- "scope=",
- "state=state",
- "webChannelId=oauth_client_id",
- ];
- queryStrings.sort();
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
- Assert.ok(gBrowser.currentURI.spec.split("?")[0], properURL, "Check URL without params");
- let actualURL = new URL(gBrowser.currentURI.spec);
- let actualQueryStrings = actualURL.search.substring(1).split("&");
- actualQueryStrings.sort();
- Assert.equal(actualQueryStrings.length, queryStrings.length, "Check number of params");
-
- for (let i = 0; i < queryStrings.length; i++) {
- Assert.equal(actualQueryStrings[i], queryStrings[i], "Check parameter " + i);
- }
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH,
- },
- authorizationEndpoint: HTTP_ENDPOINT
- });
-
- client.onComplete = function(tokenData) {
- Assert.ok(tabOpened);
- Assert.equal(tokenData.code, "code1");
- Assert.equal(tokenData.state, "state");
- resolve();
- };
-
- client.onError = reject;
-
- client.launchWebFlow();
- });
- }
- },
- {
- desc: "FxA OAuth - should open a new tab, complete OAuth flow when forcing auth",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
- let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html";
- let queryStrings = [
- "action=force_auth",
- "client_id=client_id",
- "scope=",
- "state=state",
- "webChannelId=oauth_client_id",
- "email=test%40invalid.com",
- ];
- queryStrings.sort();
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
- Assert.ok(gBrowser.currentURI.spec.split("?")[0], properURL, "Check URL without params");
-
- let actualURL = new URL(gBrowser.currentURI.spec);
- let actualQueryStrings = actualURL.search.substring(1).split("&");
- actualQueryStrings.sort();
- Assert.equal(actualQueryStrings.length, queryStrings.length, "Check number of params");
-
- for (let i = 0; i < queryStrings.length; i++) {
- Assert.equal(actualQueryStrings[i], queryStrings[i], "Check parameter " + i);
- }
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH,
- action: "force_auth",
- email: "test@invalid.com"
- },
- authorizationEndpoint: HTTP_ENDPOINT
- });
-
- client.onComplete = function(tokenData) {
- Assert.ok(tabOpened);
- Assert.equal(tokenData.code, "code1");
- Assert.equal(tokenData.state, "state");
- resolve();
- };
-
- client.onError = reject;
-
- client.launchWebFlow();
- });
- }
- },
- {
- desc: "FxA OAuth - should receive an error when there's a state mismatch",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
-
- // It should have passed in the expected non-matching state value.
- let queryString = gBrowser.currentURI.spec.split("?")[1];
- Assert.ok(queryString.indexOf('state=different-state') >= 0);
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "different-state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH,
- },
- authorizationEndpoint: HTTP_ENDPOINT
- });
-
- client.onComplete = reject;
-
- client.onError = function(err) {
- Assert.ok(tabOpened);
- Assert.equal(err.message, "OAuth flow failed. State doesn't match");
- resolve();
- };
-
- client.launchWebFlow();
- });
- }
- },
- {
- desc: "FxA OAuth - should be able to request keys during OAuth flow",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
-
- // It should have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') >= 0);
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH,
- keys: true,
- },
- authorizationEndpoint: HTTP_ENDPOINT_WITH_KEYS
- });
-
- client.onComplete = function(tokenData, keys) {
- Assert.ok(tabOpened);
- Assert.equal(tokenData.code, "code1");
- Assert.equal(tokenData.state, "state");
- Assert.deepEqual(keys.kAr, {k: "kAr"});
- Assert.deepEqual(keys.kBr, {k: "kBr"});
- resolve();
- };
-
- client.onError = reject;
-
- client.launchWebFlow();
- });
- }
- },
- {
- desc: "FxA OAuth - should not receive keys if not explicitly requested",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
-
- // It should not have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') == -1);
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH
- },
- // This endpoint will cause the completion message to contain keys.
- authorizationEndpoint: HTTP_ENDPOINT_WITH_KEYS
- });
-
- client.onComplete = function(tokenData, keys) {
- Assert.ok(tabOpened);
- Assert.equal(tokenData.code, "code1");
- Assert.equal(tokenData.state, "state");
- Assert.strictEqual(keys, undefined);
- resolve();
- };
-
- client.onError = reject;
-
- client.launchWebFlow();
- });
- }
- },
- {
- desc: "FxA OAuth - should receive an error if keys could not be obtained",
- run: function () {
- return new Promise(function(resolve, reject) {
- let tabOpened = false;
-
- waitForTab(function (tab) {
- Assert.ok("Tab successfully opened");
-
- // It should have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') >= 0);
-
- tabOpened = true;
- });
-
- let client = new FxAccountsOAuthClient({
- parameters: {
- state: "state",
- client_id: "client_id",
- oauth_uri: HTTP_PATH,
- content_uri: HTTP_PATH,
- keys: true,
- },
- // This endpoint will cause the completion message not to contain keys.
- authorizationEndpoint: HTTP_ENDPOINT
- });
-
- client.onComplete = reject;
-
- client.onError = function(err) {
- Assert.ok(tabOpened);
- Assert.equal(err.message, "OAuth flow failed. Keys were not returned");
- resolve();
- };
-
- client.launchWebFlow();
- });
- }
- }
-]; // gTests
-
-function waitForTab(aCallback) {
- let container = gBrowser.tabContainer;
- container.addEventListener("TabOpen", function tabOpener(event) {
- container.removeEventListener("TabOpen", tabOpener, false);
- gBrowser.addEventListener("load", function listener() {
- gBrowser.removeEventListener("load", listener, true);
- let tab = event.target;
- aCallback(tab);
- }, true);
- }, false);
-}
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- const webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist";
- let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref);
- let newWhitelist = origWhitelist + " http://example.com";
- Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist);
- try {
- for (let testCase of gTests) {
- info("Running: " + testCase.desc);
- yield testCase.run();
- }
- } finally {
- Services.prefs.clearUserPref(webchannelWhitelistPref);
- }
- }).then(finish, ex => {
- Assert.ok(false, "Unexpected Exception: " + ex);
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_fxa_oauth_with_keys.html b/browser/base/content/test/general/browser_fxa_oauth_with_keys.html
deleted file mode 100644
index 2c28f7088..000000000
--- a/browser/base/content/test/general/browser_fxa_oauth_with_keys.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>fxa_oauth_test</title>
-</head>
-<body>
-<script>
- window.onload = function() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- // Note: This intentionally sends a string instead of an object, to ensure both work
- // (see browser_fxa_oauth.html for the other test)
- detail: JSON.stringify({
- id: "oauth_client_id",
- message: {
- command: "oauth_complete",
- data: {
- state: "state",
- code: "code1",
- closeWindow: "signin",
- // Keys normally contain more information, but this is enough
- // to keep Loop's tests happy.
- keys: { kAr: { k: 'kAr' }, kBr: { k: 'kBr' }},
- },
- },
- }),
- });
-
- window.dispatchEvent(event);
- };
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/browser_fxa_web_channel.html b/browser/base/content/test/general/browser_fxa_web_channel.html
deleted file mode 100644
index be5631ff1..000000000
--- a/browser/base/content/test/general/browser_fxa_web_channel.html
+++ /dev/null
@@ -1,138 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>fxa_web_channel_test</title>
-</head>
-<body>
-<script>
- var webChannelId = "account_updates_test";
-
- window.onload = function() {
- var testName = window.location.search.replace(/^\?/, "");
-
- switch (testName) {
- case "profile_change":
- test_profile_change();
- break;
- case "login":
- test_login();
- break;
- case "can_link_account":
- test_can_link_account();
- break;
- case "logout":
- test_logout();
- break;
- case "delete":
- test_delete();
- break;
- }
- };
-
- function test_profile_change() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: webChannelId,
- message: {
- command: "profile:change",
- data: {
- uid: "abc123",
- },
- },
- }),
- });
-
- window.dispatchEvent(event);
- }
-
- function test_login() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: webChannelId,
- message: {
- command: "fxaccounts:login",
- data: {
- authAt: Date.now(),
- email: "testuser@testuser.com",
- keyFetchToken: 'key_fetch_token',
- sessionToken: 'session_token',
- uid: 'uid',
- unwrapBKey: 'unwrap_b_key',
- verified: true,
- },
- messageId: 1,
- },
- }),
- });
-
- window.dispatchEvent(event);
- }
-
- function test_can_link_account() {
- window.addEventListener("WebChannelMessageToContent", function (e) {
- // echo any responses from the browser back to the tests on the
- // fxaccounts_webchannel_response_echo WebChannel. The tests are
- // listening for events and do the appropriate checks.
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: 'fxaccounts_webchannel_response_echo',
- message: e.detail.message,
- })
- });
-
- window.dispatchEvent(event);
- }, true);
-
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: webChannelId,
- message: {
- command: "fxaccounts:can_link_account",
- data: {
- email: "testuser@testuser.com",
- },
- messageId: 2,
- },
- }),
- });
-
- window.dispatchEvent(event);
- }
-
- function test_logout() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: webChannelId,
- message: {
- command: "fxaccounts:logout",
- data: {
- uid: 'uid'
- },
- messageId: 3,
- },
- }),
- });
-
- window.dispatchEvent(event);
- }
-
- function test_delete() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: webChannelId,
- message: {
- command: "fxaccounts:delete",
- data: {
- uid: 'uid'
- },
- messageId: 4,
- },
- }),
- });
-
- window.dispatchEvent(event);
- }
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/browser_fxa_web_channel.js b/browser/base/content/test/general/browser_fxa_web_channel.js
deleted file mode 100644
index eb0167ffb..000000000
--- a/browser/base/content/test/general/browser_fxa_web_channel.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "FxAccountsCommon", function () {
- return Components.utils.import("resource://gre/modules/FxAccountsCommon.js", {});
-});
-
-XPCOMUtils.defineLazyModuleGetter(this, "WebChannel",
- "resource://gre/modules/WebChannel.jsm");
-
-// FxAccountsWebChannel isn't explicitly exported by FxAccountsWebChannel.jsm
-// but we can get it here via a backstage pass.
-var {FxAccountsWebChannel} = Components.utils.import("resource://gre/modules/FxAccountsWebChannel.jsm", {});
-
-const TEST_HTTP_PATH = "http://example.com";
-const TEST_BASE_URL = TEST_HTTP_PATH + "/browser/browser/base/content/test/general/browser_fxa_web_channel.html";
-const TEST_CHANNEL_ID = "account_updates_test";
-
-var gTests = [
- {
- desc: "FxA Web Channel - should receive message about profile changes",
- run: function* () {
- let client = new FxAccountsWebChannel({
- content_uri: TEST_HTTP_PATH,
- channel_id: TEST_CHANNEL_ID,
- });
- let promiseObserver = new Promise((resolve, reject) => {
- makeObserver(FxAccountsCommon.ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) {
- Assert.equal(data, "abc123");
- client.tearDown();
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: TEST_BASE_URL + "?profile_change"
- }, function* () {
- yield promiseObserver;
- });
- }
- },
- {
- desc: "fxa web channel - login messages should notify the fxAccounts object",
- run: function* () {
-
- let promiseLogin = new Promise((resolve, reject) => {
- let login = (accountData) => {
- Assert.equal(typeof accountData.authAt, 'number');
- Assert.equal(accountData.email, 'testuser@testuser.com');
- Assert.equal(accountData.keyFetchToken, 'key_fetch_token');
- Assert.equal(accountData.sessionToken, 'session_token');
- Assert.equal(accountData.uid, 'uid');
- Assert.equal(accountData.unwrapBKey, 'unwrap_b_key');
- Assert.equal(accountData.verified, true);
-
- client.tearDown();
- resolve();
- };
-
- let client = new FxAccountsWebChannel({
- content_uri: TEST_HTTP_PATH,
- channel_id: TEST_CHANNEL_ID,
- helpers: {
- login: login
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: TEST_BASE_URL + "?login"
- }, function* () {
- yield promiseLogin;
- });
- }
- },
- {
- desc: "fxa web channel - can_link_account messages should respond",
- run: function* () {
- let properUrl = TEST_BASE_URL + "?can_link_account";
-
- let promiseEcho = new Promise((resolve, reject) => {
-
- let webChannelOrigin = Services.io.newURI(properUrl, null, null);
- // responses sent to content are echoed back over the
- // `fxaccounts_webchannel_response_echo` channel. Ensure the
- // fxaccounts:can_link_account message is responded to.
- let echoWebChannel = new WebChannel('fxaccounts_webchannel_response_echo', webChannelOrigin);
- echoWebChannel.listen((webChannelId, message, target) => {
- Assert.equal(message.command, 'fxaccounts:can_link_account');
- Assert.equal(message.messageId, 2);
- Assert.equal(message.data.ok, true);
-
- client.tearDown();
- echoWebChannel.stopListening();
-
- resolve();
- });
-
- let client = new FxAccountsWebChannel({
- content_uri: TEST_HTTP_PATH,
- channel_id: TEST_CHANNEL_ID,
- helpers: {
- shouldAllowRelink(acctName) {
- return acctName === 'testuser@testuser.com';
- }
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: properUrl
- }, function* () {
- yield promiseEcho;
- });
- }
- },
- {
- desc: "fxa web channel - logout messages should notify the fxAccounts object",
- run: function* () {
- let promiseLogout = new Promise((resolve, reject) => {
- let logout = (uid) => {
- Assert.equal(uid, 'uid');
-
- client.tearDown();
- resolve();
- };
-
- let client = new FxAccountsWebChannel({
- content_uri: TEST_HTTP_PATH,
- channel_id: TEST_CHANNEL_ID,
- helpers: {
- logout: logout
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: TEST_BASE_URL + "?logout"
- }, function* () {
- yield promiseLogout;
- });
- }
- },
- {
- desc: "fxa web channel - delete messages should notify the fxAccounts object",
- run: function* () {
- let promiseDelete = new Promise((resolve, reject) => {
- let logout = (uid) => {
- Assert.equal(uid, 'uid');
-
- client.tearDown();
- resolve();
- };
-
- let client = new FxAccountsWebChannel({
- content_uri: TEST_HTTP_PATH,
- channel_id: TEST_CHANNEL_ID,
- helpers: {
- logout: logout
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: TEST_BASE_URL + "?delete"
- }, function* () {
- yield promiseDelete;
- });
- }
- }
-]; // gTests
-
-function makeObserver(aObserveTopic, aObserveFunc) {
- let callback = function (aSubject, aTopic, aData) {
- if (aTopic == aObserveTopic) {
- removeMe();
- aObserveFunc(aSubject, aTopic, aData);
- }
- };
-
- function removeMe() {
- Services.obs.removeObserver(callback, aObserveTopic);
- }
-
- Services.obs.addObserver(callback, aObserveTopic, false);
- return removeMe;
-}
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- for (let testCase of gTests) {
- info("Running: " + testCase.desc);
- yield testCase.run();
- }
- }).then(finish, ex => {
- Assert.ok(false, "Unexpected Exception: " + ex);
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_fxaccounts.js b/browser/base/content/test/general/browser_fxaccounts.js
deleted file mode 100644
index 0f68286dc..000000000
--- a/browser/base/content/test/general/browser_fxaccounts.js
+++ /dev/null
@@ -1,261 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var {Log} = Cu.import("resource://gre/modules/Log.jsm", {});
-var {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
-var {fxAccounts} = Cu.import("resource://gre/modules/FxAccounts.jsm", {});
-var FxAccountsCommon = {};
-Cu.import("resource://gre/modules/FxAccountsCommon.js", FxAccountsCommon);
-
-const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/";
-
-// instrument gFxAccounts to send observer notifications when it's done
-// what it does.
-(function() {
- let unstubs = {}; // The original functions we stub out.
-
- // The stub functions.
- let stubs = {
- updateAppMenuItem: function() {
- return unstubs['updateAppMenuItem'].call(gFxAccounts).then(() => {
- Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null);
- });
- },
- // Opening preferences is trickier than it should be as leaks are reported
- // due to the promises it fires off at load time and there's no clear way to
- // know when they are done.
- // So just ensure openPreferences is called rather than whether it opens.
- openPreferences: function() {
- Services.obs.notifyObservers(null, "test:browser_fxaccounts:openPreferences", null);
- }
- };
-
- for (let name in stubs) {
- unstubs[name] = gFxAccounts[name];
- gFxAccounts[name] = stubs[name];
- }
- // and undo our damage at the end.
- registerCleanupFunction(() => {
- for (let name in unstubs) {
- gFxAccounts[name] = unstubs[name];
- }
- stubs = unstubs = null;
- });
-})();
-
-// Other setup/cleanup
-var newTab;
-
-Services.prefs.setCharPref("identity.fxaccounts.remote.signup.uri",
- TEST_ROOT + "accounts_testRemoteCommands.html");
-
-registerCleanupFunction(() => {
- Services.prefs.clearUserPref("identity.fxaccounts.remote.signup.uri");
- Services.prefs.clearUserPref("identity.fxaccounts.remote.profile.uri");
- gBrowser.removeTab(newTab);
-});
-
-add_task(function* initialize() {
- // Set a new tab with something other than about:blank, so it doesn't get reused.
- // We must wait for it to load or the promiseTabOpen() call in the next test
- // gets confused.
- newTab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla", {animate: false});
- yield promiseTabLoaded(newTab);
-});
-
-// The elements we care about.
-var panelUILabel = document.getElementById("PanelUI-fxa-label");
-var panelUIStatus = document.getElementById("PanelUI-fxa-status");
-var panelUIFooter = document.getElementById("PanelUI-footer-fxa");
-
-// The tests
-add_task(function* test_nouser() {
- let user = yield fxAccounts.getSignedInUser();
- Assert.strictEqual(user, null, "start with no user signed in");
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
- Services.obs.notifyObservers(null, this.FxAccountsCommon.ONLOGOUT_NOTIFICATION, null);
- yield promiseUpdateDone;
-
- // Check the world - the FxA footer area is visible as it is offering a signin.
- Assert.ok(isFooterVisible())
-
- Assert.equal(panelUILabel.getAttribute("label"), panelUIStatus.getAttribute("defaultlabel"));
- Assert.equal(panelUIStatus.getAttribute("tooltiptext"), panelUIStatus.getAttribute("signedinTooltiptext"));
- Assert.ok(!panelUIFooter.hasAttribute("fxastatus"), "no fxsstatus when signed out");
- Assert.ok(!panelUIFooter.hasAttribute("fxaprofileimage"), "no fxaprofileimage when signed out");
-
- let promisePreferencesOpened = promiseObserver("test:browser_fxaccounts:openPreferences");
- panelUIStatus.click();
- yield promisePreferencesOpened;
-});
-
-/*
-XXX - Bug 1191162 - need a better hawk mock story or this will leak in debug builds.
-
-add_task(function* test_unverifiedUser() {
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
- yield setSignedInUser(false); // this will fire the observer that does the update.
- yield promiseUpdateDone;
-
- // Check the world.
- Assert.ok(isFooterVisible())
-
- Assert.equal(panelUILabel.getAttribute("label"), "foo@example.com");
- Assert.equal(panelUIStatus.getAttribute("tooltiptext"),
- panelUIStatus.getAttribute("signedinTooltiptext"));
- Assert.equal(panelUIFooter.getAttribute("fxastatus"), "signedin");
- let promisePreferencesOpened = promiseObserver("test:browser_fxaccounts:openPreferences");
- panelUIStatus.click();
- yield promisePreferencesOpened
- yield signOut();
-});
-*/
-
-add_task(function* test_verifiedUserEmptyProfile() {
- // We see 2 updateAppMenuItem() calls - one for the signedInUser and one after
- // we first fetch the profile. We want them both to fire or we aren't testing
- // the state we think we are testing.
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 2);
- gFxAccounts._cachedProfile = null;
- configureProfileURL({}); // successful but empty profile.
- yield setSignedInUser(true); // this will fire the observer that does the update.
- yield promiseUpdateDone;
-
- // Check the world.
- Assert.ok(isFooterVisible())
- Assert.equal(panelUILabel.getAttribute("label"), "foo@example.com");
- Assert.equal(panelUIStatus.getAttribute("tooltiptext"),
- panelUIStatus.getAttribute("signedinTooltiptext"));
- Assert.equal(panelUIFooter.getAttribute("fxastatus"), "signedin");
-
- let promisePreferencesOpened = promiseObserver("test:browser_fxaccounts:openPreferences");
- panelUIStatus.click();
- yield promisePreferencesOpened;
- yield signOut();
-});
-
-add_task(function* test_verifiedUserDisplayName() {
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 2);
- gFxAccounts._cachedProfile = null;
- configureProfileURL({ displayName: "Test User Display Name" });
- yield setSignedInUser(true); // this will fire the observer that does the update.
- yield promiseUpdateDone;
-
- Assert.ok(isFooterVisible())
- Assert.equal(panelUILabel.getAttribute("label"), "Test User Display Name");
- Assert.equal(panelUIStatus.getAttribute("tooltiptext"),
- panelUIStatus.getAttribute("signedinTooltiptext"));
- Assert.equal(panelUIFooter.getAttribute("fxastatus"), "signedin");
- yield signOut();
-});
-
-add_task(function* test_verifiedUserProfileFailure() {
- // profile failure means only one observer fires.
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem", 1);
- gFxAccounts._cachedProfile = null;
- configureProfileURL(null, 500);
- yield setSignedInUser(true); // this will fire the observer that does the update.
- yield promiseUpdateDone;
-
- Assert.ok(isFooterVisible())
- Assert.equal(panelUILabel.getAttribute("label"), "foo@example.com");
- Assert.equal(panelUIStatus.getAttribute("tooltiptext"),
- panelUIStatus.getAttribute("signedinTooltiptext"));
- Assert.equal(panelUIFooter.getAttribute("fxastatus"), "signedin");
- yield signOut();
-});
-
-// Helpers.
-function isFooterVisible() {
- let style = window.getComputedStyle(panelUIFooter);
- return style.getPropertyValue("display") == "flex";
-}
-
-function configureProfileURL(profile, responseStatus = 200) {
- let responseBody = profile ? JSON.stringify(profile) : "";
- let url = TEST_ROOT + "fxa_profile_handler.sjs?" +
- "responseStatus=" + responseStatus +
- "responseBody=" + responseBody +
- // This is a bit cheeky - the FxA code will just append "/profile"
- // to the preference value. We arrange for this to be seen by our
- // .sjs as part of the query string.
- "&path=";
-
- Services.prefs.setCharPref("identity.fxaccounts.remote.profile.uri", url);
-}
-
-function promiseObserver(topic, count = 1) {
- return new Promise(resolve => {
- let obs = (aSubject, aTopic, aData) => {
- if (--count == 0) {
- Services.obs.removeObserver(obs, aTopic);
- resolve(aSubject);
- }
- }
- Services.obs.addObserver(obs, topic, false);
- });
-}
-
-// Stolen from browser_aboutHome.js
-function promiseWaitForEvent(node, type, capturing) {
- return new Promise((resolve) => {
- node.addEventListener(type, function listener(event) {
- node.removeEventListener(type, listener, capturing);
- resolve(event);
- }, capturing);
- });
-}
-
-var promiseTabOpen = Task.async(function*(urlBase) {
- info("Waiting for tab to open...");
- let event = yield promiseWaitForEvent(gBrowser.tabContainer, "TabOpen", true);
- let tab = event.target;
- yield promiseTabLoadEvent(tab);
- ok(tab.linkedBrowser.currentURI.spec.startsWith(urlBase),
- "Got " + tab.linkedBrowser.currentURI.spec + ", expecting " + urlBase);
- let whenUnloaded = promiseTabUnloaded(tab);
- gBrowser.removeTab(tab);
- yield whenUnloaded;
-});
-
-function promiseTabUnloaded(tab)
-{
- return new Promise(resolve => {
- info("Wait for tab to unload");
- function handle(event) {
- tab.linkedBrowser.removeEventListener("unload", handle, true);
- info("Got unload event");
- resolve(event);
- }
- tab.linkedBrowser.addEventListener("unload", handle, true, true);
- });
-}
-
-// FxAccounts helpers.
-function setSignedInUser(verified) {
- let data = {
- email: "foo@example.com",
- uid: "1234@lcip.org",
- assertion: "foobar",
- sessionToken: "dead",
- kA: "beef",
- kB: "cafe",
- verified: verified,
-
- oauthTokens: {
- // a token for the profile server.
- profile: "key value",
- }
- }
- return fxAccounts.setSignedInUser(data);
-}
-
-var signOut = Task.async(function* () {
- // This test needs to make sure that any updates for the logout have
- // completed before starting the next test, or we see the observer
- // notifications get out of sync.
- let promiseUpdateDone = promiseObserver("test:browser_fxaccounts:updateAppMenuItem");
- // we always want a "localOnly" signout here...
- yield fxAccounts.signOut(true);
- yield promiseUpdateDone;
-});
diff --git a/browser/base/content/test/general/browser_gZipOfflineChild.js b/browser/base/content/test/general/browser_gZipOfflineChild.js
deleted file mode 100644
index 09691bed8..000000000
--- a/browser/base/content/test/general/browser_gZipOfflineChild.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const URL = "http://mochi.test:8888/browser/browser/base/content/test/general/test_offline_gzip.html"
-
-registerCleanupFunction(function() {
- // Clean up after ourself
- let uri = Services.io.newURI(URL, null, null);
- let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
- Services.perms.removeFromPrincipal(principal, "offline-app");
- Services.prefs.clearUserPref("offline-apps.allow_by_default");
-});
-
-var cacheCount = 0;
-var intervalID = 0;
-
-//
-// Handle "message" events which are posted from the iframe upon
-// offline cache events.
-//
-function handleMessageEvents(event) {
- cacheCount++;
- switch (cacheCount) {
- case 1:
- // This is the initial caching off offline data.
- is(event.data, "oncache", "Child was successfully cached.");
- // Reload the frame; this will generate an error message
- // in the case of bug 501422.
- event.source.location.reload();
- // Use setInterval to repeatedly call a function which
- // checks that one of two things has occurred: either
- // the offline cache is udpated (which means our iframe
- // successfully reloaded), or the string "error" appears
- // in the iframe, as in the case of bug 501422.
- intervalID = setInterval(function() {
- // Sometimes document.body may not exist, and trying to access
- // it will throw an exception, so handle this case.
- try {
- var bodyInnerHTML = event.source.document.body.innerHTML;
- }
- catch (e) {
- bodyInnerHTML = "";
- }
- if (cacheCount == 2 || bodyInnerHTML.includes("error")) {
- clearInterval(intervalID);
- is(cacheCount, 2, "frame not reloaded successfully");
- if (cacheCount != 2) {
- finish();
- }
- }
- }, 100);
- break;
- case 2:
- is(event.data, "onupdate", "Child was successfully updated.");
- clearInterval(intervalID);
- finish();
- break;
- default:
- // how'd we get here?
- ok(false, "cacheCount not 1 or 2");
- }
-}
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref("offline-apps.allow_by_default", true);
-
- // Open a new tab.
- gBrowser.selectedTab = gBrowser.addTab(URL);
- registerCleanupFunction(() => gBrowser.removeCurrentTab());
-
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => {
- let window = gBrowser.selectedBrowser.contentWindow;
-
- window.addEventListener("message", handleMessageEvents, false);
- });
-}
diff --git a/browser/base/content/test/general/browser_gestureSupport.js b/browser/base/content/test/general/browser_gestureSupport.js
deleted file mode 100644
index b31cad31d..000000000
--- a/browser/base/content/test/general/browser_gestureSupport.js
+++ /dev/null
@@ -1,670 +0,0 @@
-/* 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/. */
-
-// Simple gestures tests
-//
-// These tests require the ability to disable the fact that the
-// Firefox chrome intentionally prevents "simple gesture" events from
-// reaching web content.
-
-var test_utils;
-var test_commandset;
-var test_prefBranch = "browser.gesture.";
-
-function test()
-{
- waitForExplicitFinish();
-
- // Disable the default gestures support during the test
- gGestureSupport.init(false);
-
- test_utils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
- getInterface(Components.interfaces.nsIDOMWindowUtils);
-
- // Run the tests of "simple gesture" events generally
- test_EnsureConstantsAreDisjoint();
- test_TestEventListeners();
- test_TestEventCreation();
-
- // Reenable the default gestures support. The remaining tests target
- // the Firefox gesture functionality.
- gGestureSupport.init(true);
-
- // Test Firefox's gestures support.
- test_commandset = document.getElementById("mainCommandSet");
- test_swipeGestures();
- test_latchedGesture("pinch", "out", "in", "MozMagnifyGesture");
- test_thresholdGesture("pinch", "out", "in", "MozMagnifyGesture");
- test_rotateGestures();
-}
-
-var test_eventCount = 0;
-var test_expectedType;
-var test_expectedDirection;
-var test_expectedDelta;
-var test_expectedModifiers;
-var test_expectedClickCount;
-var test_imageTab;
-
-function test_gestureListener(evt)
-{
- is(evt.type, test_expectedType,
- "evt.type (" + evt.type + ") does not match expected value");
- is(evt.target, test_utils.elementFromPoint(20, 20, false, false),
- "evt.target (" + evt.target + ") does not match expected value");
- is(evt.clientX, 20,
- "evt.clientX (" + evt.clientX + ") does not match expected value");
- is(evt.clientY, 20,
- "evt.clientY (" + evt.clientY + ") does not match expected value");
- isnot(evt.screenX, 0,
- "evt.screenX (" + evt.screenX + ") does not match expected value");
- isnot(evt.screenY, 0,
- "evt.screenY (" + evt.screenY + ") does not match expected value");
-
- is(evt.direction, test_expectedDirection,
- "evt.direction (" + evt.direction + ") does not match expected value");
- is(evt.delta, test_expectedDelta,
- "evt.delta (" + evt.delta + ") does not match expected value");
-
- is(evt.shiftKey, (test_expectedModifiers & Components.interfaces.nsIDOMEvent.SHIFT_MASK) != 0,
- "evt.shiftKey did not match expected value");
- is(evt.ctrlKey, (test_expectedModifiers & Components.interfaces.nsIDOMEvent.CONTROL_MASK) != 0,
- "evt.ctrlKey did not match expected value");
- is(evt.altKey, (test_expectedModifiers & Components.interfaces.nsIDOMEvent.ALT_MASK) != 0,
- "evt.altKey did not match expected value");
- is(evt.metaKey, (test_expectedModifiers & Components.interfaces.nsIDOMEvent.META_MASK) != 0,
- "evt.metaKey did not match expected value");
-
- if (evt.type == "MozTapGesture") {
- is(evt.clickCount, test_expectedClickCount, "evt.clickCount does not match");
- }
-
- test_eventCount++;
-}
-
-function test_helper1(type, direction, delta, modifiers)
-{
- // Setup the expected values
- test_expectedType = type;
- test_expectedDirection = direction;
- test_expectedDelta = delta;
- test_expectedModifiers = modifiers;
-
- let expectedEventCount = test_eventCount + 1;
-
- document.addEventListener(type, test_gestureListener, true);
- test_utils.sendSimpleGestureEvent(type, 20, 20, direction, delta, modifiers);
- document.removeEventListener(type, test_gestureListener, true);
-
- is(expectedEventCount, test_eventCount, "Event (" + type + ") was never received by event listener");
-}
-
-function test_clicks(type, clicks)
-{
- // Setup the expected values
- test_expectedType = type;
- test_expectedDirection = 0;
- test_expectedDelta = 0;
- test_expectedModifiers = 0;
- test_expectedClickCount = clicks;
-
- let expectedEventCount = test_eventCount + 1;
-
- document.addEventListener(type, test_gestureListener, true);
- test_utils.sendSimpleGestureEvent(type, 20, 20, 0, 0, 0, clicks);
- document.removeEventListener(type, test_gestureListener, true);
-
- is(expectedEventCount, test_eventCount, "Event (" + type + ") was never received by event listener");
-}
-
-function test_TestEventListeners()
-{
- let e = test_helper1; // easier to type this name
-
- // Swipe gesture animation events
- e("MozSwipeGestureStart", 0, -0.7, 0);
- e("MozSwipeGestureUpdate", 0, -0.4, 0);
- e("MozSwipeGestureEnd", 0, 0, 0);
- e("MozSwipeGestureStart", 0, 0.6, 0);
- e("MozSwipeGestureUpdate", 0, 0.3, 0);
- e("MozSwipeGestureEnd", 0, 1, 0);
-
- // Swipe gesture event
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_LEFT, 0.0, 0);
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0.0, 0);
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_UP, 0.0, 0);
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_DOWN, 0.0, 0);
- e("MozSwipeGesture",
- SimpleGestureEvent.DIRECTION_UP | SimpleGestureEvent.DIRECTION_LEFT, 0.0, 0);
- e("MozSwipeGesture",
- SimpleGestureEvent.DIRECTION_DOWN | SimpleGestureEvent.DIRECTION_RIGHT, 0.0, 0);
- e("MozSwipeGesture",
- SimpleGestureEvent.DIRECTION_UP | SimpleGestureEvent.DIRECTION_RIGHT, 0.0, 0);
- e("MozSwipeGesture",
- SimpleGestureEvent.DIRECTION_DOWN | SimpleGestureEvent.DIRECTION_LEFT, 0.0, 0);
-
- // magnify gesture events
- e("MozMagnifyGestureStart", 0, 50.0, 0);
- e("MozMagnifyGestureUpdate", 0, -25.0, 0);
- e("MozMagnifyGestureUpdate", 0, 5.0, 0);
- e("MozMagnifyGesture", 0, 30.0, 0);
-
- // rotate gesture events
- e("MozRotateGestureStart", SimpleGestureEvent.ROTATION_CLOCKWISE, 33.0, 0);
- e("MozRotateGestureUpdate", SimpleGestureEvent.ROTATION_COUNTERCLOCKWISE, -13.0, 0);
- e("MozRotateGestureUpdate", SimpleGestureEvent.ROTATION_CLOCKWISE, 13.0, 0);
- e("MozRotateGesture", SimpleGestureEvent.ROTATION_CLOCKWISE, 33.0, 0);
-
- // Tap and presstap gesture events
- test_clicks("MozTapGesture", 1);
- test_clicks("MozTapGesture", 2);
- test_clicks("MozTapGesture", 3);
- test_clicks("MozPressTapGesture", 1);
-
- // simple delivery test for edgeui gestures
- e("MozEdgeUIStarted", 0, 0, 0);
- e("MozEdgeUICanceled", 0, 0, 0);
- e("MozEdgeUICompleted", 0, 0, 0);
-
- // event.shiftKey
- let modifier = Components.interfaces.nsIDOMEvent.SHIFT_MASK;
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
-
- // event.metaKey
- modifier = Components.interfaces.nsIDOMEvent.META_MASK;
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
-
- // event.altKey
- modifier = Components.interfaces.nsIDOMEvent.ALT_MASK;
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
-
- // event.ctrlKey
- modifier = Components.interfaces.nsIDOMEvent.CONTROL_MASK;
- e("MozSwipeGesture", SimpleGestureEvent.DIRECTION_RIGHT, 0, modifier);
-}
-
-function test_eventDispatchListener(evt)
-{
- test_eventCount++;
- evt.stopPropagation();
-}
-
-function test_helper2(type, direction, delta, altKey, ctrlKey, shiftKey, metaKey)
-{
- let event = null;
- let successful;
-
- try {
- event = document.createEvent("SimpleGestureEvent");
- successful = true;
- }
- catch (ex) {
- successful = false;
- }
- ok(successful, "Unable to create SimpleGestureEvent");
-
- try {
- event.initSimpleGestureEvent(type, true, true, window, 1,
- 10, 10, 10, 10,
- ctrlKey, altKey, shiftKey, metaKey,
- 1, window,
- 0, direction, delta, 0);
- successful = true;
- }
- catch (ex) {
- successful = false;
- }
- ok(successful, "event.initSimpleGestureEvent should not fail");
-
- // Make sure the event fields match the expected values
- is(event.type, type, "Mismatch on evt.type");
- is(event.direction, direction, "Mismatch on evt.direction");
- is(event.delta, delta, "Mismatch on evt.delta");
- is(event.altKey, altKey, "Mismatch on evt.altKey");
- is(event.ctrlKey, ctrlKey, "Mismatch on evt.ctrlKey");
- is(event.shiftKey, shiftKey, "Mismatch on evt.shiftKey");
- is(event.metaKey, metaKey, "Mismatch on evt.metaKey");
- is(event.view, window, "Mismatch on evt.view");
- is(event.detail, 1, "Mismatch on evt.detail");
- is(event.clientX, 10, "Mismatch on evt.clientX");
- is(event.clientY, 10, "Mismatch on evt.clientY");
- is(event.screenX, 10, "Mismatch on evt.screenX");
- is(event.screenY, 10, "Mismatch on evt.screenY");
- is(event.button, 1, "Mismatch on evt.button");
- is(event.relatedTarget, window, "Mismatch on evt.relatedTarget");
-
- // Test event dispatch
- let expectedEventCount = test_eventCount + 1;
- document.addEventListener(type, test_eventDispatchListener, true);
- document.dispatchEvent(event);
- document.removeEventListener(type, test_eventDispatchListener, true);
- is(expectedEventCount, test_eventCount, "Dispatched event was never received by listener");
-}
-
-function test_TestEventCreation()
-{
- // Event creation
- test_helper2("MozMagnifyGesture", SimpleGestureEvent.DIRECTION_RIGHT, 20.0,
- true, false, true, false);
- test_helper2("MozMagnifyGesture", SimpleGestureEvent.DIRECTION_LEFT, -20.0,
- false, true, false, true);
-}
-
-function test_EnsureConstantsAreDisjoint()
-{
- let up = SimpleGestureEvent.DIRECTION_UP;
- let down = SimpleGestureEvent.DIRECTION_DOWN;
- let left = SimpleGestureEvent.DIRECTION_LEFT;
- let right = SimpleGestureEvent.DIRECTION_RIGHT;
-
- let clockwise = SimpleGestureEvent.ROTATION_CLOCKWISE;
- let cclockwise = SimpleGestureEvent.ROTATION_COUNTERCLOCKWISE;
-
- ok(up ^ down, "DIRECTION_UP and DIRECTION_DOWN are not bitwise disjoint");
- ok(up ^ left, "DIRECTION_UP and DIRECTION_LEFT are not bitwise disjoint");
- ok(up ^ right, "DIRECTION_UP and DIRECTION_RIGHT are not bitwise disjoint");
- ok(down ^ left, "DIRECTION_DOWN and DIRECTION_LEFT are not bitwise disjoint");
- ok(down ^ right, "DIRECTION_DOWN and DIRECTION_RIGHT are not bitwise disjoint");
- ok(left ^ right, "DIRECTION_LEFT and DIRECTION_RIGHT are not bitwise disjoint");
- ok(clockwise ^ cclockwise, "ROTATION_CLOCKWISE and ROTATION_COUNTERCLOCKWISE are not bitwise disjoint");
-}
-
-// Helper for test of latched event processing. Emits the actual
-// gesture events to test whether the commands associated with the
-// gesture will only trigger once for each direction of movement.
-function test_emitLatchedEvents(eventPrefix, initialDelta, cmd)
-{
- let cumulativeDelta = 0;
- let isIncreasing = initialDelta > 0;
-
- let expect = {};
- // Reset the call counters and initialize expected values
- for (let dir in cmd)
- cmd[dir].callCount = expect[dir] = 0;
-
- let check = (aDir, aMsg) => ok(cmd[aDir].callCount == expect[aDir], aMsg);
- let checkBoth = function(aNum, aInc, aDec) {
- let prefix = "Step " + aNum + ": ";
- check("inc", prefix + aInc);
- check("dec", prefix + aDec);
- };
-
- // Send the "Start" event.
- test_utils.sendSimpleGestureEvent(eventPrefix + "Start", 0, 0, 0, initialDelta, 0);
- cumulativeDelta += initialDelta;
- if (isIncreasing) {
- expect.inc++;
- checkBoth(1, "Increasing command was not triggered", "Decreasing command was triggered");
- } else {
- expect.dec++;
- checkBoth(1, "Increasing command was triggered", "Decreasing command was not triggered");
- }
-
- // Send random values in the same direction and ensure neither
- // command triggers.
- for (let i = 0; i < 5; i++) {
- let delta = Math.random() * (isIncreasing ? 100 : -100);
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0, delta, 0);
- cumulativeDelta += delta;
- checkBoth(2, "Increasing command was triggered", "Decreasing command was triggered");
- }
-
- // Now go back in the opposite direction.
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0,
- - initialDelta, 0);
- cumulativeDelta += - initialDelta;
- if (isIncreasing) {
- expect.dec++;
- checkBoth(3, "Increasing command was triggered", "Decreasing command was not triggered");
- } else {
- expect.inc++;
- checkBoth(3, "Increasing command was not triggered", "Decreasing command was triggered");
- }
-
- // Send random values in the opposite direction and ensure neither
- // command triggers.
- for (let i = 0; i < 5; i++) {
- let delta = Math.random() * (isIncreasing ? -100 : 100);
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0, delta, 0);
- cumulativeDelta += delta;
- checkBoth(4, "Increasing command was triggered", "Decreasing command was triggered");
- }
-
- // Go back to the original direction. The original command should trigger.
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0,
- initialDelta, 0);
- cumulativeDelta += initialDelta;
- if (isIncreasing) {
- expect.inc++;
- checkBoth(5, "Increasing command was not triggered", "Decreasing command was triggered");
- } else {
- expect.dec++;
- checkBoth(5, "Increasing command was triggered", "Decreasing command was not triggered");
- }
-
- // Send the wrap-up event. No commands should be triggered.
- test_utils.sendSimpleGestureEvent(eventPrefix, 0, 0, 0, cumulativeDelta, 0);
- checkBoth(6, "Increasing command was triggered", "Decreasing command was triggered");
-}
-
-function test_addCommand(prefName, id)
-{
- let cmd = test_commandset.appendChild(document.createElement("command"));
- cmd.setAttribute("id", id);
- cmd.setAttribute("oncommand", "this.callCount++;");
-
- cmd.origPrefName = prefName;
- cmd.origPrefValue = gPrefService.getCharPref(prefName);
- gPrefService.setCharPref(prefName, id);
-
- return cmd;
-}
-
-function test_removeCommand(cmd)
-{
- gPrefService.setCharPref(cmd.origPrefName, cmd.origPrefValue);
- test_commandset.removeChild(cmd);
-}
-
-// Test whether latched events are only called once per direction of motion.
-function test_latchedGesture(gesture, inc, dec, eventPrefix)
-{
- let branch = test_prefBranch + gesture + ".";
-
- // Put the gesture into latched mode.
- let oldLatchedValue = gPrefService.getBoolPref(branch + "latched");
- gPrefService.setBoolPref(branch + "latched", true);
-
- // Install the test commands for increasing and decreasing motion.
- let cmd = {
- inc: test_addCommand(branch + inc, "test:incMotion"),
- dec: test_addCommand(branch + dec, "test:decMotion"),
- };
-
- // Test the gestures in each direction.
- test_emitLatchedEvents(eventPrefix, 500, cmd);
- test_emitLatchedEvents(eventPrefix, -500, cmd);
-
- // Restore the gesture to its original configuration.
- gPrefService.setBoolPref(branch + "latched", oldLatchedValue);
- for (let dir in cmd)
- test_removeCommand(cmd[dir]);
-}
-
-// Test whether non-latched events are triggered upon sufficient motion.
-function test_thresholdGesture(gesture, inc, dec, eventPrefix)
-{
- let branch = test_prefBranch + gesture + ".";
-
- // Disable latched mode for this gesture.
- let oldLatchedValue = gPrefService.getBoolPref(branch + "latched");
- gPrefService.setBoolPref(branch + "latched", false);
-
- // Set the triggering threshold value to 50.
- let oldThresholdValue = gPrefService.getIntPref(branch + "threshold");
- gPrefService.setIntPref(branch + "threshold", 50);
-
- // Install the test commands for increasing and decreasing motion.
- let cmdInc = test_addCommand(branch + inc, "test:incMotion");
- let cmdDec = test_addCommand(branch + dec, "test:decMotion");
-
- // Send the start event but stop short of triggering threshold.
- cmdInc.callCount = cmdDec.callCount = 0;
- test_utils.sendSimpleGestureEvent(eventPrefix + "Start", 0, 0, 0, 49.5, 0);
- ok(cmdInc.callCount == 0, "Increasing command was triggered");
- ok(cmdDec.callCount == 0, "Decreasing command was triggered");
-
- // Now trigger the threshold.
- cmdInc.callCount = cmdDec.callCount = 0;
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0, 1, 0);
- ok(cmdInc.callCount == 1, "Increasing command was not triggered");
- ok(cmdDec.callCount == 0, "Decreasing command was triggered");
-
- // The tracking counter should go to zero. Go back the other way and
- // stop short of triggering the threshold.
- cmdInc.callCount = cmdDec.callCount = 0;
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0, -49.5, 0);
- ok(cmdInc.callCount == 0, "Increasing command was triggered");
- ok(cmdDec.callCount == 0, "Decreasing command was triggered");
-
- // Now cross the threshold and trigger the decreasing command.
- cmdInc.callCount = cmdDec.callCount = 0;
- test_utils.sendSimpleGestureEvent(eventPrefix + "Update", 0, 0, 0, -1.5, 0);
- ok(cmdInc.callCount == 0, "Increasing command was triggered");
- ok(cmdDec.callCount == 1, "Decreasing command was not triggered");
-
- // Send the wrap-up event. No commands should trigger.
- cmdInc.callCount = cmdDec.callCount = 0;
- test_utils.sendSimpleGestureEvent(eventPrefix, 0, 0, 0, -0.5, 0);
- ok(cmdInc.callCount == 0, "Increasing command was triggered");
- ok(cmdDec.callCount == 0, "Decreasing command was triggered");
-
- // Restore the gesture to its original configuration.
- gPrefService.setBoolPref(branch + "latched", oldLatchedValue);
- gPrefService.setIntPref(branch + "threshold", oldThresholdValue);
- test_removeCommand(cmdInc);
- test_removeCommand(cmdDec);
-}
-
-function test_swipeGestures()
-{
- // easier to type names for the direction constants
- let up = SimpleGestureEvent.DIRECTION_UP;
- let down = SimpleGestureEvent.DIRECTION_DOWN;
- let left = SimpleGestureEvent.DIRECTION_LEFT;
- let right = SimpleGestureEvent.DIRECTION_RIGHT;
-
- let branch = test_prefBranch + "swipe.";
-
- // Install the test commands for the swipe gestures.
- let cmdUp = test_addCommand(branch + "up", "test:swipeUp");
- let cmdDown = test_addCommand(branch + "down", "test:swipeDown");
- let cmdLeft = test_addCommand(branch + "left", "test:swipeLeft");
- let cmdRight = test_addCommand(branch + "right", "test:swipeRight");
-
- function resetCounts() {
- cmdUp.callCount = 0;
- cmdDown.callCount = 0;
- cmdLeft.callCount = 0;
- cmdRight.callCount = 0;
- }
-
- // UP
- resetCounts();
- test_utils.sendSimpleGestureEvent("MozSwipeGesture", 0, 0, up, 0, 0);
- ok(cmdUp.callCount == 1, "Step 1: Up command was not triggered");
- ok(cmdDown.callCount == 0, "Step 1: Down command was triggered");
- ok(cmdLeft.callCount == 0, "Step 1: Left command was triggered");
- ok(cmdRight.callCount == 0, "Step 1: Right command was triggered");
-
- // DOWN
- resetCounts();
- test_utils.sendSimpleGestureEvent("MozSwipeGesture", 0, 0, down, 0, 0);
- ok(cmdUp.callCount == 0, "Step 2: Up command was triggered");
- ok(cmdDown.callCount == 1, "Step 2: Down command was not triggered");
- ok(cmdLeft.callCount == 0, "Step 2: Left command was triggered");
- ok(cmdRight.callCount == 0, "Step 2: Right command was triggered");
-
- // LEFT
- resetCounts();
- test_utils.sendSimpleGestureEvent("MozSwipeGesture", 0, 0, left, 0, 0);
- ok(cmdUp.callCount == 0, "Step 3: Up command was triggered");
- ok(cmdDown.callCount == 0, "Step 3: Down command was triggered");
- ok(cmdLeft.callCount == 1, "Step 3: Left command was not triggered");
- ok(cmdRight.callCount == 0, "Step 3: Right command was triggered");
-
- // RIGHT
- resetCounts();
- test_utils.sendSimpleGestureEvent("MozSwipeGesture", 0, 0, right, 0, 0);
- ok(cmdUp.callCount == 0, "Step 4: Up command was triggered");
- ok(cmdDown.callCount == 0, "Step 4: Down command was triggered");
- ok(cmdLeft.callCount == 0, "Step 4: Left command was triggered");
- ok(cmdRight.callCount == 1, "Step 4: Right command was not triggered");
-
- // Make sure combinations do not trigger events.
- let combos = [ up | left, up | right, down | left, down | right];
- for (let i = 0; i < combos.length; i++) {
- resetCounts();
- test_utils.sendSimpleGestureEvent("MozSwipeGesture", 0, 0, combos[i], 0, 0);
- ok(cmdUp.callCount == 0, "Step 5-"+i+": Up command was triggered");
- ok(cmdDown.callCount == 0, "Step 5-"+i+": Down command was triggered");
- ok(cmdLeft.callCount == 0, "Step 5-"+i+": Left command was triggered");
- ok(cmdRight.callCount == 0, "Step 5-"+i+": Right command was triggered");
- }
-
- // Remove the test commands.
- test_removeCommand(cmdUp);
- test_removeCommand(cmdDown);
- test_removeCommand(cmdLeft);
- test_removeCommand(cmdRight);
-}
-
-
-function test_rotateHelperGetImageRotation(aImageElement)
-{
- // Get the true image rotation from the transform matrix, bounded
- // to 0 <= result < 360
- let transformValue = content.window.getComputedStyle(aImageElement, null)
- .transform;
- if (transformValue == "none")
- return 0;
-
- transformValue = transformValue.split("(")[1]
- .split(")")[0]
- .split(",");
- var rotation = Math.round(Math.atan2(transformValue[1], transformValue[0]) *
- (180 / Math.PI));
- return (rotation < 0 ? rotation + 360 : rotation);
-}
-
-function test_rotateHelperOneGesture(aImageElement, aCurrentRotation,
- aDirection, aAmount, aStop)
-{
- if (aAmount <= 0 || aAmount > 90) // Bound to 0 < aAmount <= 90
- return;
-
- // easier to type names for the direction constants
- let clockwise = SimpleGestureEvent.ROTATION_CLOCKWISE;
-
- let delta = aAmount * (aDirection == clockwise ? 1 : -1);
-
- // Kill transition time on image so test isn't wrong and doesn't take 10 seconds
- aImageElement.style.transitionDuration = "0s";
-
- // Start the gesture, perform an update, and force flush
- test_utils.sendSimpleGestureEvent("MozRotateGestureStart", 0, 0, aDirection, .001, 0);
- test_utils.sendSimpleGestureEvent("MozRotateGestureUpdate", 0, 0, aDirection, delta, 0);
- aImageElement.clientTop;
-
- // If stop, check intermediate
- if (aStop) {
- // Send near-zero-delta to stop, and force flush
- test_utils.sendSimpleGestureEvent("MozRotateGestureUpdate", 0, 0, aDirection, .001, 0);
- aImageElement.clientTop;
-
- let stopExpectedRotation = (aCurrentRotation + delta) % 360;
- if (stopExpectedRotation < 0)
- stopExpectedRotation += 360;
-
- is(stopExpectedRotation, test_rotateHelperGetImageRotation(aImageElement),
- "Image rotation at gesture stop/hold: expected=" + stopExpectedRotation +
- ", observed=" + test_rotateHelperGetImageRotation(aImageElement) +
- ", init=" + aCurrentRotation +
- ", amt=" + aAmount +
- ", dir=" + (aDirection == clockwise ? "cl" : "ccl"));
- }
- // End it and force flush
- test_utils.sendSimpleGestureEvent("MozRotateGesture", 0, 0, aDirection, 0, 0);
- aImageElement.clientTop;
-
- let finalExpectedRotation;
-
- if (aAmount < 45 && aStop) {
- // Rotate a bit, then stop. Expect no change at end of gesture.
- finalExpectedRotation = aCurrentRotation;
- }
- else {
- // Either not stopping (expect 90 degree change in aDirection), OR
- // stopping but after 45, (expect 90 degree change in aDirection)
- finalExpectedRotation = (aCurrentRotation +
- (aDirection == clockwise ? 1 : -1) * 90) % 360;
- if (finalExpectedRotation < 0)
- finalExpectedRotation += 360;
- }
-
- is(finalExpectedRotation, test_rotateHelperGetImageRotation(aImageElement),
- "Image rotation gesture end: expected=" + finalExpectedRotation +
- ", observed=" + test_rotateHelperGetImageRotation(aImageElement) +
- ", init=" + aCurrentRotation +
- ", amt=" + aAmount +
- ", dir=" + (aDirection == clockwise ? "cl" : "ccl"));
-}
-
-function test_rotateGesturesOnTab()
-{
- gBrowser.selectedBrowser.removeEventListener("load", test_rotateGesturesOnTab, true);
-
- if (!(content.document instanceof ImageDocument)) {
- ok(false, "Image document failed to open for rotation testing");
- gBrowser.removeTab(test_imageTab);
- finish();
- return;
- }
-
- // easier to type names for the direction constants
- let cl = SimpleGestureEvent.ROTATION_CLOCKWISE;
- let ccl = SimpleGestureEvent.ROTATION_COUNTERCLOCKWISE;
-
- let imgElem = content.document.body &&
- content.document.body.firstElementChild;
-
- if (!imgElem) {
- ok(false, "Could not get image element on ImageDocument for rotation!");
- gBrowser.removeTab(test_imageTab);
- finish();
- return;
- }
-
- // Quick function to normalize rotation to 0 <= r < 360
- var normRot = function(rotation) {
- rotation = rotation % 360;
- if (rotation < 0)
- rotation += 360;
- return rotation;
- }
-
- for (var initRot = 0; initRot < 360; initRot += 90) {
- // Test each case: at each 90 degree snap; cl/ccl;
- // amount more or less than 45; stop and hold or don't (32 total tests)
- // The amount added to the initRot is where it is expected to be
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 0), cl, 35, true );
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 0), cl, 35, false);
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 90), cl, 55, true );
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 180), cl, 55, false);
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 270), ccl, 35, true );
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 270), ccl, 35, false);
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 180), ccl, 55, true );
- test_rotateHelperOneGesture(imgElem, normRot(initRot + 90), ccl, 55, false);
-
- // Manually rotate it 90 degrees clockwise to prepare for next iteration,
- // and force flush
- test_utils.sendSimpleGestureEvent("MozRotateGestureStart", 0, 0, cl, .001, 0);
- test_utils.sendSimpleGestureEvent("MozRotateGestureUpdate", 0, 0, cl, 90, 0);
- test_utils.sendSimpleGestureEvent("MozRotateGestureUpdate", 0, 0, cl, .001, 0);
- test_utils.sendSimpleGestureEvent("MozRotateGesture", 0, 0, cl, 0, 0);
- imgElem.clientTop;
- }
-
- gBrowser.removeTab(test_imageTab);
- test_imageTab = null;
- finish();
-}
-
-function test_rotateGestures()
-{
- test_imageTab = gBrowser.addTab("chrome://branding/content/about-logo.png");
- gBrowser.selectedTab = test_imageTab;
-
- gBrowser.selectedBrowser.addEventListener("load", test_rotateGesturesOnTab, true);
-}
diff --git a/browser/base/content/test/general/browser_getshortcutoruri.js b/browser/base/content/test/general/browser_getshortcutoruri.js
deleted file mode 100644
index 9ebf8e9ca..000000000
--- a/browser/base/content/test/general/browser_getshortcutoruri.js
+++ /dev/null
@@ -1,143 +0,0 @@
-function getPostDataString(aIS) {
- if (!aIS)
- return null;
-
- var sis = Cc["@mozilla.org/scriptableinputstream;1"].
- createInstance(Ci.nsIScriptableInputStream);
- sis.init(aIS);
- var dataLines = sis.read(aIS.available()).split("\n");
-
- // only want the last line
- return dataLines[dataLines.length-1];
-}
-
-function keywordResult(aURL, aPostData, aIsUnsafe) {
- this.url = aURL;
- this.postData = aPostData;
- this.isUnsafe = aIsUnsafe;
-}
-
-function keyWordData() {}
-keyWordData.prototype = {
- init: function(aKeyWord, aURL, aPostData, aSearchWord) {
- this.keyword = aKeyWord;
- this.uri = makeURI(aURL);
- this.postData = aPostData;
- this.searchWord = aSearchWord;
-
- this.method = (this.postData ? "POST" : "GET");
- }
-}
-
-function bmKeywordData(aKeyWord, aURL, aPostData, aSearchWord) {
- this.init(aKeyWord, aURL, aPostData, aSearchWord);
-}
-bmKeywordData.prototype = new keyWordData();
-
-function searchKeywordData(aKeyWord, aURL, aPostData, aSearchWord) {
- this.init(aKeyWord, aURL, aPostData, aSearchWord);
-}
-searchKeywordData.prototype = new keyWordData();
-
-var testData = [
- [new bmKeywordData("bmget", "http://bmget/search=%s", null, "foo"),
- new keywordResult("http://bmget/search=foo", null)],
-
- [new bmKeywordData("bmpost", "http://bmpost/", "search=%s", "foo2"),
- new keywordResult("http://bmpost/", "search=foo2")],
-
- [new bmKeywordData("bmpostget", "http://bmpostget/search1=%s", "search2=%s", "foo3"),
- new keywordResult("http://bmpostget/search1=foo3", "search2=foo3")],
-
- [new bmKeywordData("bmget-nosearch", "http://bmget-nosearch/", null, ""),
- new keywordResult("http://bmget-nosearch/", null)],
-
- [new searchKeywordData("searchget", "http://searchget/?search={searchTerms}", null, "foo4"),
- new keywordResult("http://searchget/?search=foo4", null, true)],
-
- [new searchKeywordData("searchpost", "http://searchpost/", "search={searchTerms}", "foo5"),
- new keywordResult("http://searchpost/", "search=foo5", true)],
-
- [new searchKeywordData("searchpostget", "http://searchpostget/?search1={searchTerms}", "search2={searchTerms}", "foo6"),
- new keywordResult("http://searchpostget/?search1=foo6", "search2=foo6", true)],
-
- // Bookmark keywords that don't take parameters should not be activated if a
- // parameter is passed (bug 420328).
- [new bmKeywordData("bmget-noparam", "http://bmget-noparam/", null, "foo7"),
- new keywordResult(null, null, true)],
- [new bmKeywordData("bmpost-noparam", "http://bmpost-noparam/", "not_a=param", "foo8"),
- new keywordResult(null, null, true)],
-
- // Test escaping (%s = escaped, %S = raw)
- // UTF-8 default
- [new bmKeywordData("bmget-escaping", "http://bmget/?esc=%s&raw=%S", null, "foé"),
- new keywordResult("http://bmget/?esc=fo%C3%A9&raw=foé", null)],
- // Explicitly-defined ISO-8859-1
- [new bmKeywordData("bmget-escaping2", "http://bmget/?esc=%s&raw=%S&mozcharset=ISO-8859-1", null, "foé"),
- new keywordResult("http://bmget/?esc=fo%E9&raw=foé", null)],
-
- // Bug 359809: Test escaping +, /, and @
- // UTF-8 default
- [new bmKeywordData("bmget-escaping", "http://bmget/?esc=%s&raw=%S", null, "+/@"),
- new keywordResult("http://bmget/?esc=%2B%2F%40&raw=+/@", null)],
- // Explicitly-defined ISO-8859-1
- [new bmKeywordData("bmget-escaping2", "http://bmget/?esc=%s&raw=%S&mozcharset=ISO-8859-1", null, "+/@"),
- new keywordResult("http://bmget/?esc=%2B%2F%40&raw=+/@", null)],
-
- // Test using a non-bmKeywordData object, to test the behavior of
- // getShortcutOrURIAndPostData for non-keywords (setupKeywords only adds keywords for
- // bmKeywordData objects)
- [{keyword: "http://gavinsharp.com"},
- new keywordResult(null, null, true)]
-];
-
-add_task(function* test_getshortcutoruri() {
- yield setupKeywords();
-
- for (let item of testData) {
- let [data, result] = item;
-
- let query = data.keyword;
- if (data.searchWord)
- query += " " + data.searchWord;
- let returnedData = yield getShortcutOrURIAndPostData(query);
- // null result.url means we should expect the same query we sent in
- let expected = result.url || query;
- is(returnedData.url, expected, "got correct URL for " + data.keyword);
- is(getPostDataString(returnedData.postData), result.postData, "got correct postData for " + data.keyword);
- is(returnedData.mayInheritPrincipal, !result.isUnsafe, "got correct mayInheritPrincipal for " + data.keyword);
- }
-
- yield cleanupKeywords();
-});
-
-var folder = null;
-var gAddedEngines = [];
-
-function* setupKeywords() {
- folder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "keyword-test" });
- for (let item of testData) {
- let data = item[0];
- if (data instanceof bmKeywordData) {
- yield PlacesUtils.bookmarks.insert({ url: data.uri, parentGuid: folder.guid });
- yield PlacesUtils.keywords.insert({ keyword: data.keyword, url: data.uri.spec, postData: data.postData });
- }
-
- if (data instanceof searchKeywordData) {
- Services.search.addEngineWithDetails(data.keyword, "", data.keyword, "", data.method, data.uri.spec);
- let addedEngine = Services.search.getEngineByName(data.keyword);
- if (data.postData) {
- let [paramName, paramValue] = data.postData.split("=");
- addedEngine.addParam(paramName, paramValue, null);
- }
- gAddedEngines.push(addedEngine);
- }
- }
-}
-
-function* cleanupKeywords() {
- PlacesUtils.bookmarks.remove(folder);
- gAddedEngines.map(Services.search.removeEngine);
-}
diff --git a/browser/base/content/test/general/browser_hide_removing.js b/browser/base/content/test/general/browser_hide_removing.js
deleted file mode 100644
index be62e2d89..000000000
--- a/browser/base/content/test/general/browser_hide_removing.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* 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/. */
-
-// Bug 587922: tabs don't get removed if they're hidden
-
-function test() {
- waitForExplicitFinish();
-
- // Add a tab that will get removed and hidden
- let testTab = gBrowser.addTab("about:blank", {skipAnimation: true});
- is(gBrowser.visibleTabs.length, 2, "just added a tab, so 2 tabs");
- gBrowser.selectedTab = testTab;
-
- let numVisBeforeHide, numVisAfterHide;
- gBrowser.tabContainer.addEventListener("TabSelect", function() {
- gBrowser.tabContainer.removeEventListener("TabSelect", arguments.callee, false);
-
- // While the next tab is being selected, hide the removing tab
- numVisBeforeHide = gBrowser.visibleTabs.length;
- gBrowser.hideTab(testTab);
- numVisAfterHide = gBrowser.visibleTabs.length;
- }, false);
- gBrowser.removeTab(testTab, {animate: true});
-
- // Make sure the tab gets removed at the end of the animation by polling
- (function checkRemoved() {
- return setTimeout(function() {
- if (gBrowser.tabs.length != 1) {
- checkRemoved();
- return;
- }
-
- is(numVisBeforeHide, 1, "animated remove has in 1 tab left");
- is(numVisAfterHide, 1, "hiding a removing tab is also has 1 tab");
- finish();
- }, 50);
- })();
-}
diff --git a/browser/base/content/test/general/browser_homeDrop.js b/browser/base/content/test/general/browser_homeDrop.js
deleted file mode 100644
index 6e87963d5..000000000
--- a/browser/base/content/test/general/browser_homeDrop.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function*() {
- let HOMEPAGE_PREF = "browser.startup.homepage";
-
- let homepageStr = Cc["@mozilla.org/supports-string;1"]
- .createInstance(Ci.nsISupportsString);
- homepageStr.data = "about:mozilla";
- yield pushPrefs([HOMEPAGE_PREF, homepageStr, Ci.nsISupportsString]);
-
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- // Since synthesizeDrop triggers the srcElement, need to use another button.
- let dragSrcElement = document.getElementById("downloads-button");
- ok(dragSrcElement, "Downloads button exists");
- let homeButton = document.getElementById("home-button");
- ok(homeButton, "home button present");
-
- function* drop(dragData, homepage) {
- let setHomepageDialogPromise = BrowserTestUtils.domWindowOpened();
-
- EventUtils.synthesizeDrop(dragSrcElement, homeButton, dragData, "copy", window);
-
- let setHomepageDialog = yield setHomepageDialogPromise;
- ok(true, "dialog appeared in response to home button drop");
- yield BrowserTestUtils.waitForEvent(setHomepageDialog, "load", false);
-
- let setHomepagePromise = new Promise(function(resolve) {
- let observer = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
- observe: function(subject, topic, data) {
- is(topic, "nsPref:changed", "observed correct topic");
- is(data, HOMEPAGE_PREF, "observed correct data");
- let modified = Services.prefs.getComplexValue(HOMEPAGE_PREF,
- Ci.nsISupportsString);
- is(modified.data, homepage, "homepage is set correctly");
- Services.prefs.removeObserver(HOMEPAGE_PREF, observer);
-
- Services.prefs.setComplexValue(HOMEPAGE_PREF,
- Ci.nsISupportsString, homepageStr);
-
- resolve();
- }
- };
- Services.prefs.addObserver(HOMEPAGE_PREF, observer, false);
- });
-
- setHomepageDialog.document.documentElement.acceptDialog();
-
- yield setHomepagePromise;
- }
-
- function dropInvalidURI() {
- return new Promise(resolve => {
- let consoleListener = {
- observe: function (m) {
- if (m.message.includes("NS_ERROR_DOM_BAD_URI")) {
- ok(true, "drop was blocked");
- resolve();
- }
- }
- };
- Services.console.registerListener(consoleListener);
- registerCleanupFunction(function () {
- Services.console.unregisterListener(consoleListener);
- });
-
- executeSoon(function () {
- info("Attempting second drop, of a javascript: URI");
- // The drop handler throws an exception when dragging URIs that inherit
- // principal, e.g. javascript:
- expectUncaughtException();
- EventUtils.synthesizeDrop(dragSrcElement, homeButton, [[{type: "text/plain", data: "javascript:8888"}]], "copy", window);
- });
- });
- }
-
- yield* drop([[{type: "text/plain",
- data: "http://mochi.test:8888/"}]],
- "http://mochi.test:8888/");
- yield* drop([[{type: "text/plain",
- data: "http://mochi.test:8888/\nhttp://mochi.test:8888/b\nhttp://mochi.test:8888/c"}]],
- "http://mochi.test:8888/|http://mochi.test:8888/b|http://mochi.test:8888/c");
- yield dropInvalidURI();
-});
-
diff --git a/browser/base/content/test/general/browser_identity_UI.js b/browser/base/content/test/general/browser_identity_UI.js
deleted file mode 100644
index 5aacb2e79..000000000
--- a/browser/base/content/test/general/browser_identity_UI.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/* Tests for correct behaviour of getEffectiveHost on identity handler */
-
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(2);
-
- ok(gIdentityHandler, "gIdentityHandler should exist");
-
- BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", true).then(() => {
- gBrowser.selectedBrowser.addEventListener("load", checkResult, true);
- nextTest();
- });
-}
-
-// Greek IDN for 'example.test'.
-var idnDomain = "\u03C0\u03B1\u03C1\u03AC\u03B4\u03B5\u03B9\u03B3\u03BC\u03B1.\u03B4\u03BF\u03BA\u03B9\u03BC\u03AE";
-var tests = [
- {
- name: "normal domain",
- location: "http://test1.example.org/",
- effectiveHost: "test1.example.org"
- },
- {
- name: "view-source",
- location: "view-source:http://example.com/",
- effectiveHost: null
- },
- {
- name: "normal HTTPS",
- location: "https://example.com/",
- effectiveHost: "example.com",
- isHTTPS: true
- },
- {
- name: "IDN subdomain",
- location: "http://sub1." + idnDomain + "/",
- effectiveHost: "sub1." + idnDomain
- },
- {
- name: "subdomain with port",
- location: "http://sub1.test1.example.org:8000/",
- effectiveHost: "sub1.test1.example.org"
- },
- {
- name: "subdomain HTTPS",
- location: "https://test1.example.com/",
- effectiveHost: "test1.example.com",
- isHTTPS: true
- },
- {
- name: "view-source HTTPS",
- location: "view-source:https://example.com/",
- effectiveHost: null,
- isHTTPS: true
- },
- {
- name: "IP address",
- location: "http://127.0.0.1:8888/",
- effectiveHost: "127.0.0.1"
- },
-]
-
-var gCurrentTest, gCurrentTestIndex = -1, gTestDesc, gPopupHidden;
-// Go through the tests in both directions, to add additional coverage for
-// transitions between different states.
-var gForward = true;
-var gCheckETLD = false;
-function nextTest() {
- if (!gCheckETLD) {
- if (gForward)
- gCurrentTestIndex++;
- else
- gCurrentTestIndex--;
-
- if (gCurrentTestIndex == tests.length) {
- // Went too far, reverse
- gCurrentTestIndex--;
- gForward = false;
- }
-
- if (gCurrentTestIndex == -1) {
- gBrowser.selectedBrowser.removeEventListener("load", checkResult, true);
- gBrowser.removeCurrentTab();
- finish();
- return;
- }
-
- gCurrentTest = tests[gCurrentTestIndex];
- gTestDesc = "#" + gCurrentTestIndex + " (" + gCurrentTest.name + ")";
- if (!gForward)
- gTestDesc += " (second time)";
- if (gCurrentTest.isHTTPS) {
- gCheckETLD = true;
- }
-
- // Navigate to the next page, which will cause checkResult to fire.
- let spec = gBrowser.selectedBrowser.currentURI.spec;
- if (spec == "about:blank" || spec == gCurrentTest.location) {
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, gCurrentTest.location);
- } else {
- // Open the Control Center and make sure it closes after nav (Bug 1207542).
- let popupShown = promisePopupShown(gIdentityHandler._identityPopup);
- gPopupHidden = promisePopupHidden(gIdentityHandler._identityPopup);
- gIdentityHandler._identityBox.click();
- info("Waiting for the Control Center to be shown");
- popupShown.then(() => {
- is_element_visible(gIdentityHandler._identityPopup, "Control Center is visible");
- // Show the subview, which is an easy way in automation to reproduce
- // Bug 1207542, where the CC wouldn't close on navigation.
- gBrowser.ownerDocument.querySelector("#identity-popup-security-expander").click();
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, gCurrentTest.location);
- });
- }
- } else {
- gCheckETLD = false;
- gTestDesc = "#" + gCurrentTestIndex + " (" + gCurrentTest.name + " without eTLD in identity icon label)";
- if (!gForward)
- gTestDesc += " (second time)";
- gBrowser.selectedBrowser.reloadWithFlags(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE |
- Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY);
- }
-}
-
-function checkResult() {
- // Sanity check other values, and the value of gIdentityHandler.getEffectiveHost()
- is(gIdentityHandler._uri.spec, gCurrentTest.location, "location matches for test " + gTestDesc);
- // getEffectiveHost can't be called for all modes
- if (gCurrentTest.effectiveHost === null) {
- let identityBox = document.getElementById("identity-box");
- ok(identityBox.className == "unknownIdentity" ||
- identityBox.className == "chromeUI", "mode matched");
- } else {
- is(gIdentityHandler.getEffectiveHost(), gCurrentTest.effectiveHost, "effectiveHost matches for test " + gTestDesc);
- }
-
- if (gPopupHidden) {
- info("Waiting for the Control Center to hide");
- gPopupHidden.then(() => {
- gPopupHidden = null;
- is_element_hidden(gIdentityHandler._identityPopup, "control center is hidden");
- executeSoon(nextTest);
- });
- } else {
- executeSoon(nextTest);
- }
-}
diff --git a/browser/base/content/test/general/browser_insecureLoginForms.js b/browser/base/content/test/general/browser_insecureLoginForms.js
deleted file mode 100644
index 72db7dbe6..000000000
--- a/browser/base/content/test/general/browser_insecureLoginForms.js
+++ /dev/null
@@ -1,162 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Load directly from the browser-chrome support files of login tests.
-const TEST_URL_PATH = "/browser/toolkit/components/passwordmgr/test/browser/";
-
-/**
- * Waits for the given number of occurrences of InsecureLoginFormsStateChange
- * on the given browser element.
- */
-function waitForInsecureLoginFormsStateChange(browser, count) {
- return BrowserTestUtils.waitForEvent(browser, "InsecureLoginFormsStateChange",
- false, () => --count == 0);
-}
-
-/**
- * Checks the insecure login forms logic for the identity block.
- */
-add_task(function* test_simple() {
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({
- "set": [["security.insecure_password.ui.enabled", true]],
- }, resolve));
-
- for (let [origin, expectWarning] of [
- ["http://example.com", true],
- ["http://127.0.0.1", false],
- ["https://example.com", false],
- ]) {
- let testUrlPath = origin + TEST_URL_PATH;
- let tab = gBrowser.addTab(testUrlPath + "form_basic.html");
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.switchTab(gBrowser, tab),
- BrowserTestUtils.browserLoaded(browser),
- // One event is triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 2),
- ]);
-
- let { gIdentityHandler } = gBrowser.ownerGlobal;
- gIdentityHandler._identityBox.click();
- document.getElementById("identity-popup-security-expander").click();
-
- if (expectWarning) {
- is_element_visible(document.getElementById("connection-icon"));
- let connectionIconImage = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("connection-icon"), "")
- .getPropertyValue("list-style-image");
- let securityViewBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-securityView"), "")
- .getPropertyValue("background-image");
- let securityContentBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-security-content"), "")
- .getPropertyValue("background-image");
- is(connectionIconImage,
- "url(\"chrome://browser/skin/connection-mixed-active-loaded.svg#icon\")",
- "Using expected icon image in the identity block");
- is(securityViewBG,
- "url(\"chrome://browser/skin/controlcenter/mcb-disabled.svg\")",
- "Using expected icon image in the Control Center main view");
- is(securityContentBG,
- "url(\"chrome://browser/skin/controlcenter/mcb-disabled.svg\")",
- "Using expected icon image in the Control Center subview");
- is(Array.filter(document.querySelectorAll("[observes=identity-popup-insecure-login-forms-learn-more]"),
- element => !is_hidden(element)).length, 1,
- "The 'Learn more' link should be visible once.");
- }
-
- // Messages should be visible when the scheme is HTTP, and invisible when
- // the scheme is HTTPS.
- is(Array.every(document.querySelectorAll("[when-loginforms=insecure]"),
- element => !is_hidden(element)),
- expectWarning,
- "The relevant messages should be visible or hidden.");
-
- gIdentityHandler._identityPopup.hidden = true;
- gBrowser.removeTab(tab);
- }
-});
-
-/**
- * Checks that the insecure login forms logic does not regress mixed content
- * blocking messages when mixed active content is loaded.
- */
-add_task(function* test_mixedcontent() {
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({
- "set": [["security.mixed_content.block_active_content", false]],
- }, resolve));
-
- // Load the page with the subframe in a new tab.
- let testUrlPath = "://example.com" + TEST_URL_PATH;
- let tab = gBrowser.addTab("https" + testUrlPath + "insecure_test.html");
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.switchTab(gBrowser, tab),
- BrowserTestUtils.browserLoaded(browser),
- // Two events are triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 3),
- ]);
-
- assertMixedContentBlockingState(browser, { activeLoaded: true,
- activeBlocked: false,
- passiveLoaded: false });
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * Checks that insecure window.opener does not trigger a warning.
- */
-add_task(function* test_ignoring_window_opener() {
- let newTabURL = "https://example.com" + TEST_URL_PATH + "form_basic.html";
- let path = getRootDirectory(gTestPath)
- .replace("chrome://mochitests/content", "http://example.com");
- let url = path + "insecure_opener.html";
-
- yield BrowserTestUtils.withNewTab(url, function*(browser) {
- // Clicking the link will spawn a new tab.
- let loaded = BrowserTestUtils.waitForNewTab(gBrowser, newTabURL);
- yield ContentTask.spawn(browser, {}, function() {
- content.document.getElementById("link").click();
- });
- let tab = yield loaded;
- browser = tab.linkedBrowser;
- yield waitForInsecureLoginFormsStateChange(browser, 2);
-
- // Open the identity popup.
- let { gIdentityHandler } = gBrowser.ownerGlobal;
- gIdentityHandler._identityBox.click();
- document.getElementById("identity-popup-security-expander").click();
-
- ok(is_visible(document.getElementById("connection-icon")),
- "Connection icon is visible");
-
- // Assert that the identity indicators are still "secure".
- let connectionIconImage = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("connection-icon"))
- .getPropertyValue("list-style-image");
- let securityViewBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-securityView"))
- .getPropertyValue("background-image");
- let securityContentBG = gBrowser.ownerGlobal
- .getComputedStyle(document.getElementById("identity-popup-security-content"))
- .getPropertyValue("background-image");
- is(connectionIconImage,
- "url(\"chrome://browser/skin/connection-secure.svg\")",
- "Using expected icon image in the identity block");
- is(securityViewBG,
- "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-secure\")",
- "Using expected icon image in the Control Center main view");
- is(securityContentBG,
- "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-secure\")",
- "Using expected icon image in the Control Center subview");
-
- ok(Array.every(document.querySelectorAll("[when-loginforms=insecure]"),
- element => is_hidden(element)),
- "All messages should be hidden.");
-
- gIdentityHandler._identityPopup.hidden = true;
-
- yield BrowserTestUtils.removeTab(tab);
- });
-});
diff --git a/browser/base/content/test/general/browser_invalid_uri_back_forward_manipulation.js b/browser/base/content/test/general/browser_invalid_uri_back_forward_manipulation.js
deleted file mode 100644
index 8e69e781b..000000000
--- a/browser/base/content/test/general/browser_invalid_uri_back_forward_manipulation.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-
-
-/**
- * Verify that loading an invalid URI does not clobber a previously-loaded page's history
- * entry, but that the invalid URI gets its own history entry instead. We're checking this
- * using nsIWebNavigation's canGoBack, as well as actually going back and then checking
- * canGoForward.
- */
-add_task(function* checkBackFromInvalidURI() {
- yield pushPrefs(["keyword.enabled", false]);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots", true);
- gURLBar.value = "::2600";
- gURLBar.focus();
-
- let promiseErrorPageLoaded = new Promise(resolve => {
- tab.linkedBrowser.addEventListener("DOMContentLoaded", function onLoad() {
- tab.linkedBrowser.removeEventListener("DOMContentLoaded", onLoad, false, true);
- resolve();
- }, false, true);
- });
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield promiseErrorPageLoaded;
-
- ok(gBrowser.webNavigation.canGoBack, "Should be able to go back");
- if (gBrowser.webNavigation.canGoBack) {
- // Can't use DOMContentLoaded here because the page is bfcached. Can't use pageshow for
- // the error page because it doesn't seem to fire for those.
- let promiseOtherPageLoaded = BrowserTestUtils.waitForEvent(tab.linkedBrowser, "pageshow", false,
- // Be paranoid we *are* actually seeing this other page load, not some kind of race
- // for if/when we do start firing pageshow for the error page...
- function(e) { return gBrowser.currentURI.spec == "about:robots" }
- );
- gBrowser.goBack();
- yield promiseOtherPageLoaded;
- ok(gBrowser.webNavigation.canGoForward, "Should be able to go forward from previous page.");
- }
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_keywordBookmarklets.js b/browser/base/content/test/general/browser_keywordBookmarklets.js
deleted file mode 100644
index 5e94733fe..000000000
--- a/browser/base/content/test/general/browser_keywordBookmarklets.js
+++ /dev/null
@@ -1,54 +0,0 @@
-"use strict"
-
-add_task(function* test_keyword_bookmarklet() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmarklet",
- url: "javascript:'1';" });
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- registerCleanupFunction (function* () {
- gBrowser.removeTab(tab);
- yield PlacesUtils.bookmarks.remove(bm);
- });
- yield promisePageShow();
- let originalPrincipal = gBrowser.contentPrincipal;
-
- function getPrincipalURI() {
- return ContentTask.spawn(tab.linkedBrowser, null, function() {
- return content.document.nodePrincipal.URI.spec;
- });
- }
-
- let originalPrincipalURI = yield getPrincipalURI();
-
- yield PlacesUtils.keywords.insert({ keyword: "bm", url: "javascript:'1';" })
-
- // Enter bookmarklet keyword in the URL bar
- gURLBar.value = "bm";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- yield promisePageShow();
-
- let newPrincipalURI = yield getPrincipalURI();
- is(newPrincipalURI, originalPrincipalURI, "content has the same principal");
-
- // In e10s, null principals don't round-trip so the same null principal sent
- // from the child will be a new null principal. Verify that this is the
- // case.
- if (tab.linkedBrowser.isRemoteBrowser) {
- ok(originalPrincipal.isNullPrincipal && gBrowser.contentPrincipal.isNullPrincipal,
- "both principals should be null principals in the parent");
- } else {
- ok(gBrowser.contentPrincipal.equals(originalPrincipal),
- "javascript bookmarklet should inherit principal");
- }
-});
-
-function* promisePageShow() {
- return new Promise(resolve => {
- gBrowser.selectedBrowser.addEventListener("pageshow", function listen() {
- gBrowser.selectedBrowser.removeEventListener("pageshow", listen);
- resolve();
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_keywordSearch.js b/browser/base/content/test/general/browser_keywordSearch.js
deleted file mode 100644
index cf8bd0c0e..000000000
--- a/browser/base/content/test/general/browser_keywordSearch.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- **/
-
-var gTests = [
- {
- name: "normal search (search service)",
- testText: "test search",
- searchURL: Services.search.defaultEngine.getSubmission("test search", null, "keyword").uri.spec
- },
- {
- name: "?-prefixed search (search service)",
- testText: "? foo ",
- searchURL: Services.search.defaultEngine.getSubmission("foo", null, "keyword").uri.spec
- }
-];
-
-function test() {
- waitForExplicitFinish();
-
- let windowObserver = {
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- ok(false, "Alert window opened");
- let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- win.addEventListener("load", function() {
- win.removeEventListener("load", arguments.callee, false);
- win.close();
- }, false);
- executeSoon(finish);
- }
- }
- };
-
- Services.ww.registerNotification(windowObserver);
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onLocationChange(webProgress, req, flags, status) {
- // Only care about document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart))
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- };
- gBrowser.addProgressListener(listener);
-
- registerCleanupFunction(function () {
- Services.ww.unregisterNotification(windowObserver);
-
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- });
-
- nextTest();
-}
-
-var gCurrTest;
-function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- doTest();
- } else {
- finish();
- }
-}
-
-function doTest() {
- info("Running test: " + gCurrTest.name);
-
- // Simulate a user entering search terms
- gURLBar.value = gCurrTest.testText;
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
-}
diff --git a/browser/base/content/test/general/browser_keywordSearch_postData.js b/browser/base/content/test/general/browser_keywordSearch_postData.js
deleted file mode 100644
index 3f700fa58..000000000
--- a/browser/base/content/test/general/browser_keywordSearch_postData.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- **/
-
-var gTests = [
- {
- name: "normal search (search service)",
- testText: "test search",
- expectText: "test+search"
- },
- {
- name: "?-prefixed search (search service)",
- testText: "? foo ",
- expectText: "foo"
- }
-];
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let searchObserver = function search_observer(aSubject, aTopic, aData) {
- let engine = aSubject.QueryInterface(Ci.nsISearchEngine);
- info("Observer: " + aData + " for " + engine.name);
-
- if (aData != "engine-added")
- return;
-
- if (engine.name != "POST Search")
- return;
-
- Services.search.defaultEngine = engine;
-
- registerCleanupFunction(function () {
- Services.search.removeEngine(engine);
- });
-
- // ready to execute the tests!
- executeSoon(nextTest);
- };
-
- Services.obs.addObserver(searchObserver, "browser-search-engine-modified", false);
-
- registerCleanupFunction(function () {
- gBrowser.removeTab(tab);
-
- Services.obs.removeObserver(searchObserver, "browser-search-engine-modified");
- });
-
- Services.search.addEngine("http://test:80/browser/browser/base/content/test/general/POSTSearchEngine.xml",
- null, null, false);
-}
-
-var gCurrTest;
-function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- doTest();
- } else {
- finish();
- }
-}
-
-function doTest() {
- info("Running test: " + gCurrTest.name);
-
- waitForLoad(function () {
- let loadedText = gBrowser.contentDocument.body.textContent;
- ok(loadedText, "search page loaded");
- let needle = "searchterms=" + gCurrTest.expectText;
- is(loadedText, needle, "The query POST data should be returned in the response");
- nextTest();
- });
-
- // Simulate a user entering search terms
- gURLBar.value = gCurrTest.testText;
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
-}
-
-
-function waitForLoad(cb) {
- let browser = gBrowser.selectedBrowser;
- browser.addEventListener("load", function listener() {
- if (browser.currentURI.spec == "about:blank")
- return;
- info("Page loaded: " + browser.currentURI.spec);
- browser.removeEventListener("load", listener, true);
-
- cb();
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_lastAccessedTab.js b/browser/base/content/test/general/browser_lastAccessedTab.js
deleted file mode 100644
index 57bd330ae..000000000
--- a/browser/base/content/test/general/browser_lastAccessedTab.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// gBrowser.selectedTab.lastAccessed and Date.now() called from this test can't
-// run concurrently, and therefore don't always match exactly.
-const CURRENT_TIME_TOLERANCE_MS = 15;
-
-function isCurrent(tab, msg) {
- const DIFF = Math.abs(Date.now() - tab.lastAccessed);
- ok(DIFF <= CURRENT_TIME_TOLERANCE_MS, msg + " (difference: " + DIFF + ")");
-}
-
-function nextStep(fn) {
- setTimeout(fn, CURRENT_TIME_TOLERANCE_MS + 10);
-}
-
-var originalTab;
-var newTab;
-
-function test() {
- waitForExplicitFinish();
-
- originalTab = gBrowser.selectedTab;
- nextStep(step2);
-}
-
-function step2() {
- isCurrent(originalTab, "selected tab has the current timestamp");
- newTab = gBrowser.addTab("about:blank", {skipAnimation: true});
- nextStep(step3);
-}
-
-function step3() {
- ok(newTab.lastAccessed < Date.now(), "new tab hasn't been selected so far");
- gBrowser.selectedTab = newTab;
- isCurrent(newTab, "new tab has the current timestamp after being selected");
- nextStep(step4);
-}
-
-function step4() {
- ok(originalTab.lastAccessed < Date.now(),
- "original tab has old timestamp after being deselected");
- isCurrent(newTab, "new tab has the current timestamp since it's still selected");
-
- gBrowser.removeTab(newTab);
- finish();
-}
diff --git a/browser/base/content/test/general/browser_mcb_redirect.js b/browser/base/content/test/general/browser_mcb_redirect.js
deleted file mode 100644
index 41b4e9468..000000000
--- a/browser/base/content/test/general/browser_mcb_redirect.js
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Description of the Tests for
- * - Bug 418354 - Call Mixed content blocking on redirects
- *
- * Single redirect script tests
- * 1. Load a script over https inside an https page
- * - the server responds with a 302 redirect to a >> HTTP << script
- * - the doorhanger should appear!
- *
- * 2. Load a script over https inside an http page
- * - the server responds with a 302 redirect to a >> HTTP << script
- * - the doorhanger should not appear!
- *
- * Single redirect image tests
- * 3. Load an image over https inside an https page
- * - the server responds with a 302 redirect to a >> HTTP << image
- * - the image should not load
- *
- * 4. Load an image over https inside an http page
- * - the server responds with a 302 redirect to a >> HTTP << image
- * - the image should load and get cached
- *
- * Single redirect cached image tests
- * 5. Using offline mode to ensure we hit the cache, load a cached image over
- * https inside an http page
- * - the server would have responded with a 302 redirect to a >> HTTP <<
- * image, but instead we try to use the cached image.
- * - the image should load
- *
- * 6. Using offline mode to ensure we hit the cache, load a cached image over
- * https inside an https page
- * - the server would have responded with a 302 redirect to a >> HTTP <<
- * image, but instead we try to use the cached image.
- * - the image should not load
- *
- * Double redirect image test
- * 7. Load an image over https inside an http page
- * - the server responds with a 302 redirect to a >> HTTP << server
- * - the HTTP server responds with a 302 redirect to a >> HTTPS << image
- * - the image should load and get cached
- *
- * Double redirect cached image tests
- * 8. Using offline mode to ensure we hit the cache, load a cached image over
- * https inside an http page
- * - the image would have gone through two redirects: HTTPS->HTTP->HTTPS,
- * but instead we try to use the cached image.
- * - the image should load
- *
- * 9. Using offline mode to ensure we hit the cache, load a cached image over
- * https inside an https page
- * - the image would have gone through two redirects: HTTPS->HTTP->HTTPS,
- * but instead we try to use the cached image.
- * - the image should not load
- */
-
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-const PREF_DISPLAY = "security.mixed_content.block_display_content";
-const gHttpsTestRoot = "https://example.com/browser/browser/base/content/test/general/";
-const gHttpTestRoot = "http://example.com/browser/browser/base/content/test/general/";
-
-var origBlockActive;
-var origBlockDisplay;
-var gTestBrowser = null;
-
-// ------------------------ Helper Functions ---------------------
-
-registerCleanupFunction(function() {
- // Set preferences back to their original values
- Services.prefs.setBoolPref(PREF_ACTIVE, origBlockActive);
- Services.prefs.setBoolPref(PREF_DISPLAY, origBlockDisplay);
-
- // Make sure we are online again
- Services.io.offline = false;
-});
-
-function cleanUpAfterTests() {
- gBrowser.removeCurrentTab();
- window.focus();
- finish();
-}
-
-function waitForCondition(condition, nextTest, errorMsg, okMsg) {
- var tries = 0;
- var interval = setInterval(function() {
- if (tries >= 30) {
- ok(false, errorMsg);
- moveOn();
- }
- if (condition()) {
- ok(true, okMsg)
- moveOn();
- }
- tries++;
- }, 500);
- var moveOn = function() {
- clearInterval(interval); nextTest();
- };
-}
-
-// ------------------------ Test 1 ------------------------------
-
-function test1() {
- gTestBrowser.addEventListener("load", checkUIForTest1, true);
- var url = gHttpsTestRoot + "test_mcb_redirect.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkUIForTest1() {
- gTestBrowser.removeEventListener("load", checkUIForTest1, true);
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-
- var expected = "script blocked";
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test2, "Error: Waited too long for status in Test 1!",
- "OK: Expected result in innerHTML for Test1!");
-}
-
-// ------------------------ Test 2 ------------------------------
-
-function test2() {
- gTestBrowser.addEventListener("load", checkUIForTest2, true);
- var url = gHttpTestRoot + "test_mcb_redirect.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkUIForTest2() {
- gTestBrowser.removeEventListener("load", checkUIForTest2, true);
-
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: false});
-
- var expected = "script executed";
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test3, "Error: Waited too long for status in Test 2!",
- "OK: Expected result in innerHTML for Test2!");
-}
-
-// ------------------------ Test 3 ------------------------------
-// HTTPS page loading insecure image
-function test3() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest3, true);
- var url = gHttpsTestRoot + "test_mcb_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest3() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest3, true);
-
- var expected = "image blocked"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test4, "Error: Waited too long for status in Test 3!",
- "OK: Expected result in innerHTML for Test3!");
-}
-
-// ------------------------ Test 4 ------------------------------
-// HTTP page loading insecure image
-function test4() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest4, true);
- var url = gHttpTestRoot + "test_mcb_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest4() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest4, true);
-
- var expected = "image loaded"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test5, "Error: Waited too long for status in Test 4!",
- "OK: Expected result in innerHTML for Test4!");
-}
-
-// ------------------------ Test 5 ------------------------------
-// HTTP page laoding insecure cached image
-// Assuming test 4 succeeded, the image has already been loaded once
-// and hence should be cached per the sjs cache-control header
-// Going into offline mode to ensure we are loading from the cache.
-function test5() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest5, true);
- // Go into offline mode
- Services.io.offline = true;
- var url = gHttpTestRoot + "test_mcb_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest5() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest5, true);
-
- var expected = "image loaded"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test6, "Error: Waited too long for status in Test 5!",
- "OK: Expected result in innerHTML for Test5!");
- // Go back online
- Services.io.offline = false;
-}
-
-// ------------------------ Test 6 ------------------------------
-// HTTPS page loading insecure cached image
-// Assuming test 4 succeeded, the image has already been loaded once
-// and hence should be cached per the sjs cache-control header
-// Going into offline mode to ensure we are loading from the cache.
-function test6() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest6, true);
- // Go into offline mode
- Services.io.offline = true;
- var url = gHttpsTestRoot + "test_mcb_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest6() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest6, true);
-
- var expected = "image blocked"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test7, "Error: Waited too long for status in Test 6!",
- "OK: Expected result in innerHTML for Test6!");
- // Go back online
- Services.io.offline = false;
-}
-
-// ------------------------ Test 7 ------------------------------
-// HTTP page loading insecure image that went through a double redirect
-function test7() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest7, true);
- var url = gHttpTestRoot + "test_mcb_double_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest7() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest7, true);
-
- var expected = "image loaded"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test8, "Error: Waited too long for status in Test 7!",
- "OK: Expected result in innerHTML for Test7!");
-}
-
-// ------------------------ Test 8 ------------------------------
-// HTTP page loading insecure cached image that went through a double redirect
-// Assuming test 7 succeeded, the image has already been loaded once
-// and hence should be cached per the sjs cache-control header
-// Going into offline mode to ensure we are loading from the cache.
-function test8() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest8, true);
- // Go into offline mode
- Services.io.offline = true;
- var url = gHttpTestRoot + "test_mcb_double_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest8() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest8, true);
-
- var expected = "image loaded"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- test9, "Error: Waited too long for status in Test 8!",
- "OK: Expected result in innerHTML for Test8!");
- // Go back online
- Services.io.offline = false;
-}
-
-// ------------------------ Test 9 ------------------------------
-// HTTPS page loading insecure cached image that went through a double redirect
-// Assuming test 7 succeeded, the image has already been loaded once
-// and hence should be cached per the sjs cache-control header
-// Going into offline mode to ensure we are loading from the cache.
-function test9() {
- gTestBrowser.addEventListener("load", checkLoadEventForTest9, true);
- // Go into offline mode
- Services.io.offline = true;
- var url = gHttpsTestRoot + "test_mcb_double_redirect_image.html"
- gTestBrowser.contentWindow.location = url;
-}
-
-function checkLoadEventForTest9() {
- gTestBrowser.removeEventListener("load", checkLoadEventForTest9, true);
-
- var expected = "image blocked"
- waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
- cleanUpAfterTests, "Error: Waited too long for status in Test 9!",
- "OK: Expected result in innerHTML for Test9!");
- // Go back online
- Services.io.offline = false;
-}
-
-// ------------------------ SETUP ------------------------------
-
-function test() {
- // Performing async calls, e.g. 'onload', we have to wait till all of them finished
- waitForExplicitFinish();
-
- // Store original preferences so we can restore settings after testing
- origBlockActive = Services.prefs.getBoolPref(PREF_ACTIVE);
- origBlockDisplay = Services.prefs.getBoolPref(PREF_DISPLAY);
- Services.prefs.setBoolPref(PREF_ACTIVE, true);
- Services.prefs.setBoolPref(PREF_DISPLAY, true);
-
- pushPrefs(["dom.ipc.processCount", 1]).then(() => {
- var newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
- newTab.linkedBrowser.stop();
-
- executeSoon(test1);
- });
-}
diff --git a/browser/base/content/test/general/browser_menuButtonBadgeManager.js b/browser/base/content/test/general/browser_menuButtonBadgeManager.js
deleted file mode 100644
index 9afe39ab7..000000000
--- a/browser/base/content/test/general/browser_menuButtonBadgeManager.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-var menuButton = document.getElementById("PanelUI-menu-button");
-
-add_task(function* testButtonActivities() {
- is(menuButton.hasAttribute("badge-status"), false, "Should not have a badge status");
- is(menuButton.hasAttribute("badge"), false, "Should not have the badge attribute set");
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_FXA, "fxa-needs-authentication");
- is(menuButton.getAttribute("badge-status"), "fxa-needs-authentication", "Should have fxa-needs-authentication badge status");
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE, "update-succeeded");
- is(menuButton.getAttribute("badge-status"), "update-succeeded", "Should have update-succeeded badge status (update > fxa)");
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE, "update-failed");
- is(menuButton.getAttribute("badge-status"), "update-failed", "Should have update-failed badge status");
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_DOWNLOAD, "download-severe");
- is(menuButton.getAttribute("badge-status"), "download-severe", "Should have download-severe badge status");
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_DOWNLOAD, "download-warning");
- is(menuButton.getAttribute("badge-status"), "download-warning", "Should have download-warning badge status");
-
- gMenuButtonBadgeManager.addBadge("unknownbadge", "attr");
- is(menuButton.getAttribute("badge-status"), "download-warning", "Should not have changed badge status");
-
- gMenuButtonBadgeManager.removeBadge(gMenuButtonBadgeManager.BADGEID_DOWNLOAD);
- is(menuButton.getAttribute("badge-status"), "update-failed", "Should have update-failed badge status");
-
- gMenuButtonBadgeManager.removeBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE);
- is(menuButton.getAttribute("badge-status"), "fxa-needs-authentication", "Should have fxa-needs-authentication badge status");
-
- gMenuButtonBadgeManager.removeBadge(gMenuButtonBadgeManager.BADGEID_FXA);
- is(menuButton.hasAttribute("badge-status"), false, "Should not have a badge status");
-
- yield PanelUI.show();
- is(menuButton.hasAttribute("badge-status"), false, "Should not have a badge status (Hamburger menu opened)");
- PanelUI.hide();
-
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_FXA, "fxa-needs-authentication");
- gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE, "update-succeeded");
- gMenuButtonBadgeManager.clearBadges();
- is(menuButton.hasAttribute("badge-status"), false, "Should not have a badge status (clearBadges called)");
-});
diff --git a/browser/base/content/test/general/browser_menuButtonFitts.js b/browser/base/content/test/general/browser_menuButtonFitts.js
deleted file mode 100644
index e2541b925..000000000
--- a/browser/base/content/test/general/browser_menuButtonFitts.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function test () {
- waitForExplicitFinish();
- window.maximize();
-
- // Find where the nav-bar is vertically.
- var navBar = document.getElementById("nav-bar");
- var boundingRect = navBar.getBoundingClientRect();
- var yPixel = boundingRect.top + Math.floor(boundingRect.height / 2);
- var xPixel = boundingRect.width - 1; // Use the last pixel of the screen since it is maximized.
-
- function onPopupHidden() {
- PanelUI.panel.removeEventListener("popuphidden", onPopupHidden);
- window.restore();
- finish();
- }
- function onPopupShown() {
- PanelUI.panel.removeEventListener("popupshown", onPopupShown);
- ok(true, "Clicking at the far edge of the window opened the menu popup.");
- PanelUI.panel.addEventListener("popuphidden", onPopupHidden);
- PanelUI.hide();
- }
- registerCleanupFunction(function() {
- PanelUI.panel.removeEventListener("popupshown", onPopupShown);
- PanelUI.panel.removeEventListener("popuphidden", onPopupHidden);
- });
- PanelUI.panel.addEventListener("popupshown", onPopupShown);
- EventUtils.synthesizeMouseAtPoint(xPixel, yPixel, {}, window);
-}
diff --git a/browser/base/content/test/general/browser_middleMouse_noJSPaste.js b/browser/base/content/test/general/browser_middleMouse_noJSPaste.js
deleted file mode 100644
index fa0c26f78..000000000
--- a/browser/base/content/test/general/browser_middleMouse_noJSPaste.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const middleMousePastePref = "middlemouse.contentLoadURL";
-const autoScrollPref = "general.autoScroll";
-
-add_task(function* () {
- yield pushPrefs([middleMousePastePref, true], [autoScrollPref, false]);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- let url = "javascript:http://www.example.com/";
- yield new Promise((resolve, reject) => {
- SimpleTest.waitForClipboard(url, () => {
- Components.classes["@mozilla.org/widget/clipboardhelper;1"]
- .getService(Components.interfaces.nsIClipboardHelper)
- .copyString(url);
- }, resolve, () => {
- ok(false, "Clipboard copy failed");
- reject();
- });
- });
-
- let middlePagePromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- // Middle click on the content area
- info("Middle clicking");
- yield BrowserTestUtils.synthesizeMouse(null, 10, 10, {button: 1}, gBrowser.selectedBrowser);
- yield middlePagePromise;
-
- is(gBrowser.currentURI.spec, url.replace(/^javascript:/, ""), "url loaded by middle click doesn't include JS");
-
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_minimize.js b/browser/base/content/test/general/browser_minimize.js
deleted file mode 100644
index 1d761c0da..000000000
--- a/browser/base/content/test/general/browser_minimize.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function *() {
- registerCleanupFunction(function() {
- window.restore();
- });
- function waitForActive() { return gBrowser.selectedTab.linkedBrowser.docShellIsActive; }
- function waitForInactive() { return !gBrowser.selectedTab.linkedBrowser.docShellIsActive; }
- yield promiseWaitForCondition(waitForActive);
- is(gBrowser.selectedTab.linkedBrowser.docShellIsActive, true, "Docshell should be active");
- window.minimize();
- yield promiseWaitForCondition(waitForInactive);
- is(gBrowser.selectedTab.linkedBrowser.docShellIsActive, false, "Docshell should be Inactive");
- window.restore();
- yield promiseWaitForCondition(waitForActive);
- is(gBrowser.selectedTab.linkedBrowser.docShellIsActive, true, "Docshell should be active again");
-});
diff --git a/browser/base/content/test/general/browser_misused_characters_in_strings.js b/browser/base/content/test/general/browser_misused_characters_in_strings.js
deleted file mode 100644
index fe8022662..000000000
--- a/browser/base/content/test/general/browser_misused_characters_in_strings.js
+++ /dev/null
@@ -1,244 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* This list allows pre-existing or 'unfixable' issues to remain, while we
- * detect newly occurring issues in shipping files. It is a list of objects
- * specifying conditions under which an error should be ignored.
- *
- * As each issue is found in the whitelist, it is removed from the list. At
- * the end of the test, there is an assertion that all items have been
- * removed from the whitelist, thus ensuring there are no stale entries. */
-let gWhitelist = [{
- file: "search.properties",
- key: "searchForSomethingWith",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "certerror.introPara",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "weakCryptoAdvanced.longDesc",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "weakCryptoAdvanced.override",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "inadequateSecurityError.longDesc",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "certerror.wrongSystemTime",
- type: "single-quote"
- }, {
- file: "phishing-afterload-warning-message.dtd",
- key: "safeb.blocked.malwarePage.shortDesc",
- type: "single-quote"
- }, {
- file: "phishing-afterload-warning-message.dtd",
- key: "safeb.blocked.unwantedPage.shortDesc",
- type: "single-quote"
- }, {
- file: "phishing-afterload-warning-message.dtd",
- key: "safeb.blocked.phishingPage.shortDesc2",
- type: "single-quote"
- }, {
- file: "mathfont.properties",
- key: "operator.\\u002E\\u002E\\u002E.postfix",
- type: "ellipsis"
- }, {
- file: "layout_errors.properties",
- key: "ImageMapRectBoundsError",
- type: "double-quote"
- }, {
- file: "layout_errors.properties",
- key: "ImageMapCircleWrongNumberOfCoords",
- type: "double-quote"
- }, {
- file: "layout_errors.properties",
- key: "ImageMapCircleNegativeRadius",
- type: "double-quote"
- }, {
- file: "layout_errors.properties",
- key: "ImageMapPolyWrongNumberOfCoords",
- type: "double-quote"
- }, {
- file: "layout_errors.properties",
- key: "ImageMapPolyOddNumberOfCoords",
- type: "double-quote"
- }, {
- file: "xbl.properties",
- key: "CommandNotInChrome",
- type: "double-quote"
- }, {
- file: "dom.properties",
- key: "PatternAttributeCompileFailure",
- type: "single-quote"
- }, {
- file: "pipnss.properties",
- key: "certErrorMismatchSingle2",
- type: "double-quote"
- }, {
- file: "pipnss.properties",
- key: "certErrorCodePrefix2",
- type: "double-quote"
- }, {
- file: "aboutSupport.dtd",
- key: "aboutSupport.pageSubtitle",
- type: "single-quote"
- }, {
- file: "aboutSupport.dtd",
- key: "aboutSupport.userJSDescription",
- type: "single-quote"
- }, {
- file: "netError.dtd",
- key: "inadequateSecurityError.longDesc",
- type: "single-quote"
- }, {
- file: "netErrorApp.dtd",
- key: "securityOverride.warningContent",
- type: "single-quote"
- }, {
- file: "pocket.properties",
- key: "tos",
- type: "double-quote"
- }, {
- file: "pocket.properties",
- key: "tos",
- type: "apostrophe"
- }, {
- file: "aboutNetworking.dtd",
- key: "aboutNetworking.logTutorial",
- type: "single-quote"
- }
-];
-
-var moduleLocation = gTestPath.replace(/\/[^\/]*$/i, "/parsingTestHelpers.jsm");
-var {generateURIsFromDirTree} = Cu.import(moduleLocation, {});
-
-/**
- * Check if an error should be ignored due to matching one of the whitelist
- * objects defined in gWhitelist.
- *
- * @param filepath The URI spec of the locale file
- * @param key The key of the entity that is being checked
- * @param type The type of error that has been found
- * @return true if the error should be ignored, false otherwise.
- */
-function ignoredError(filepath, key, type) {
- for (let index in gWhitelist) {
- let whitelistItem = gWhitelist[index];
- if (filepath.endsWith(whitelistItem.file) &&
- key == whitelistItem.key &&
- type == whitelistItem.type) {
- gWhitelist.splice(index, 1);
- return true;
- }
- }
- return false;
-}
-
-function fetchFile(uri) {
- return new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest();
- xhr.open("GET", uri, true);
- xhr.onreadystatechange = function() {
- if (this.readyState != this.DONE) {
- return;
- }
- try {
- resolve(this.responseText);
- } catch (ex) {
- ok(false, `Script error reading ${uri}: ${ex}`);
- resolve("");
- }
- };
- xhr.onerror = error => {
- ok(false, `XHR error reading ${uri}: ${error}`);
- resolve("");
- };
- xhr.send(null);
- });
-}
-
-function testForError(filepath, key, str, pattern, type, helpText) {
- if (str.match(pattern) &&
- !ignoredError(filepath, key, type)) {
- ok(false, `${filepath} with key=${key} has a misused ${type}. ${helpText}`);
- }
-}
-
-function testForErrors(filepath, key, str) {
- testForError(filepath, key, str, /\w'\w/, "apostrophe", "Strings with apostrophes should use foo\u2019s instead of foo's.");
- testForError(filepath, key, str, /\w\u2018\w/, "incorrect-apostrophe", "Strings with apostrophes should use foo\u2019s instead of foo\u2018s.");
- testForError(filepath, key, str, /'.+'/, "single-quote", "Single-quoted strings should use Unicode \u2018foo\u2019 instead of 'foo'.");
- testForError(filepath, key, str, /"/, "double-quote", "Double-quoted strings should use Unicode \u201cfoo\u201d instead of \"foo\".");
- testForError(filepath, key, str, /\.\.\./, "ellipsis", "Strings with an ellipsis should use the Unicode \u2026 character instead of three periods.");
-}
-
-function* getAllTheFiles(extension) {
- let appDirGreD = Services.dirsvc.get("GreD", Ci.nsIFile);
- let appDirXCurProcD = Services.dirsvc.get("XCurProcD", Ci.nsIFile);
- if (appDirGreD.contains(appDirXCurProcD)) {
- return yield generateURIsFromDirTree(appDirGreD, [extension]);
- }
- if (appDirXCurProcD.contains(appDirGreD)) {
- return yield generateURIsFromDirTree(appDirXCurProcD, [extension]);
- }
- let urisGreD = yield generateURIsFromDirTree(appDirGreD, [extension]);
- let urisXCurProcD = yield generateURIsFromDirTree(appDirXCurProcD, [extension]);
- return Array.from(new Set(urisGreD.concat(appDirXCurProcD)));
-}
-
-add_task(function* checkAllTheProperties() {
- // This asynchronously produces a list of URLs (sadly, mostly sync on our
- // test infrastructure because it runs against jarfiles there, and
- // our zipreader APIs are all sync)
- let uris = yield getAllTheFiles(".properties");
- ok(uris.length, `Found ${uris.length} .properties files to scan for misused characters`);
-
- for (let uri of uris) {
- let bundle = new StringBundle(uri.spec);
- let entities = bundle.getAll();
- for (let entity of entities) {
- testForErrors(uri.spec, entity.key, entity.value);
- }
- }
-});
-
-var checkDTD = Task.async(function* (aURISpec) {
- let rawContents = yield fetchFile(aURISpec);
- // The regular expression below is adapted from:
- // https://hg.mozilla.org/mozilla-central/file/68c0b7d6f16ce5bb023e08050102b5f2fe4aacd8/python/compare-locales/compare_locales/parser.py#l233
- let entities = rawContents.match(/<!ENTITY\s+([\w\.]*)\s+("[^"]*"|'[^']*')\s*>/g);
- if (!entities) {
- // Some files, such as requestAutocomplete.dtd, have no entities defined.
- return;
- }
- for (let entity of entities) {
- let [, key, str] = entity.match(/<!ENTITY\s+([\w\.]*)\s+("[^"]*"|'[^']*')\s*>/);
- // The matched string includes the enclosing quotation marks,
- // we need to slice them off.
- str = str.slice(1, -1);
- testForErrors(aURISpec, key, str);
- }
-});
-
-add_task(function* checkAllTheDTDs() {
- let uris = yield getAllTheFiles(".dtd");
- ok(uris.length, `Found ${uris.length} .dtd files to scan for misused characters`);
- for (let uri of uris) {
- yield checkDTD(uri.spec);
- }
-
- // This support DTD file supplies a string with a newline to make sure
- // the regex in checkDTD works correctly for that case.
- let dtdLocation = gTestPath.replace(/\/[^\/]*$/i, "/bug1262648_string_with_newlines.dtd");
- yield checkDTD(dtdLocation);
-});
-
-add_task(function* ensureWhiteListIsEmpty() {
- is(gWhitelist.length, 0, "No remaining whitelist entries exist");
-});
diff --git a/browser/base/content/test/general/browser_mixedContentFramesOnHttp.js b/browser/base/content/test/general/browser_mixedContentFramesOnHttp.js
deleted file mode 100644
index ac19efd05..000000000
--- a/browser/base/content/test/general/browser_mixedContentFramesOnHttp.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- *
- * Test for Bug 1182551 -
- *
- * This test has a top level HTTP page with an HTTPS iframe. The HTTPS iframe
- * includes an HTTP image. We check that the top level security state is
- * STATE_IS_INSECURE. The mixed content from the iframe shouldn't "upgrade"
- * the HTTP top level page to broken HTTPS.
- */
-
-const gHttpTestUrl = "http://example.com/browser/browser/base/content/test/general/file_mixedContentFramesOnHttp.html";
-
-var gTestBrowser = null;
-
-add_task(function *() {
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({
- "set": [
- ["security.mixed_content.block_active_content", true],
- ["security.mixed_content.block_display_content", false]
- ]
- }, resolve);
- });
- let url = gHttpTestUrl
- yield BrowserTestUtils.withNewTab({gBrowser, url}, function*() {
- gTestBrowser = gBrowser.selectedBrowser;
- // check security state is insecure
- isSecurityState("insecure");
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: true});
- });
-});
-
diff --git a/browser/base/content/test/general/browser_mixedContentFromOnunload.js b/browser/base/content/test/general/browser_mixedContentFromOnunload.js
deleted file mode 100644
index 9b39776f4..000000000
--- a/browser/base/content/test/general/browser_mixedContentFromOnunload.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- *
- * Tests for Bug 947079 - Fix bug in nsSecureBrowserUIImpl that sets the wrong
- * security state on a page because of a subresource load that is not on the
- * same page.
- */
-
-// We use different domains for each test and for navigation within each test
-const gHttpTestRoot1 = "http://example.com/browser/browser/base/content/test/general/";
-const gHttpsTestRoot1 = "https://test1.example.com/browser/browser/base/content/test/general/";
-const gHttpTestRoot2 = "http://example.net/browser/browser/base/content/test/general/";
-const gHttpsTestRoot2 = "https://test2.example.com/browser/browser/base/content/test/general/";
-
-var gTestBrowser = null;
-add_task(function *() {
- let url = gHttpTestRoot1 + "file_mixedContentFromOnunload.html";
- yield BrowserTestUtils.withNewTab({gBrowser, url}, function*() {
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({
- "set": [
- ["security.mixed_content.block_active_content", true],
- ["security.mixed_content.block_display_content", false]
- ]
- }, resolve);
- });
- gTestBrowser = gBrowser.selectedBrowser;
- // Navigation from an http page to a https page with no mixed content
- // The http page loads an http image on unload
- url = gHttpsTestRoot1 + "file_mixedContentFromOnunload_test1.html";
- yield BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
- // check security state. Since current url is https and doesn't have any
- // mixed content resources, we expect it to be secure.
- isSecurityState("secure");
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: false});
- // Navigation from an http page to a https page that has mixed display content
- // The https page loads an http image on unload
- url = gHttpTestRoot2 + "file_mixedContentFromOnunload.html";
- yield BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
- url = gHttpsTestRoot2 + "file_mixedContentFromOnunload_test2.html";
- yield BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
- isSecurityState("broken");
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: true});
- });
-});
diff --git a/browser/base/content/test/general/browser_mixed_content_cert_override.js b/browser/base/content/test/general/browser_mixed_content_cert_override.js
deleted file mode 100644
index 037fce5d2..000000000
--- a/browser/base/content/test/general/browser_mixed_content_cert_override.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Bug 1253771 - check mixed content blocking in combination with overriden certificates
- */
-
-"use strict";
-
-const MIXED_CONTENT_URL = "https://self-signed.example.com/browser/browser/base/content/test/general/test-mixedcontent-securityerrors.html";
-
-function getConnectionState() {
- return document.getElementById("identity-popup").getAttribute("connection");
-}
-
-function getPopupContentVerifier() {
- return document.getElementById("identity-popup-content-verifier");
-}
-
-function getConnectionIcon() {
- return window.getComputedStyle(document.getElementById("connection-icon")).listStyleImage;
-}
-
-function checkIdentityPopup(icon) {
- gIdentityHandler.refreshIdentityPopup();
- is(getConnectionIcon(), `url("chrome://browser/skin/${icon}")`);
- is(getConnectionState(), "secure-cert-user-overridden");
- isnot(getPopupContentVerifier().style.display, "none", "Overridden certificate warning is shown");
- ok(getPopupContentVerifier().textContent.includes("security exception"), "Text shows overridden certificate warning.");
-}
-
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- // check that a warning is shown when loading a page with mixed content and an overridden certificate
- yield loadBadCertPage(MIXED_CONTENT_URL);
- checkIdentityPopup("connection-mixed-passive-loaded.svg#icon");
-
- // check that the crossed out icon is shown when disabling mixed content protection
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
-
- checkIdentityPopup("connection-mixed-active-loaded.svg#icon");
-
- // check that a warning is shown even without mixed content
- yield BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://self-signed.example.com");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- checkIdentityPopup("connection-mixed-passive-loaded.svg#icon");
-
- // remove cert exception
- let certOverrideService = Cc["@mozilla.org/security/certoverride;1"]
- .getService(Ci.nsICertOverrideService);
- certOverrideService.clearValidityOverride("self-signed.example.com", -1);
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
diff --git a/browser/base/content/test/general/browser_mixedcontent_securityflags.js b/browser/base/content/test/general/browser_mixedcontent_securityflags.js
deleted file mode 100644
index 1c2614b86..000000000
--- a/browser/base/content/test/general/browser_mixedcontent_securityflags.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// The test loads a web page with mixed active and mixed display content and
-// makes sure that the mixed content flags on the docshell are set correctly.
-// * Using default about:config prefs (mixed active blocked, mixed display
-// loaded) we load the page and check the flags.
-// * We change the about:config prefs (mixed active blocked, mixed display
-// blocked), reload the page, and check the flags again.
-// * We override protection so all mixed content can load and check the
-// flags again.
-
-const TEST_URI = "https://example.com/browser/browser/base/content/test/general/test-mixedcontent-securityerrors.html";
-const PREF_DISPLAY = "security.mixed_content.block_display_content";
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-var gTestBrowser = null;
-
-registerCleanupFunction(function() {
- // Set preferences back to their original values
- Services.prefs.clearUserPref(PREF_DISPLAY);
- Services.prefs.clearUserPref(PREF_ACTIVE);
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* blockMixedActiveContentTest() {
- // Turn on mixed active blocking and mixed display loading and load the page.
- Services.prefs.setBoolPref(PREF_DISPLAY, false);
- Services.prefs.setBoolPref(PREF_ACTIVE, true);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URI);
- gTestBrowser = gBrowser.getBrowserForTab(tab);
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- is(docShell.hasMixedDisplayContentBlocked, false, "hasMixedDisplayContentBlocked flag has been set");
- is(docShell.hasMixedActiveContentBlocked, true, "hasMixedActiveContentBlocked flag has been set");
- is(docShell.hasMixedDisplayContentLoaded, true, "hasMixedDisplayContentLoaded flag has been set");
- is(docShell.hasMixedActiveContentLoaded, false, "hasMixedActiveContentLoaded flag has been set");
- });
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: true});
-
- // Turn on mixed active and mixed display blocking and reload the page.
- Services.prefs.setBoolPref(PREF_DISPLAY, true);
- Services.prefs.setBoolPref(PREF_ACTIVE, true);
-
- gBrowser.reload();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- is(docShell.hasMixedDisplayContentBlocked, true, "hasMixedDisplayContentBlocked flag has been set");
- is(docShell.hasMixedActiveContentBlocked, true, "hasMixedActiveContentBlocked flag has been set");
- is(docShell.hasMixedDisplayContentLoaded, false, "hasMixedDisplayContentLoaded flag has been set");
- is(docShell.hasMixedActiveContentLoaded, false, "hasMixedActiveContentLoaded flag has been set");
- });
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
-});
-
-add_task(function* overrideMCB() {
- // Disable mixed content blocking (reloads page) and retest
- let {gIdentityHandler} = gTestBrowser.ownerGlobal;
- gIdentityHandler.disableMixedContentProtection();
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- is(docShell.hasMixedDisplayContentLoaded, true, "hasMixedDisplayContentLoaded flag has not been set");
- is(docShell.hasMixedActiveContentLoaded, true, "hasMixedActiveContentLoaded flag has not been set");
- is(docShell.hasMixedDisplayContentBlocked, false, "second hasMixedDisplayContentBlocked flag has been set");
- is(docShell.hasMixedActiveContentBlocked, false, "second hasMixedActiveContentBlocked flag has been set");
- });
- assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: true});
-});
diff --git a/browser/base/content/test/general/browser_modifiedclick_inherit_principal.js b/browser/base/content/test/general/browser_modifiedclick_inherit_principal.js
deleted file mode 100644
index 3b5a5a149..000000000
--- a/browser/base/content/test/general/browser_modifiedclick_inherit_principal.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-
-const kURL =
- "http://example.com/browser/browser/base/content/test/general/dummy_page.html";
- "data:text/html,<a href=''>Middle-click me</a>";
-
-/*
- * Check that when manually opening content JS links in new tabs/windows,
- * we use the correct principal, and we don't clear the URL bar.
- */
-add_task(function* () {
- yield BrowserTestUtils.withNewTab(kURL, function* (browser) {
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
- yield ContentTask.spawn(browser, null, function* () {
- let a = content.document.createElement("a");
- a.href = "javascript:document.write('spoof'); void(0);";
- a.textContent = "Some link";
- content.document.body.appendChild(a);
- });
- info("Added element");
- yield BrowserTestUtils.synthesizeMouseAtCenter("a", {button: 1}, browser);
- let newTab = yield newTabPromise;
- is(newTab.linkedBrowser.contentPrincipal.origin, "http://example.com",
- "Principal should be for example.com");
- yield BrowserTestUtils.switchTab(gBrowser, newTab);
- info(gURLBar.value);
- isnot(gURLBar.value, "", "URL bar should not be empty.");
- yield BrowserTestUtils.removeTab(newTab);
- });
-});
diff --git a/browser/base/content/test/general/browser_newTabDrop.js b/browser/base/content/test/general/browser_newTabDrop.js
deleted file mode 100644
index 03c90df3f..000000000
--- a/browser/base/content/test/general/browser_newTabDrop.js
+++ /dev/null
@@ -1,99 +0,0 @@
-registerCleanupFunction(function* cleanup() {
- while (gBrowser.tabs.length > 1) {
- yield BrowserTestUtils.removeTab(gBrowser.tabs[gBrowser.tabs.length - 1]);
- }
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.removeEngine(engine);
-});
-
-let originalEngine;
-add_task(function* test_setup() {
- // Stop search-engine loads from hitting the network
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-});
-
-// New Tab Button opens any link.
-add_task(function*() { yield dropText("mochi.test/first", 1); });
-add_task(function*() { yield dropText("javascript:'bad'", 1); });
-add_task(function*() { yield dropText("jAvascript:'bad'", 1); });
-add_task(function*() { yield dropText("mochi.test/second", 1); });
-add_task(function*() { yield dropText("data:text/html,bad", 1); });
-add_task(function*() { yield dropText("mochi.test/third", 1); });
-
-// Single text/plain item, with multiple links.
-add_task(function*() { yield dropText("mochi.test/1\nmochi.test/2", 2); });
-add_task(function*() { yield dropText("javascript:'bad1'\nmochi.test/3", 2); });
-add_task(function*() { yield dropText("mochi.test/4\ndata:text/html,bad1", 2); });
-
-// Multiple text/plain items, with single and multiple links.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/5"}],
- [{type: "text/plain",
- data: "mochi.test/6\nmochi.test/7"}]], 3);
-});
-
-// Single text/x-moz-url item, with multiple links.
-// "text/x-moz-url" has titles in even-numbered lines.
-add_task(function*() {
- yield drop([[{type: "text/x-moz-url",
- data: "mochi.test/8\nTITLE8\nmochi.test/9\nTITLE9"}]], 2);
-});
-
-// Single item with multiple types.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/10"},
- {type: "text/x-moz-url",
- data: "mochi.test/11\nTITLE11"}]], 1);
-});
-
-function dropText(text, expectedTabOpenCount=0) {
- return drop([[{type: "text/plain", data: text}]], expectedTabOpenCount);
-}
-
-function* drop(dragData, expectedTabOpenCount=0) {
- let dragDataString = JSON.stringify(dragData);
- info(`Starting test for datagData:${dragDataString}; expectedTabOpenCount:${expectedTabOpenCount}`);
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- // Since synthesizeDrop triggers the srcElement, need to use another button.
- let dragSrcElement = document.getElementById("downloads-button");
- ok(dragSrcElement, "Downloads button exists");
- let newTabButton = document.getElementById("new-tab-button");
- ok(newTabButton, "New Tab button exists");
-
- let awaitDrop = BrowserTestUtils.waitForEvent(newTabButton, "drop");
- let actualTabOpenCount = 0;
- let openedTabs = [];
- let checkCount = function(event) {
- openedTabs.push(event.target);
- actualTabOpenCount++;
- return actualTabOpenCount == expectedTabOpenCount;
- };
- let awaitTabOpen = expectedTabOpenCount && BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen", false, checkCount);
-
- EventUtils.synthesizeDrop(dragSrcElement, newTabButton, dragData, "link", window);
-
- let tabsOpened = false;
- if (awaitTabOpen) {
- yield awaitTabOpen;
- info("Got TabOpen event");
- tabsOpened = true;
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- }
- is(tabsOpened, !!expectedTabOpenCount, `Tabs for ${dragDataString} should only open if any of dropped items are valid`);
-
- yield awaitDrop;
- ok(true, "Got drop event");
-}
diff --git a/browser/base/content/test/general/browser_newWindowDrop.js b/browser/base/content/test/general/browser_newWindowDrop.js
deleted file mode 100644
index f404d4eed..000000000
--- a/browser/base/content/test/general/browser_newWindowDrop.js
+++ /dev/null
@@ -1,120 +0,0 @@
-registerCleanupFunction(function* cleanup() {
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.removeEngine(engine);
-});
-
-let originalEngine;
-add_task(function* test_setup() {
- // Opening multiple windows on debug build takes too long time.
- requestLongerTimeout(10);
-
- // Stop search-engine loads from hitting the network
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- // Move New Window button to nav bar, to make it possible to drag and drop.
- let {CustomizableUI} = Cu.import("resource:///modules/CustomizableUI.jsm", {});
- let origPlacement = CustomizableUI.getPlacementOfWidget("new-window-button");
- if (!origPlacement || origPlacement.area != CustomizableUI.AREA_NAVBAR) {
- CustomizableUI.addWidgetToArea("new-window-button",
- CustomizableUI.AREA_NAVBAR,
- 0);
- CustomizableUI.ensureWidgetPlacedInWindow("new-window-button", window);
- registerCleanupFunction(function () {
- CustomizableUI.reset();
- });
- }
-});
-
-// New Window Button opens any link.
-add_task(function*() { yield dropText("mochi.test/first", 1); });
-add_task(function*() { yield dropText("javascript:'bad'", 1); });
-add_task(function*() { yield dropText("jAvascript:'bad'", 1); });
-add_task(function*() { yield dropText("mochi.test/second", 1); });
-add_task(function*() { yield dropText("data:text/html,bad", 1); });
-add_task(function*() { yield dropText("mochi.test/third", 1); });
-
-// Single text/plain item, with multiple links.
-add_task(function*() { yield dropText("mochi.test/1\nmochi.test/2", 2); });
-add_task(function*() { yield dropText("javascript:'bad1'\nmochi.test/3", 2); });
-add_task(function*() { yield dropText("mochi.test/4\ndata:text/html,bad1", 2); });
-
-// Multiple text/plain items, with single and multiple links.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/5"}],
- [{type: "text/plain",
- data: "mochi.test/6\nmochi.test/7"}]], 3);
-});
-
-// Single text/x-moz-url item, with multiple links.
-// "text/x-moz-url" has titles in even-numbered lines.
-add_task(function*() {
- yield drop([[{type: "text/x-moz-url",
- data: "mochi.test/8\nTITLE8\nmochi.test/9\nTITLE9"}]], 2);
-});
-
-// Single item with multiple types.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/10"},
- {type: "text/x-moz-url",
- data: "mochi.test/11\nTITLE11"}]], 1);
-});
-
-function dropText(text, expectedWindowOpenCount=0) {
- return drop([[{type: "text/plain", data: text}]], expectedWindowOpenCount);
-}
-
-function* drop(dragData, expectedWindowOpenCount=0) {
- let dragDataString = JSON.stringify(dragData);
- info(`Starting test for datagData:${dragDataString}; expectedWindowOpenCount:${expectedWindowOpenCount}`);
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- // Since synthesizeDrop triggers the srcElement, need to use another button.
- let dragSrcElement = document.getElementById("downloads-button");
- ok(dragSrcElement, "Downloads button exists");
- let newWindowButton = document.getElementById("new-window-button");
- ok(newWindowButton, "New Window button exists");
-
- let tmp = {};
- Cu.import("resource://testing-common/TestUtils.jsm", tmp);
-
- let awaitDrop = BrowserTestUtils.waitForEvent(newWindowButton, "drop");
- let actualWindowOpenCount = 0;
- let openedWindows = [];
- let checkCount = function(window) {
- // Add observer as soon as domWindow is opened to avoid missing the topic.
- let awaitStartup = tmp.TestUtils.topicObserved("browser-delayed-startup-finished",
- subject => subject == window);
- openedWindows.push([window, awaitStartup]);
- actualWindowOpenCount++;
- return actualWindowOpenCount == expectedWindowOpenCount;
- };
- let awaitWindowOpen = expectedWindowOpenCount && BrowserTestUtils.domWindowOpened(null, checkCount);
-
- EventUtils.synthesizeDrop(dragSrcElement, newWindowButton, dragData, "link", window);
-
- let windowsOpened = false;
- if (awaitWindowOpen) {
- yield awaitWindowOpen;
- info("Got Window opened");
- windowsOpened = true;
- for (let [window, awaitStartup] of openedWindows.reverse()) {
- // Wait for startup before closing, to properly close the browser window.
- yield awaitStartup;
- yield BrowserTestUtils.closeWindow(window);
- }
- }
- is(windowsOpened, !!expectedWindowOpenCount, `Windows for ${dragDataString} should only open if any of dropped items are valid`);
-
- yield awaitDrop;
- ok(true, "Got drop event");
-}
diff --git a/browser/base/content/test/general/browser_newwindow_focus.js b/browser/base/content/test/general/browser_newwindow_focus.js
deleted file mode 100644
index 7880db0bd..000000000
--- a/browser/base/content/test/general/browser_newwindow_focus.js
+++ /dev/null
@@ -1,96 +0,0 @@
-"use strict";
-
-/**
- * These tests are for the auto-focus behaviour on the initial browser
- * when a window is opened from content.
- */
-
-const PAGE = `data:text/html,<a id="target" href="%23" onclick="window.open('http://www.example.com', '_blank', 'width=100,height=100');">Click me</a>`;
-
-/**
- * Returns a Promise that resolves when a new window has
- * opened, and the "load" event has fired in that window.
- * We can't use BrowserTestUtils.domWindowOpened directly,
- * because by the time the "then" on the Promise runs,
- * DOMContentLoaded and load may have already run in the new
- * window. However, we want to be very explicit about what
- * events we're waiting for, and not rely on a quirk of our
- * Promises infrastructure.
- */
-function promiseNewWindow() {
- return new Promise((resolve) => {
- let observer = (subject, topic, data) => {
- if (topic == "domwindowopened") {
- Services.ww.unregisterNotification(observer);
- let win = subject.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- resolve(win);
- });
- }
- };
-
- Services.ww.registerNotification(observer);
- });
-}
-
-/**
- * Test that when a new window is opened from content, focus moves
- * to the initial browser in that window once the window has finished
- * painting.
- */
-add_task(function* test_focus_browser() {
- yield BrowserTestUtils.withNewTab({
- url: PAGE,
- gBrowser,
- }, function*(browser) {
- let newWinPromise = promiseNewWindow();
- let delayedStartupPromise = BrowserTestUtils.waitForNewWindow();
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#target", {}, browser);
- let newWin = yield newWinPromise;
- yield BrowserTestUtils.contentPainted(newWin.gBrowser.selectedBrowser);
- yield delayedStartupPromise;
-
- let focusedElement =
- Services.focus.getFocusedElementForWindow(newWin, false, {});
-
- Assert.equal(focusedElement, newWin.gBrowser.selectedBrowser,
- "Initial browser should be focused");
-
- yield BrowserTestUtils.closeWindow(newWin);
- });
-});
-
-/**
- * Test that when a new window is opened from content and focus
- * shifts in that window before the content has a chance to paint
- * that we _don't_ steal focus once content has painted.
- */
-add_task(function* test_no_steal_focus() {
- yield BrowserTestUtils.withNewTab({
- url: PAGE,
- gBrowser,
- }, function*(browser) {
- let newWinPromise = promiseNewWindow();
- let delayedStartupPromise = BrowserTestUtils.waitForNewWindow();
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#target", {}, browser);
- let newWin = yield newWinPromise;
-
- // Because we're switching focus, we shouldn't steal it once
- // content paints.
- newWin.gURLBar.focus();
-
- yield BrowserTestUtils.contentPainted(newWin.gBrowser.selectedBrowser);
- yield delayedStartupPromise;
-
- let focusedElement =
- Services.focus.getFocusedElementForWindow(newWin, false, {});
-
- Assert.equal(focusedElement, newWin.gURLBar.inputField,
- "URLBar should be focused");
-
- yield BrowserTestUtils.closeWindow(newWin);
- });
-});
diff --git a/browser/base/content/test/general/browser_no_mcb_on_http_site.js b/browser/base/content/test/general/browser_no_mcb_on_http_site.js
deleted file mode 100644
index 45fd67379..000000000
--- a/browser/base/content/test/general/browser_no_mcb_on_http_site.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Description of the Tests for
- * - Bug 909920 - Mixed content warning should not show on a HTTP site
- *
- * Description of the tests:
- * Test 1:
- * 1) Load an http page
- * 2) The page includes a css file using https
- * 3) The css file loads an |IMAGE| << over http
- *
- * Test 2:
- * 1) Load an http page
- * 2) The page includes a css file using https
- * 3) The css file loads a |FONT| over http
- *
- * Test 3:
- * 1) Load an http page
- * 2) The page includes a css file using https
- * 3) The css file imports (@import) another css file using http
- * 3) The imported css file loads a |FONT| over http
-*
- * Since the top-domain is >> NOT << served using https, the MCB
- * should >> NOT << trigger a warning.
- */
-
-const PREF_ACTIVE = "security.mixed_content.block_active_content";
-const PREF_DISPLAY = "security.mixed_content.block_display_content";
-
-const gHttpTestRoot = "http://example.com/browser/browser/base/content/test/general/";
-
-var gTestBrowser = null;
-
-function cleanUpAfterTests() {
- gBrowser.removeCurrentTab();
- window.focus();
-}
-
-add_task(function* init() {
- yield SpecialPowers.pushPrefEnv({ set: [[ PREF_ACTIVE, true ],
- [ PREF_DISPLAY, true ]] });
- let url = gHttpTestRoot + "test_no_mcb_on_http_site_img.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url)
- gTestBrowser = tab.linkedBrowser;
-});
-
-// ------------- TEST 1 -----------------------------------------
-
-add_task(function* test1() {
- let expected = "Verifying MCB does not trigger warning/error for an http page ";
- expected += "with https css that includes http image";
-
- yield ContentTask.spawn(gTestBrowser, expected, function* (condition) {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("testDiv").innerHTML == condition,
- "Waited too long for status in Test 1!");
- });
-
- // Explicit OKs needed because the harness requires at least one call to ok.
- ok(true, "test 1 passed");
-
- // set up test 2
- let url = gHttpTestRoot + "test_no_mcb_on_http_site_font.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-// ------------- TEST 2 -----------------------------------------
-
-add_task(function* test2() {
- let expected = "Verifying MCB does not trigger warning/error for an http page ";
- expected += "with https css that includes http font";
-
- yield ContentTask.spawn(gTestBrowser, expected, function* (condition) {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("testDiv").innerHTML == condition,
- "Waited too long for status in Test 2!");
- });
-
- ok(true, "test 2 passed");
-
- // set up test 3
- let url = gHttpTestRoot + "test_no_mcb_on_http_site_font2.html";
- BrowserTestUtils.loadURI(gTestBrowser, url);
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-// ------------- TEST 3 -----------------------------------------
-
-add_task(function* test3() {
- let expected = "Verifying MCB does not trigger warning/error for an http page "
- expected += "with https css that imports another http css which includes http font";
-
- yield ContentTask.spawn(gTestBrowser, expected, function* (condition) {
- yield ContentTaskUtils.waitForCondition(
- () => content.document.getElementById("testDiv").innerHTML == condition,
- "Waited too long for status in Test 3!");
- });
-
- ok(true, "test3 passed");
-});
-
-// ------------------------------------------------------
-
-add_task(function* cleanup() {
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/general/browser_offlineQuotaNotification.js b/browser/base/content/test/general/browser_offlineQuotaNotification.js
deleted file mode 100644
index e56bfe9a8..000000000
--- a/browser/base/content/test/general/browser_offlineQuotaNotification.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-// Test offline quota warnings - must be run as a mochitest-browser test or
-// else the test runner gets in the way of notifications due to bug 857897.
-
-const URL = "http://mochi.test:8888/browser/browser/base/content/test/general/offlineQuotaNotification.html";
-
-registerCleanupFunction(function() {
- // Clean up after ourself
- let uri = Services.io.newURI(URL, null, null);
- let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
- Services.perms.removeFromPrincipal(principal, "offline-app");
- Services.prefs.clearUserPref("offline-apps.quota.warn");
- Services.prefs.clearUserPref("offline-apps.allow_by_default");
- let {OfflineAppCacheHelper} = Components.utils.import("resource:///modules/offlineAppCache.jsm", {});
- OfflineAppCacheHelper.clear();
-});
-
-// Same as the other one, but for in-content preferences
-function checkInContentPreferences(win) {
- let doc = win.document;
- let sel = doc.getElementById("categories").selectedItems[0].id;
- let tab = doc.getElementById("advancedPrefs").selectedTab.id;
- is(gBrowser.currentURI.spec, "about:preferences#advanced", "about:preferences loaded");
- is(sel, "category-advanced", "Advanced pane was selected");
- is(tab, "networkTab", "Network tab is selected");
- // all good, we are done.
- win.close();
- finish();
-}
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref("offline-apps.allow_by_default", false);
-
- // Open a new tab.
- gBrowser.selectedTab = gBrowser.addTab(URL);
- registerCleanupFunction(() => gBrowser.removeCurrentTab());
-
-
- Promise.all([
- // Wait for a notification that asks whether to allow offline storage.
- promiseNotification(),
- // Wait for the tab to load.
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser),
- ]).then(() => {
- info("Loaded page, adding onCached handler");
- // Need a promise to keep track of when we've added our handler.
- let mm = gBrowser.selectedBrowser.messageManager;
- let onCachedAttached = BrowserTestUtils.waitForMessage(mm, "Test:OnCachedAttached");
- let gotCached = ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- return new Promise(resolve => {
- content.window.applicationCache.oncached = function() {
- setTimeout(resolve, 0);
- };
- sendAsyncMessage("Test:OnCachedAttached");
- });
- });
- gotCached.then(function() {
- // We got cached - now we should have provoked the quota warning.
- let notification = PopupNotifications.getNotification('offline-app-usage');
- ok(notification, "have offline-app-usage notification");
- // select the default action - this should cause the preferences
- // tab to open - which we track via an "Initialized" event.
- PopupNotifications.panel.firstElementChild.button.click();
- let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
- newTabBrowser.addEventListener("Initialized", function PrefInit() {
- newTabBrowser.removeEventListener("Initialized", PrefInit, true);
- executeSoon(function() {
- checkInContentPreferences(newTabBrowser.contentWindow);
- })
- }, true);
- });
- onCachedAttached.then(function() {
- Services.prefs.setIntPref("offline-apps.quota.warn", 1);
-
- // Click the notification panel's "Allow" button. This should kick
- // off updates which will call our oncached handler above.
- PopupNotifications.panel.firstElementChild.button.click();
- });
- });
-}
-
-function promiseNotification() {
- return new Promise(resolve => {
- PopupNotifications.panel.addEventListener("popupshown", function onShown() {
- PopupNotifications.panel.removeEventListener("popupshown", onShown);
- resolve();
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_overflowScroll.js b/browser/base/content/test/general/browser_overflowScroll.js
deleted file mode 100644
index 56932fae2..000000000
--- a/browser/base/content/test/general/browser_overflowScroll.js
+++ /dev/null
@@ -1,91 +0,0 @@
-var tabstrip = gBrowser.tabContainer.mTabstrip;
-var scrollbox = tabstrip._scrollbox;
-var originalSmoothScroll = tabstrip.smoothScroll;
-var tabs = gBrowser.tabs;
-
-var rect = ele => ele.getBoundingClientRect();
-var width = ele => rect(ele).width;
-var left = ele => rect(ele).left;
-var right = ele => rect(ele).right;
-var isLeft = (ele, msg) => is(left(ele) + tabstrip._tabMarginLeft, left(scrollbox), msg);
-var isRight = (ele, msg) => is(right(ele) - tabstrip._tabMarginRight, right(scrollbox), msg);
-var elementFromPoint = x => tabstrip._elementFromPoint(x);
-var nextLeftElement = () => elementFromPoint(left(scrollbox) - 1);
-var nextRightElement = () => elementFromPoint(right(scrollbox) + 1);
-var firstScrollable = () => tabs[gBrowser._numPinnedTabs];
-
-function test() {
- requestLongerTimeout(2);
- waitForExplicitFinish();
-
- // If the previous (or more) test finished with cleaning up the tabs,
- // there may be some pending animations. That can cause a failure of
- // this tests, so, we should test this in another stack.
- setTimeout(doTest, 0);
-}
-
-function doTest() {
- tabstrip.smoothScroll = false;
-
- var tabMinWidth = parseInt(getComputedStyle(gBrowser.selectedTab, null).minWidth);
- var tabCountForOverflow = Math.ceil(width(tabstrip) / tabMinWidth * 3);
- while (tabs.length < tabCountForOverflow)
- gBrowser.addTab("about:blank", {skipAnimation: true});
- gBrowser.pinTab(tabs[0]);
-
- tabstrip.addEventListener("overflow", runOverflowTests, false);
-}
-
-function runOverflowTests(aEvent) {
- if (aEvent.detail != 1)
- return;
-
- tabstrip.removeEventListener("overflow", runOverflowTests, false);
-
- var upButton = tabstrip._scrollButtonUp;
- var downButton = tabstrip._scrollButtonDown;
- var element;
-
- gBrowser.selectedTab = firstScrollable();
- ok(left(scrollbox) <= left(firstScrollable()), "Selecting the first tab scrolls it into view " +
- "(" + left(scrollbox) + " <= " + left(firstScrollable()) + ")");
-
- element = nextRightElement();
- EventUtils.synthesizeMouseAtCenter(downButton, {});
- isRight(element, "Scrolled one tab to the right with a single click");
-
- gBrowser.selectedTab = tabs[tabs.length - 1];
- ok(right(gBrowser.selectedTab) <= right(scrollbox), "Selecting the last tab scrolls it into view " +
- "(" + right(gBrowser.selectedTab) + " <= " + right(scrollbox) + ")");
-
- element = nextLeftElement();
- EventUtils.synthesizeMouse(upButton, 1, 1, {});
- isLeft(element, "Scrolled one tab to the left with a single click");
-
- let elementPoint = left(scrollbox) - width(scrollbox);
- element = elementFromPoint(elementPoint);
- if (elementPoint == right(element)) {
- element = element.nextSibling;
- }
- EventUtils.synthesizeMouse(upButton, 1, 1, {clickCount: 2});
- isLeft(element, "Scrolled one page of tabs with a double click");
-
- EventUtils.synthesizeMouse(upButton, 1, 1, {clickCount: 3});
- var firstScrollableLeft = left(firstScrollable());
- ok(left(scrollbox) <= firstScrollableLeft, "Scrolled to the start with a triple click " +
- "(" + left(scrollbox) + " <= " + firstScrollableLeft + ")");
-
- for (var i = 2; i; i--)
- EventUtils.synthesizeWheel(scrollbox, 1, 1, { deltaX: -1.0, deltaMode: WheelEvent.DOM_DELTA_LINE });
- is(left(firstScrollable()), firstScrollableLeft, "Remained at the start with the mouse wheel");
-
- element = nextRightElement();
- EventUtils.synthesizeWheel(scrollbox, 1, 1, { deltaX: 1.0, deltaMode: WheelEvent.DOM_DELTA_LINE});
- isRight(element, "Scrolled one tab to the right with the mouse wheel");
-
- while (tabs.length > 1)
- gBrowser.removeTab(tabs[0]);
-
- tabstrip.smoothScroll = originalSmoothScroll;
- finish();
-}
diff --git a/browser/base/content/test/general/browser_pageInfo.js b/browser/base/content/test/general/browser_pageInfo.js
deleted file mode 100644
index 90fe2e17f..000000000
--- a/browser/base/content/test/general/browser_pageInfo.js
+++ /dev/null
@@ -1,38 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- var pageInfo;
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.selectedBrowser.addEventListener("load", function loadListener() {
- gBrowser.selectedBrowser.removeEventListener("load", loadListener, true);
-
- Services.obs.addObserver(observer, "page-info-dialog-loaded", false);
- pageInfo = BrowserPageInfo();
- }, true);
- content.location =
- "https://example.com/browser/browser/base/content/test/general/feed_tab.html";
-
- function observer(win, topic, data) {
- Services.obs.removeObserver(observer, "page-info-dialog-loaded");
- pageInfo.onFinished.push(handlePageInfo);
- }
-
- function handlePageInfo() {
- ok(pageInfo.document.getElementById("feedTab"), "Feed tab");
- let feedListbox = pageInfo.document.getElementById("feedListbox");
- ok(feedListbox, "Feed list");
-
- var feedRowsNum = feedListbox.getRowCount();
- is(feedRowsNum, 3, "Number of feeds listed");
-
- for (var i = 0; i < feedRowsNum; i++) {
- let feedItem = feedListbox.getItemAtIndex(i);
- is(feedItem.getAttribute("name"), i + 1, "Feed name");
- }
-
- pageInfo.close();
- gBrowser.removeCurrentTab();
- finish();
- }
-}
diff --git a/browser/base/content/test/general/browser_page_style_menu.js b/browser/base/content/test/general/browser_page_style_menu.js
deleted file mode 100644
index cb080d52a..000000000
--- a/browser/base/content/test/general/browser_page_style_menu.js
+++ /dev/null
@@ -1,97 +0,0 @@
-"use strict";
-
-/**
- * Stylesheets are updated for a browser after the pageshow event.
- * This helper function returns a Promise that waits for that pageshow
- * event, and then resolves on the next tick to ensure that gPageStyleMenu
- * has had a chance to update the stylesheets.
- *
- * @param browser
- * The <xul:browser> to wait for.
- * @return Promise
- */
-function promiseStylesheetsUpdated(browser) {
- return ContentTask.spawn(browser, { PAGE }, function*(args) {
- return new Promise((resolve) => {
- addEventListener("pageshow", function onPageShow(e) {
- if (e.target.location == args.PAGE) {
- removeEventListener("pageshow", onPageShow);
- content.setTimeout(resolve, 0);
- }
- });
- })
- });
-}
-
-const PAGE = "http://example.com/browser/browser/base/content/test/general/page_style_sample.html";
-
-/*
- * Test that the right stylesheets do (and others don't) show up
- * in the page style menu.
- */
-add_task(function*() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", false);
- let browser = tab.linkedBrowser;
- yield BrowserTestUtils.loadURI(browser, PAGE);
- yield promiseStylesheetsUpdated(browser);
-
- let menupopup = document.getElementById("pageStyleMenu").menupopup;
- gPageStyleMenu.fillPopup(menupopup);
-
- var items = [];
- var current = menupopup.getElementsByTagName("menuseparator")[0];
- while (current.nextSibling) {
- current = current.nextSibling;
- items.push(current);
- }
-
- items = items.map(el => ({
- label: el.getAttribute("label"),
- checked: el.getAttribute("checked") == "true",
- }));
-
- let validLinks = yield ContentTask.spawn(gBrowser.selectedBrowser, items, function(contentItems) {
- let contentValidLinks = 0;
- Array.forEach(content.document.querySelectorAll("link, style"), function (el) {
- var title = el.getAttribute("title");
- var rel = el.getAttribute("rel");
- var media = el.getAttribute("media");
- var idstring = el.nodeName + " " + (title ? title : "without title and") +
- " with rel=\"" + rel + "\"" +
- (media ? " and media=\"" + media + "\"" : "");
-
- var item = contentItems.filter(aItem => aItem.label == title);
- var found = item.length == 1;
- var checked = found && item[0].checked;
-
- switch (el.getAttribute("data-state")) {
- case "0":
- ok(!found, idstring + " should not show up in page style menu");
- break;
- case "0-todo":
- contentValidLinks++;
- todo(!found, idstring + " should not show up in page style menu");
- ok(!checked, idstring + " should not be selected");
- break;
- case "1":
- contentValidLinks++;
- ok(found, idstring + " should show up in page style menu");
- ok(!checked, idstring + " should not be selected");
- break;
- case "2":
- contentValidLinks++;
- ok(found, idstring + " should show up in page style menu");
- ok(checked, idstring + " should be selected");
- break;
- default:
- throw "data-state attribute is missing or has invalid value";
- }
- });
- return contentValidLinks;
- });
-
- ok(items.length, "At least one item in the menu");
- is(items.length, validLinks, "all valid links found");
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_page_style_menu_update.js b/browser/base/content/test/general/browser_page_style_menu_update.js
deleted file mode 100644
index a0c741e48..000000000
--- a/browser/base/content/test/general/browser_page_style_menu_update.js
+++ /dev/null
@@ -1,67 +0,0 @@
-"use strict";
-
-const PAGE = "http://example.com/browser/browser/base/content/test/general/page_style_sample.html";
-
-/**
- * Stylesheets are updated for a browser after the pageshow event.
- * This helper function returns a Promise that waits for that pageshow
- * event, and then resolves on the next tick to ensure that gPageStyleMenu
- * has had a chance to update the stylesheets.
- *
- * @param browser
- * The <xul:browser> to wait for.
- * @return Promise
- */
-function promiseStylesheetsUpdated(browser) {
- return ContentTask.spawn(browser, { PAGE }, function*(args) {
- return new Promise((resolve) => {
- addEventListener("pageshow", function onPageShow(e) {
- if (e.target.location == args.PAGE) {
- removeEventListener("pageshow", onPageShow);
- content.setTimeout(resolve, 0);
- }
- });
- })
- });
-}
-
-/**
- * Tests that the Page Style menu shows the currently
- * selected Page Style after a new one has been selected.
- */
-add_task(function*() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", false);
- let browser = tab.linkedBrowser;
-
- yield BrowserTestUtils.loadURI(browser, PAGE);
- yield promiseStylesheetsUpdated(browser);
-
- let menupopup = document.getElementById("pageStyleMenu").menupopup;
- gPageStyleMenu.fillPopup(menupopup);
-
- // page_style_sample.html should default us to selecting the stylesheet
- // with the title "6" first.
- let selected = menupopup.querySelector("menuitem[checked='true']");
- is(selected.getAttribute("label"), "6", "Should have '6' stylesheet selected by default");
-
- // Now select stylesheet "1"
- let target = menupopup.querySelector("menuitem[label='1']");
- target.click();
-
- // Now we need to wait for the content process to send its stylesheet
- // update for the selected tab to the parent. Because messages are
- // guaranteed to be sent in order, we'll make sure we do the check
- // after the parent has been updated by yielding until the child
- // has finished running a ContentTask for us.
- yield ContentTask.spawn(browser, {}, function*() {
- dump('\nJust wasting some time.\n');
- });
-
- gPageStyleMenu.fillPopup(menupopup);
- // gPageStyleMenu empties out the menu between opens, so we need
- // to get a new reference to the selected menuitem
- selected = menupopup.querySelector("menuitem[checked='true']");
- is(selected.getAttribute("label"), "1", "Should now have stylesheet 1 selected");
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_pageinfo_svg_image.js b/browser/base/content/test/general/browser_pageinfo_svg_image.js
deleted file mode 100644
index 02514d79f..000000000
--- a/browser/base/content/test/general/browser_pageinfo_svg_image.js
+++ /dev/null
@@ -1,38 +0,0 @@
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.selectedBrowser.addEventListener("load", function loadListener() {
- gBrowser.selectedBrowser.removeEventListener("load", loadListener, true);
- var pageInfo = BrowserPageInfo(gBrowser.selectedBrowser.currentURI.spec,
- "mediaTab");
-
- pageInfo.addEventListener("load", function loadListener2() {
- pageInfo.removeEventListener("load", loadListener2, true);
- pageInfo.onFinished.push(function() {
- executeSoon(function() {
- var imageTree = pageInfo.document.getElementById("imagetree");
- var imageRowsNum = imageTree.view.rowCount;
-
- ok(imageTree, "Image tree is null (media tab is broken)");
-
- is(imageRowsNum, 1, "should have one image");
-
- // Only bother running this if we've got the right number of rows.
- if (imageRowsNum == 1) {
- is(imageTree.view.getCellText(0, imageTree.columns[0]),
- "https://example.com/browser/browser/base/content/test/general/title_test.svg",
- "The URL should be the svg image.");
- }
-
- pageInfo.close();
- gBrowser.removeCurrentTab();
- finish();
- });
- });
- }, true);
- }, true);
-
- content.location =
- "https://example.com/browser/browser/base/content/test/general/svg_image.html";
-}
diff --git a/browser/base/content/test/general/browser_parsable_css.js b/browser/base/content/test/general/browser_parsable_css.js
deleted file mode 100644
index 72954d2e5..000000000
--- a/browser/base/content/test/general/browser_parsable_css.js
+++ /dev/null
@@ -1,376 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* This list allows pre-existing or 'unfixable' CSS issues to remain, while we
- * detect newly occurring issues in shipping CSS. It is a list of objects
- * specifying conditions under which an error should be ignored.
- *
- * Every property of the objects in it needs to consist of a regular expression
- * matching the offending error. If an object has multiple regex criteria, they
- * ALL need to match an error in order for that error not to cause a test
- * failure. */
-let whitelist = [
- // CodeMirror is imported as-is, see bug 1004423.
- {sourceName: /codemirror\.css$/i,
- isFromDevTools: true},
- // The debugger uses cross-browser CSS.
- {sourceName: /devtools\/client\/debugger\/new\/styles.css/i,
- isFromDevTools: true},
- // PDFjs is futureproofing its pseudoselectors, and those rules are dropped.
- {sourceName: /web\/viewer\.css$/i,
- errorMessage: /Unknown pseudo-class.*(fullscreen|selection)/i,
- isFromDevTools: false},
- // Tracked in bug 1004428.
- {sourceName: /aboutaccounts\/(main|normalize)\.css$/i,
- isFromDevTools: false},
- // Highlighter CSS uses a UA-only pseudo-class, see bug 985597.
- {sourceName: /highlighters\.css$/i,
- errorMessage: /Unknown pseudo-class.*moz-native-anonymous/i,
- isFromDevTools: true},
- // Responsive Design Mode CSS uses a UA-only pseudo-class, see Bug 1241714.
- {sourceName: /responsive-ua\.css$/i,
- errorMessage: /Unknown pseudo-class.*moz-dropdown-list/i,
- isFromDevTools: true},
-
- {sourceName: /\b(contenteditable|EditorOverride|svg|forms|html|mathml|ua)\.css$/i,
- errorMessage: /Unknown pseudo-class.*-moz-/i,
- isFromDevTools: false},
- {sourceName: /\b(html|mathml|ua)\.css$/i,
- errorMessage: /Unknown property.*-moz-/i,
- isFromDevTools: false},
- // Reserved to UA sheets unless layout.css.overflow-clip-box.enabled flipped to true.
- {sourceName: /res\/forms\.css$/i,
- errorMessage: /Unknown property.*overflow-clip-box/i,
- isFromDevTools: false},
- {sourceName: /res\/(ua|html)\.css$/i,
- errorMessage: /Unknown pseudo-class .*\bfullscreen\b/i,
- isFromDevTools: false},
- {sourceName: /skin\/timepicker\.css$/i,
- errorMessage: /Error in parsing.*mask/i,
- isFromDevTools: false},
-];
-
-// Platform can be "linux", "macosx" or "win". If omitted, the exception applies to all platforms.
-let allowedImageReferences = [
- // Bug 1302691
- {file: "chrome://devtools/skin/images/dock-bottom-minimize@2x.png",
- from: "chrome://devtools/skin/toolbox.css",
- isFromDevTools: true},
- {file: "chrome://devtools/skin/images/dock-bottom-maximize@2x.png",
- from: "chrome://devtools/skin/toolbox.css",
- isFromDevTools: true},
-];
-
-var moduleLocation = gTestPath.replace(/\/[^\/]*$/i, "/parsingTestHelpers.jsm");
-var {generateURIsFromDirTree} = Cu.import(moduleLocation, {});
-
-// Add suffix to stylesheets' URI so that we always load them here and
-// have them parsed. Add a random number so that even if we run this
-// test multiple times, it would be unlikely to affect each other.
-const kPathSuffix = "?always-parse-css-" + Math.random();
-
-/**
- * Check if an error should be ignored due to matching one of the whitelist
- * objects defined in whitelist
- *
- * @param aErrorObject the error to check
- * @return true if the error should be ignored, false otherwise.
- */
-function ignoredError(aErrorObject) {
- for (let whitelistItem of whitelist) {
- let matches = true;
- for (let prop of ["sourceName", "errorMessage"]) {
- if (whitelistItem.hasOwnProperty(prop) &&
- !whitelistItem[prop].test(aErrorObject[prop] || "")) {
- matches = false;
- break;
- }
- }
- if (matches) {
- whitelistItem.used = true;
- return true;
- }
- }
- return false;
-}
-
-function once(target, name) {
- return new Promise((resolve, reject) => {
- let cb = () => {
- target.removeEventListener(name, cb);
- resolve();
- };
- target.addEventListener(name, cb);
- });
-}
-
-function fetchFile(uri) {
- return new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest();
- xhr.responseType = "text";
- xhr.open("GET", uri, true);
- xhr.onreadystatechange = function() {
- if (this.readyState != this.DONE) {
- return;
- }
- try {
- resolve(this.responseText);
- } catch (ex) {
- ok(false, `Script error reading ${uri}: ${ex}`);
- resolve("");
- }
- };
- xhr.onerror = error => {
- ok(false, `XHR error reading ${uri}: ${error}`);
- resolve("");
- };
- xhr.send(null);
- });
-}
-
-var gChromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Ci.nsIChromeRegistry);
-var gChromeMap = new Map();
-
-function getBaseUriForChromeUri(chromeUri) {
- let chromeFile = chromeUri + "gobbledygooknonexistentfile.reallynothere";
- let uri = Services.io.newURI(chromeFile, null, null);
- let fileUri = gChromeReg.convertChromeURL(uri);
- return fileUri.resolve(".");
-}
-
-function parseManifest(manifestUri) {
- return fetchFile(manifestUri.spec).then(data => {
- for (let line of data.split('\n')) {
- let [type, ...argv] = line.split(/\s+/);
- let component;
- if (type == "content" || type == "skin") {
- [component] = argv;
- } else {
- // skip unrelated lines
- continue;
- }
- let chromeUri = `chrome://${component}/${type}/`;
- gChromeMap.set(getBaseUriForChromeUri(chromeUri), chromeUri);
- }
- });
-}
-
-function convertToChromeUri(fileUri) {
- let baseUri = fileUri.spec;
- let path = "";
- while (true) {
- let slashPos = baseUri.lastIndexOf("/", baseUri.length - 2);
- if (slashPos < 0) {
- info(`File not accessible from chrome protocol: ${fileUri.path}`);
- return fileUri;
- }
- path = baseUri.slice(slashPos + 1) + path;
- baseUri = baseUri.slice(0, slashPos + 1);
- if (gChromeMap.has(baseUri)) {
- let chromeBaseUri = gChromeMap.get(baseUri);
- let chromeUri = `${chromeBaseUri}${path}`;
- return Services.io.newURI(chromeUri, null, null);
- }
- }
-}
-
-function messageIsCSSError(msg) {
- // Only care about CSS errors generated by our iframe:
- if ((msg instanceof Ci.nsIScriptError) &&
- msg.category.includes("CSS") &&
- msg.sourceName.endsWith(kPathSuffix)) {
- let sourceName = msg.sourceName.slice(0, -kPathSuffix.length);
- let msgInfo = { sourceName, errorMessage: msg.errorMessage };
- // Check if this error is whitelisted in whitelist
- if (!ignoredError(msgInfo)) {
- ok(false, `Got error message for ${sourceName}: ${msg.errorMessage}`);
- return true;
- }
- info(`Ignored error for ${sourceName} because of filter.`);
- }
- return false;
-}
-
-let imageURIsToReferencesMap = new Map();
-
-function processCSSRules(sheet) {
- for (let rule of sheet.cssRules) {
- if (rule instanceof CSSMediaRule) {
- processCSSRules(rule);
- continue;
- }
- if (!(rule instanceof CSSStyleRule))
- continue;
-
- // Extract urls from the css text.
- // Note: CSSStyleRule.cssText always has double quotes around URLs even
- // when the original CSS file didn't.
- let urls = rule.cssText.match(/url\("[^"]*"\)/g);
- if (!urls)
- continue;
-
- for (let url of urls) {
- // Remove the url(" prefix and the ") suffix.
- url = url.replace(/url\("(.*)"\)/, "$1");
- if (url.startsWith("data:"))
- continue;
-
- // Make the url absolute and remove the ref.
- let baseURI = Services.io.newURI(rule.parentStyleSheet.href, null, null);
- url = Services.io.newURI(url, null, baseURI).specIgnoringRef;
-
- // Store the image url along with the css file referencing it.
- let baseUrl = baseURI.spec.split("?always-parse-css")[0];
- if (!imageURIsToReferencesMap.has(url)) {
- imageURIsToReferencesMap.set(url, new Set([baseUrl]));
- } else {
- imageURIsToReferencesMap.get(url).add(baseUrl);
- }
- }
- }
-}
-
-function chromeFileExists(aURI)
-{
- let available = 0;
- try {
- let channel = NetUtil.newChannel({uri: aURI, loadUsingSystemPrincipal: true});
- let stream = channel.open();
- let sstream = Cc["@mozilla.org/scriptableinputstream;1"]
- .createInstance(Ci.nsIScriptableInputStream);
- sstream.init(stream);
- available = sstream.available();
- sstream.close();
- } catch (e) {
- if (e.result != Components.results.NS_ERROR_FILE_NOT_FOUND) {
- dump("Checking " + aURI + ": " + e + "\n");
- Cu.reportError(e);
- }
- }
- return available > 0;
-}
-
-add_task(function* checkAllTheCSS() {
- let appDir = Services.dirsvc.get("GreD", Ci.nsIFile);
- // This asynchronously produces a list of URLs (sadly, mostly sync on our
- // test infrastructure because it runs against jarfiles there, and
- // our zipreader APIs are all sync)
- let uris = yield generateURIsFromDirTree(appDir, [".css", ".manifest"]);
-
- // Create a clean iframe to load all the files into. This needs to live at a
- // chrome URI so that it's allowed to load and parse any styles.
- let testFile = getRootDirectory(gTestPath) + "dummy_page.html";
- let windowless = Services.appShell.createWindowlessBrowser();
- let iframe = windowless.document.createElementNS("http://www.w3.org/1999/xhtml", "html:iframe");
- windowless.document.documentElement.appendChild(iframe);
- let iframeLoaded = once(iframe, 'load');
- iframe.contentWindow.location = testFile;
- yield iframeLoaded;
- let doc = iframe.contentWindow.document;
-
- // Parse and remove all manifests from the list.
- // NOTE that this must be done before filtering out devtools paths
- // so that all chrome paths can be recorded.
- let manifestPromises = [];
- uris = uris.filter(uri => {
- if (uri.path.endsWith(".manifest")) {
- manifestPromises.push(parseManifest(uri));
- return false;
- }
- return true;
- });
- // Wait for all manifest to be parsed
- yield Promise.all(manifestPromises);
-
- // We build a list of promises that get resolved when their respective
- // files have loaded and produced no errors.
- let allPromises = [];
-
- // filter out either the devtools paths or the non-devtools paths:
- let isDevtools = SimpleTest.harnessParameters.subsuite == "devtools";
- let devtoolsPathBits = ["webide", "devtools"];
- uris = uris.filter(uri => isDevtools == devtoolsPathBits.some(path => uri.spec.includes(path)));
-
- for (let uri of uris) {
- let linkEl = doc.createElement("link");
- linkEl.setAttribute("rel", "stylesheet");
- let promiseForThisSpec = Promise.defer();
- let onLoad = (e) => {
- processCSSRules(linkEl.sheet);
- promiseForThisSpec.resolve();
- linkEl.removeEventListener("load", onLoad);
- linkEl.removeEventListener("error", onError);
- };
- let onError = (e) => {
- ok(false, "Loading " + linkEl.getAttribute("href") + " threw an error!");
- promiseForThisSpec.resolve();
- linkEl.removeEventListener("load", onLoad);
- linkEl.removeEventListener("error", onError);
- };
- linkEl.addEventListener("load", onLoad);
- linkEl.addEventListener("error", onError);
- linkEl.setAttribute("type", "text/css");
- let chromeUri = convertToChromeUri(uri);
- linkEl.setAttribute("href", chromeUri.spec + kPathSuffix);
- allPromises.push(promiseForThisSpec.promise);
- doc.head.appendChild(linkEl);
- }
-
- // Wait for all the files to have actually loaded:
- yield Promise.all(allPromises);
-
- // Check if all the files referenced from CSS actually exist.
- for (let [image, references] of imageURIsToReferencesMap) {
- if (!chromeFileExists(image)) {
- for (let ref of references) {
- let ignored = false;
- for (let item of allowedImageReferences) {
- if (image.endsWith(item.file) && ref.endsWith(item.from) &&
- isDevtools == item.isFromDevTools &&
- (!item.platforms || item.platforms.includes(AppConstants.platform))) {
- item.used = true;
- ignored = true;
- break;
- }
- }
- if (!ignored)
- ok(false, "missing " + image + " referenced from " + ref);
- }
- }
- }
-
- let messages = Services.console.getMessageArray();
- // Count errors (the test output will list actual issues for us, as well
- // as the ok(false) in messageIsCSSError.
- let errors = messages.filter(messageIsCSSError);
- is(errors.length, 0, "All the styles (" + allPromises.length + ") loaded without errors.");
-
- // Confirm that all whitelist rules have been used.
- for (let item of whitelist) {
- if (!item.used && isDevtools == item.isFromDevTools) {
- ok(false, "Unused whitelist item. " +
- (item.sourceName ? " sourceName: " + item.sourceName : "") +
- (item.errorMessage ? " errorMessage: " + item.errorMessage : ""));
- }
- }
-
- // Confirm that all file whitelist rules have been used.
- for (let item of allowedImageReferences) {
- if (!item.used && isDevtools == item.isFromDevTools &&
- (!item.platforms || item.platforms.includes(AppConstants.platform))) {
- ok(false, "Unused file whitelist item. " +
- " file: " + item.file +
- " from: " + item.from);
- }
- }
-
- // Clean up to avoid leaks:
- iframe.remove();
- doc.head.innerHTML = '';
- doc = null;
- iframe = null;
- windowless.close();
- windowless = null;
- imageURIsToReferencesMap = null;
-});
diff --git a/browser/base/content/test/general/browser_parsable_script.js b/browser/base/content/test/general/browser_parsable_script.js
deleted file mode 100644
index 50333dd65..000000000
--- a/browser/base/content/test/general/browser_parsable_script.js
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* This list allows pre-existing or 'unfixable' JS issues to remain, while we
- * detect newly occurring issues in shipping JS. It is a list of regexes
- * matching files which have errors:
- */
-const kWhitelist = new Set([
- /defaults\/profile\/prefs.js$/,
- /browser\/content\/browser\/places\/controller.js$/,
-]);
-
-
-var moduleLocation = gTestPath.replace(/\/[^\/]*$/i, "/parsingTestHelpers.jsm");
-var {generateURIsFromDirTree} = Cu.import(moduleLocation, {});
-
-// Normally we would use reflect.jsm to get Reflect.parse. However, if
-// we do that, then all the AST data is allocated in reflect.jsm's
-// zone. That exposes a bug in our GC. The GC collects reflect.jsm's
-// zone but not the zone in which our test code lives (since no new
-// data is being allocated in it). The cross-compartment wrappers in
-// our zone that point to the AST data never get collected, and so the
-// AST data itself is never collected. We need to GC both zones at
-// once to fix the problem.
-const init = Components.classes["@mozilla.org/jsreflect;1"].createInstance();
-init();
-
-/**
- * Check if an error should be ignored due to matching one of the whitelist
- * objects defined in kWhitelist
- *
- * @param uri the uri to check against the whitelist
- * @return true if the uri should be skipped, false otherwise.
- */
-function uriIsWhiteListed(uri) {
- for (let whitelistItem of kWhitelist) {
- if (whitelistItem.test(uri.spec)) {
- return true;
- }
- }
- return false;
-}
-
-function parsePromise(uri) {
- let promise = new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest();
- xhr.open("GET", uri, true);
- xhr.onreadystatechange = function() {
- if (this.readyState == this.DONE) {
- let scriptText = this.responseText;
- try {
- info("Checking " + uri);
- Reflect.parse(scriptText);
- resolve(true);
- } catch (ex) {
- let errorMsg = "Script error reading " + uri + ": " + ex;
- ok(false, errorMsg);
- resolve(false);
- }
- }
- };
- xhr.onerror = (error) => {
- ok(false, "XHR error reading " + uri + ": " + error);
- resolve(false);
- };
- xhr.overrideMimeType("application/javascript");
- xhr.send(null);
- });
- return promise;
-}
-
-add_task(function* checkAllTheJS() {
- // In debug builds, even on a fast machine, collecting the file list may take
- // more than 30 seconds, and parsing all files may take four more minutes.
- // For this reason, this test must be explictly requested in debug builds by
- // using the "--setpref parse=<filter>" argument to mach. You can specify:
- // - A case-sensitive substring of the file name to test (slow).
- // - A single absolute URI printed out by a previous run (fast).
- // - An empty string to run the test on all files (slowest).
- let parseRequested = Services.prefs.prefHasUserValue("parse");
- let parseValue = parseRequested && Services.prefs.getCharPref("parse");
- if (SpecialPowers.isDebugBuild) {
- if (!parseRequested) {
- ok(true, "Test disabled on debug build. To run, execute: ./mach" +
- " mochitest-browser --setpref parse=<case_sensitive_filter>" +
- " browser/base/content/test/general/browser_parsable_script.js");
- return;
- }
- // Request a 15 minutes timeout (30 seconds * 30) for debug builds.
- requestLongerTimeout(30);
- }
-
- let uris;
- // If an absolute URI is specified on the command line, use it immediately.
- if (parseValue && parseValue.includes(":")) {
- uris = [NetUtil.newURI(parseValue)];
- } else {
- let appDir = Services.dirsvc.get("XCurProcD", Ci.nsIFile);
- // This asynchronously produces a list of URLs (sadly, mostly sync on our
- // test infrastructure because it runs against jarfiles there, and
- // our zipreader APIs are all sync)
- let startTimeMs = Date.now();
- info("Collecting URIs");
- uris = yield generateURIsFromDirTree(appDir, [".js", ".jsm"]);
- info("Collected URIs in " + (Date.now() - startTimeMs) + "ms");
-
- // Apply the filter specified on the command line, if any.
- if (parseValue) {
- uris = uris.filter(uri => {
- if (uri.spec.includes(parseValue)) {
- return true;
- }
- info("Not checking filtered out " + uri.spec);
- return false;
- });
- }
- }
-
- // We create an array of promises so we can parallelize all our parsing
- // and file loading activity:
- let allPromises = [];
- for (let uri of uris) {
- if (uriIsWhiteListed(uri)) {
- info("Not checking whitelisted " + uri.spec);
- continue;
- }
- allPromises.push(parsePromise(uri.spec));
- }
-
- let promiseResults = yield Promise.all(allPromises);
- is(promiseResults.filter((x) => !x).length, 0, "There should be 0 parsing errors");
-});
diff --git a/browser/base/content/test/general/browser_permissions.js b/browser/base/content/test/general/browser_permissions.js
deleted file mode 100644
index 721a669d2..000000000
--- a/browser/base/content/test/general/browser_permissions.js
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Test the Permissions section in the Control Center.
- */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PERMISSIONS_PAGE = "http://example.com/browser/browser/base/content/test/general/permissions.html";
-var {SitePermissions} = Cu.import("resource:///modules/SitePermissions.jsm", {});
-
-registerCleanupFunction(function() {
- SitePermissions.remove(gBrowser.currentURI, "cookie");
- SitePermissions.remove(gBrowser.currentURI, "geo");
- SitePermissions.remove(gBrowser.currentURI, "camera");
- SitePermissions.remove(gBrowser.currentURI, "microphone");
-
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-});
-
-function* openIdentityPopup() {
- let {gIdentityHandler} = gBrowser.ownerGlobal;
- let promise = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
- gIdentityHandler._identityBox.click();
- return promise;
-}
-
-function* closeIdentityPopup() {
- let {gIdentityHandler} = gBrowser.ownerGlobal;
- let promise = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popuphidden");
- gIdentityHandler._identityPopup.hidePopup();
- return promise;
-}
-
-add_task(function* testMainViewVisible() {
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
-
- let permissionsList = document.getElementById("identity-popup-permission-list");
- let emptyLabel = permissionsList.nextSibling.nextSibling;
-
- yield openIdentityPopup();
-
- ok(!is_hidden(emptyLabel), "List of permissions is empty");
-
- yield closeIdentityPopup();
-
- SitePermissions.set(gBrowser.currentURI, "camera", SitePermissions.ALLOW);
-
- yield openIdentityPopup();
-
- ok(is_hidden(emptyLabel), "List of permissions is not empty");
-
- let labelText = SitePermissions.getPermissionLabel("camera");
- let labels = permissionsList.querySelectorAll(".identity-popup-permission-label");
- is(labels.length, 1, "One permission visible in main view");
- is(labels[0].textContent, labelText, "Correct value");
-
- let img = permissionsList.querySelector("image.identity-popup-permission-icon");
- ok(img, "There is an image for the permissions");
- ok(img.classList.contains("camera-icon"), "proper class is in image class");
-
- yield closeIdentityPopup();
-
- SitePermissions.remove(gBrowser.currentURI, "camera");
-
- yield openIdentityPopup();
-
- ok(!is_hidden(emptyLabel), "List of permissions is empty");
-
- yield closeIdentityPopup();
-});
-
-add_task(function* testIdentityIcon() {
- let {gIdentityHandler} = gBrowser.ownerGlobal;
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
-
- SitePermissions.set(gBrowser.currentURI, "geo", SitePermissions.ALLOW);
-
- ok(gIdentityHandler._identityBox.classList.contains("grantedPermissions"),
- "identity-box signals granted permissions");
-
- SitePermissions.remove(gBrowser.currentURI, "geo");
-
- ok(!gIdentityHandler._identityBox.classList.contains("grantedPermissions"),
- "identity-box doesn't signal granted permissions");
-
- SitePermissions.set(gBrowser.currentURI, "camera", SitePermissions.BLOCK);
-
- ok(!gIdentityHandler._identityBox.classList.contains("grantedPermissions"),
- "identity-box doesn't signal granted permissions");
-
- SitePermissions.set(gBrowser.currentURI, "cookie", SitePermissions.SESSION);
-
- ok(gIdentityHandler._identityBox.classList.contains("grantedPermissions"),
- "identity-box signals granted permissions");
-
- SitePermissions.remove(gBrowser.currentURI, "geo");
- SitePermissions.remove(gBrowser.currentURI, "camera");
- SitePermissions.remove(gBrowser.currentURI, "cookie");
-});
-
-add_task(function* testCancelPermission() {
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
-
- let permissionsList = document.getElementById("identity-popup-permission-list");
- let emptyLabel = permissionsList.nextSibling.nextSibling;
-
- SitePermissions.set(gBrowser.currentURI, "geo", SitePermissions.ALLOW);
- SitePermissions.set(gBrowser.currentURI, "camera", SitePermissions.BLOCK);
-
- yield openIdentityPopup();
-
- ok(is_hidden(emptyLabel), "List of permissions is not empty");
-
- let cancelButtons = permissionsList
- .querySelectorAll(".identity-popup-permission-remove-button");
-
- cancelButtons[0].click();
- let labels = permissionsList.querySelectorAll(".identity-popup-permission-label");
- is(labels.length, 1, "One permission should be removed");
- cancelButtons[1].click();
- labels = permissionsList.querySelectorAll(".identity-popup-permission-label");
- is(labels.length, 0, "One permission should be removed");
-
- yield closeIdentityPopup();
-});
-
-add_task(function* testPermissionHints() {
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
-
- let permissionsList = document.getElementById("identity-popup-permission-list");
- let emptyHint = document.getElementById("identity-popup-permission-empty-hint");
- let reloadHint = document.getElementById("identity-popup-permission-reload-hint");
-
- yield openIdentityPopup();
-
- ok(!is_hidden(emptyHint), "Empty hint is visible");
- ok(is_hidden(reloadHint), "Reload hint is hidden");
-
- yield closeIdentityPopup();
-
- SitePermissions.set(gBrowser.currentURI, "geo", SitePermissions.ALLOW);
- SitePermissions.set(gBrowser.currentURI, "camera", SitePermissions.BLOCK);
-
- yield openIdentityPopup();
-
- ok(is_hidden(emptyHint), "Empty hint is hidden");
- ok(is_hidden(reloadHint), "Reload hint is hidden");
-
- let cancelButtons = permissionsList
- .querySelectorAll(".identity-popup-permission-remove-button");
- SitePermissions.remove(gBrowser.currentURI, "camera");
-
- cancelButtons[0].click();
- ok(is_hidden(emptyHint), "Empty hint is hidden");
- ok(!is_hidden(reloadHint), "Reload hint is visible");
-
- cancelButtons[1].click();
- ok(is_hidden(emptyHint), "Empty hint is hidden");
- ok(!is_hidden(reloadHint), "Reload hint is visible");
-
- yield closeIdentityPopup();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
- yield openIdentityPopup();
-
- ok(!is_hidden(emptyHint), "Empty hint is visible after reloading");
- ok(is_hidden(reloadHint), "Reload hint is hidden after reloading");
-
- yield closeIdentityPopup();
-});
-
-add_task(function* testPermissionIcons() {
- let {gIdentityHandler} = gBrowser.ownerGlobal;
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(tab, PERMISSIONS_PAGE);
-
- SitePermissions.set(gBrowser.currentURI, "camera", SitePermissions.ALLOW);
- SitePermissions.set(gBrowser.currentURI, "geo", SitePermissions.BLOCK);
- SitePermissions.set(gBrowser.currentURI, "microphone", SitePermissions.SESSION);
-
- let geoIcon = gIdentityHandler._identityBox
- .querySelector(".blocked-permission-icon[data-permission-id='geo']");
- ok(geoIcon.hasAttribute("showing"), "blocked permission icon is shown");
-
- let cameraIcon = gIdentityHandler._identityBox
- .querySelector(".blocked-permission-icon[data-permission-id='camera']");
- ok(!cameraIcon.hasAttribute("showing"),
- "allowed permission icon is not shown");
-
- let microphoneIcon = gIdentityHandler._identityBox
- .querySelector(".blocked-permission-icon[data-permission-id='microphone']");
- ok(!microphoneIcon.hasAttribute("showing"),
- "allowed permission icon is not shown");
-
- SitePermissions.remove(gBrowser.currentURI, "geo");
-
- ok(!geoIcon.hasAttribute("showing"),
- "blocked permission icon is not shown after reset");
-});
diff --git a/browser/base/content/test/general/browser_pinnedTabs.js b/browser/base/content/test/general/browser_pinnedTabs.js
deleted file mode 100644
index e0ddb5072..000000000
--- a/browser/base/content/test/general/browser_pinnedTabs.js
+++ /dev/null
@@ -1,75 +0,0 @@
-var tabs;
-
-function index(tab) {
- return Array.indexOf(gBrowser.tabs, tab);
-}
-
-function indexTest(tab, expectedIndex, msg) {
- var diag = "tab " + tab + " should be at index " + expectedIndex;
- if (msg)
- msg = msg + " (" + diag + ")";
- else
- msg = diag;
- is(index(tabs[tab]), expectedIndex, msg);
-}
-
-function PinUnpinHandler(tab, eventName) {
- this.eventCount = 0;
- var self = this;
- tab.addEventListener(eventName, function() {
- tab.removeEventListener(eventName, arguments.callee, true);
-
- self.eventCount++;
- }, true);
- gBrowser.tabContainer.addEventListener(eventName, function(e) {
- gBrowser.tabContainer.removeEventListener(eventName, arguments.callee, true);
-
- if (e.originalTarget == tab) {
- self.eventCount++;
- }
- }, true);
-}
-
-function test() {
- tabs = [gBrowser.selectedTab, gBrowser.addTab(), gBrowser.addTab(), gBrowser.addTab()];
- indexTest(0, 0);
- indexTest(1, 1);
- indexTest(2, 2);
- indexTest(3, 3);
-
- var eh = new PinUnpinHandler(tabs[3], "TabPinned");
- gBrowser.pinTab(tabs[3]);
- is(eh.eventCount, 2, "TabPinned event should be fired");
- indexTest(0, 1);
- indexTest(1, 2);
- indexTest(2, 3);
- indexTest(3, 0);
-
- eh = new PinUnpinHandler(tabs[1], "TabPinned");
- gBrowser.pinTab(tabs[1]);
- is(eh.eventCount, 2, "TabPinned event should be fired");
- indexTest(0, 2);
- indexTest(1, 1);
- indexTest(2, 3);
- indexTest(3, 0);
-
- gBrowser.moveTabTo(tabs[3], 3);
- indexTest(3, 1, "shouldn't be able to mix a pinned tab into normal tabs");
-
- gBrowser.moveTabTo(tabs[2], 0);
- indexTest(2, 2, "shouldn't be able to mix a normal tab into pinned tabs");
-
- eh = new PinUnpinHandler(tabs[1], "TabUnpinned");
- gBrowser.unpinTab(tabs[1]);
- is(eh.eventCount, 2, "TabUnpinned event should be fired");
- indexTest(1, 1, "unpinning a tab should move a tab to the start of normal tabs");
-
- eh = new PinUnpinHandler(tabs[3], "TabUnpinned");
- gBrowser.unpinTab(tabs[3]);
- is(eh.eventCount, 2, "TabUnpinned event should be fired");
- indexTest(3, 0, "unpinning a tab should move a tab to the start of normal tabs");
-
- gBrowser.removeTab(tabs[1]);
- gBrowser.removeTab(tabs[2]);
- gBrowser.removeTab(tabs[3]);
-}
diff --git a/browser/base/content/test/general/browser_plainTextLinks.js b/browser/base/content/test/general/browser_plainTextLinks.js
deleted file mode 100644
index 7a304fce0..000000000
--- a/browser/base/content/test/general/browser_plainTextLinks.js
+++ /dev/null
@@ -1,146 +0,0 @@
-function testExpected(expected, msg) {
- is(document.getElementById("context-openlinkincurrent").hidden, expected, msg);
-}
-
-function testLinkExpected(expected, msg) {
- is(gContextMenu.linkURL, expected, msg);
-}
-
-add_task(function *() {
- const url = "data:text/html;charset=UTF-8,Test For Non-Hyperlinked url selection";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- yield SimpleTest.promiseFocus(gBrowser.selectedBrowser.contentWindowAsCPOW);
-
- // Initial setup of the content area.
- yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) {
- let doc = content.document;
- let range = doc.createRange();
- let selection = content.getSelection();
-
- let mainDiv = doc.createElement("div");
- let div = doc.createElement("div");
- let div2 = doc.createElement("div");
- let span1 = doc.createElement("span");
- let span2 = doc.createElement("span");
- let span3 = doc.createElement("span");
- let span4 = doc.createElement("span");
- let p1 = doc.createElement("p");
- let p2 = doc.createElement("p");
- span1.textContent = "http://index.";
- span2.textContent = "example.com example.com";
- span3.textContent = " - Test";
- span4.innerHTML = "<a href='http://www.example.com'>http://www.example.com/example</a>";
- p1.textContent = "mailto:test.com ftp.example.com";
- p2.textContent = "example.com -";
- div.appendChild(span1);
- div.appendChild(span2);
- div.appendChild(span3);
- div.appendChild(span4);
- div.appendChild(p1);
- div.appendChild(p2);
- let p3 = doc.createElement("p");
- p3.textContent = "main.example.com";
- div2.appendChild(p3);
- mainDiv.appendChild(div);
- mainDiv.appendChild(div2);
- doc.body.appendChild(mainDiv);
-
- function setSelection(el1, el2, index1, index2) {
- while (el1.nodeType != el1.TEXT_NODE)
- el1 = el1.firstChild;
- while (el2.nodeType != el1.TEXT_NODE)
- el2 = el2.firstChild;
-
- selection.removeAllRanges();
- range.setStart(el1, index1);
- range.setEnd(el2, index2);
- selection.addRange(range);
-
- return range;
- }
-
- // Each of these tests creates a selection and returns a range within it.
- content.tests = [
- () => setSelection(span1.firstChild, span2.firstChild, 0, 11),
- () => setSelection(span1.firstChild, span2.firstChild, 7, 11),
- () => setSelection(span1.firstChild, span2.firstChild, 8, 11),
- () => setSelection(span2.firstChild, span2.firstChild, 0, 11),
- () => setSelection(span2.firstChild, span2.firstChild, 11, 23),
- () => setSelection(span2.firstChild, span2.firstChild, 0, 10),
- () => setSelection(span2.firstChild, span3.firstChild, 12, 7),
- () => setSelection(span2.firstChild, span2.firstChild, 12, 19),
- () => setSelection(p1.firstChild, p1.firstChild, 0, 15),
- () => setSelection(p1.firstChild, p1.firstChild, 16, 31),
- () => setSelection(p2.firstChild, p2.firstChild, 0, 14),
- () => {
- selection.selectAllChildren(div2);
- return selection.getRangeAt(0);
- },
- () => {
- selection.selectAllChildren(span4);
- return selection.getRangeAt(0);
- },
- () => {
- mainDiv.innerHTML = "(open-suse.ru)";
- return setSelection(mainDiv, mainDiv, 1, 13);
- },
- () => setSelection(mainDiv, mainDiv, 1, 14)
- ];
- });
-
- let checks = [
- () => testExpected(false, "The link context menu should show for http://www.example.com"),
- () => testExpected(false, "The link context menu should show for www.example.com"),
- () => testExpected(true, "The link context menu should not show for ww.example.com"),
- () => {
- testExpected(false, "The link context menu should show for example.com");
- testLinkExpected("http://example.com/", "url for example.com selection should not prepend www");
- },
- () => testExpected(false, "The link context menu should show for example.com"),
- () => testExpected(true, "Link options should not show for selection that's not at a word boundary"),
- () => testExpected(true, "Link options should not show for selection that has whitespace"),
- () => testExpected(true, "Link options should not show unless a url is selected"),
- () => testExpected(true, "Link options should not show for mailto: links"),
- () => {
- testExpected(false, "Link options should show for ftp.example.com");
- testLinkExpected("http://ftp.example.com/", "ftp.example.com should be preceeded with http://");
- },
- () => testExpected(false, "Link options should show for www.example.com "),
- () => testExpected(false, "Link options should show for triple-click selections"),
- () => testLinkExpected("http://www.example.com/", "Linkified text should open the correct link"),
- () => {
- testExpected(false, "Link options should show for open-suse.ru");
- testLinkExpected("http://open-suse.ru/", "Linkified text should open the correct link");
- },
- () => testExpected(true, "Link options should not show for 'open-suse.ru)'")
- ];
-
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
-
- for (let testid = 0; testid < checks.length; testid++) {
- let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid: testid }, function* (arg) {
- let range = content.tests[arg.testid]();
-
- // Get the range of the selection and determine its coordinates. These
- // coordinates will be returned to the parent process and the context menu
- // will be opened at that location.
- let rangeRect = range.getBoundingClientRect();
- return [rangeRect.x + 3, rangeRect.y + 3];
- });
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtPoint(menuPosition[0], menuPosition[1],
- { type: "contextmenu", button: 2 }, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- checks[testid]();
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
- }
-
- gBrowser.removeCurrentTab();
-});
-
diff --git a/browser/base/content/test/general/browser_printpreview.js b/browser/base/content/test/general/browser_printpreview.js
deleted file mode 100644
index c38fc18be..000000000
--- a/browser/base/content/test/general/browser_printpreview.js
+++ /dev/null
@@ -1,74 +0,0 @@
-let ourTab;
-
-function test() {
- waitForExplicitFinish();
-
- BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home", true).then(function(tab) {
- ourTab = tab;
- ok(!gInPrintPreviewMode,
- "Should NOT be in print preview mode at starting this tests");
- // Skip access key test on platforms which don't support access key.
- if (!/Win|Linux/.test(navigator.platform)) {
- openPrintPreview(testClosePrintPreviewWithEscKey);
- } else {
- openPrintPreview(testClosePrintPreviewWithAccessKey);
- }
- });
-}
-
-function tidyUp() {
- BrowserTestUtils.removeTab(ourTab).then(finish);
-}
-
-function testClosePrintPreviewWithAccessKey() {
- EventUtils.synthesizeKey("c", { altKey: true });
- checkPrintPreviewClosed(function (aSucceeded) {
- ok(aSucceeded,
- "print preview mode should be finished by access key");
- openPrintPreview(testClosePrintPreviewWithEscKey);
- });
-}
-
-function testClosePrintPreviewWithEscKey() {
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- checkPrintPreviewClosed(function (aSucceeded) {
- ok(aSucceeded,
- "print preview mode should be finished by Esc key press");
- openPrintPreview(testClosePrintPreviewWithClosingWindowShortcutKey);
- });
-}
-
-function testClosePrintPreviewWithClosingWindowShortcutKey() {
- EventUtils.synthesizeKey("w", { accelKey: true });
- checkPrintPreviewClosed(function (aSucceeded) {
- ok(aSucceeded,
- "print preview mode should be finished by closing window shortcut key");
- tidyUp();
- });
-}
-
-function openPrintPreview(aCallback) {
- document.getElementById("cmd_printPreview").doCommand();
- executeSoon(function () {
- if (gInPrintPreviewMode) {
- executeSoon(aCallback);
- return;
- }
- executeSoon(arguments.callee);
- });
-}
-
-function checkPrintPreviewClosed(aCallback) {
- let count = 0;
- executeSoon(function () {
- if (!gInPrintPreviewMode) {
- executeSoon(function () { aCallback(count < 1000); });
- return;
- }
- if (++count == 1000) {
- // The test might fail.
- PrintUtils.exitPrintPreview();
- }
- executeSoon(arguments.callee);
- });
-}
diff --git a/browser/base/content/test/general/browser_private_browsing_window.js b/browser/base/content/test/general/browser_private_browsing_window.js
deleted file mode 100644
index 607a34060..000000000
--- a/browser/base/content/test/general/browser_private_browsing_window.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// Make sure that we can open private browsing windows
-
-function test() {
- waitForExplicitFinish();
- var nonPrivateWin = OpenBrowserWindow();
- ok(!PrivateBrowsingUtils.isWindowPrivate(nonPrivateWin), "OpenBrowserWindow() should open a normal window");
- nonPrivateWin.close();
-
- var privateWin = OpenBrowserWindow({private: true});
- ok(PrivateBrowsingUtils.isWindowPrivate(privateWin), "OpenBrowserWindow({private: true}) should open a private window");
-
- nonPrivateWin = OpenBrowserWindow({private: false});
- ok(!PrivateBrowsingUtils.isWindowPrivate(nonPrivateWin), "OpenBrowserWindow({private: false}) should open a normal window");
- nonPrivateWin.close();
-
- whenDelayedStartupFinished(privateWin, function() {
- nonPrivateWin = privateWin.OpenBrowserWindow({private: false});
- ok(!PrivateBrowsingUtils.isWindowPrivate(nonPrivateWin), "privateWin.OpenBrowserWindow({private: false}) should open a normal window");
-
- nonPrivateWin.close();
-
- [
- { normal: "menu_newNavigator", private: "menu_newPrivateWindow", accesskey: true },
- { normal: "appmenu_newNavigator", private: "appmenu_newPrivateWindow", accesskey: false },
- ].forEach(function(menu) {
- let newWindow = privateWin.document.getElementById(menu.normal);
- let newPrivateWindow = privateWin.document.getElementById(menu.private);
- if (newWindow && newPrivateWindow) {
- ok(!newPrivateWindow.hidden, "New Private Window menu item should be hidden");
- isnot(newWindow.label, newPrivateWindow.label, "New Window's label shouldn't be overwritten");
- if (menu.accesskey) {
- isnot(newWindow.accessKey, newPrivateWindow.accessKey, "New Window's accessKey shouldn't be overwritten");
- }
- isnot(newWindow.command, newPrivateWindow.command, "New Window's command shouldn't be overwritten");
- }
- });
-
- privateWin.close();
-
- Services.prefs.setBoolPref("browser.privatebrowsing.autostart", true);
- privateWin = OpenBrowserWindow({private: true});
- whenDelayedStartupFinished(privateWin, function() {
- [
- { normal: "menu_newNavigator", private: "menu_newPrivateWindow", accessKey: true },
- { normal: "appmenu_newNavigator", private: "appmenu_newPrivateWindow", accessKey: false },
- ].forEach(function(menu) {
- let newWindow = privateWin.document.getElementById(menu.normal);
- let newPrivateWindow = privateWin.document.getElementById(menu.private);
- if (newWindow && newPrivateWindow) {
- ok(newPrivateWindow.hidden, "New Private Window menu item should be hidden");
- is(newWindow.label, newPrivateWindow.label, "New Window's label should be overwritten");
- if (menu.accesskey) {
- is(newWindow.accessKey, newPrivateWindow.accessKey, "New Window's accessKey should be overwritten");
- }
- is(newWindow.command, newPrivateWindow.command, "New Window's command should be overwritten");
- }
- });
-
- privateWin.close();
- Services.prefs.clearUserPref("browser.privatebrowsing.autostart");
- finish();
- });
- });
-}
-
diff --git a/browser/base/content/test/general/browser_private_no_prompt.js b/browser/base/content/test/general/browser_private_no_prompt.js
deleted file mode 100644
index c6c580f80..000000000
--- a/browser/base/content/test/general/browser_private_no_prompt.js
+++ /dev/null
@@ -1,12 +0,0 @@
-function test() {
- waitForExplicitFinish();
- var privateWin = OpenBrowserWindow({private: true});
-
- whenDelayedStartupFinished(privateWin, function () {
- privateWin.BrowserOpenTab();
- privateWin.BrowserTryToCloseWindow();
- ok(true, "didn't prompt");
-
- executeSoon(finish);
- });
-}
diff --git a/browser/base/content/test/general/browser_purgehistory_clears_sh.js b/browser/base/content/test/general/browser_purgehistory_clears_sh.js
deleted file mode 100644
index 1a1e6554d..000000000
--- a/browser/base/content/test/general/browser_purgehistory_clears_sh.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const url = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-
-add_task(function* purgeHistoryTest() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url,
- }, function* purgeHistoryTestInner(browser) {
- let backButton = browser.ownerDocument.getElementById("Browser:Back");
- let forwardButton = browser.ownerDocument.getElementById("Browser:Forward");
-
- ok(!browser.webNavigation.canGoBack,
- "Initial value for webNavigation.canGoBack");
- ok(!browser.webNavigation.canGoForward,
- "Initial value for webNavigation.canGoBack");
- ok(backButton.hasAttribute("disabled"), "Back button is disabled");
- ok(forwardButton.hasAttribute("disabled"), "Forward button is disabled");
-
- yield ContentTask.spawn(browser, null, function*() {
- let startHistory = content.history.length;
- content.history.pushState({}, "");
- content.history.pushState({}, "");
- content.history.back();
- let newHistory = content.history.length;
- Assert.equal(startHistory, 1, "Initial SHistory size");
- Assert.equal(newHistory, 3, "New SHistory size");
- });
-
- ok(browser.webNavigation.canGoBack, true,
- "New value for webNavigation.canGoBack");
- ok(browser.webNavigation.canGoForward, true,
- "New value for webNavigation.canGoForward");
- ok(!backButton.hasAttribute("disabled"), "Back button was enabled");
- ok(!forwardButton.hasAttribute("disabled"), "Forward button was enabled");
-
-
- let tmp = {};
- Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tmp);
-
- let {Sanitizer} = tmp;
- let sanitizer = new Sanitizer();
-
- yield sanitizer.sanitize(["history"]);
-
- yield ContentTask.spawn(browser, null, function*() {
- Assert.equal(content.history.length, 1, "SHistory correctly cleared");
- });
-
- ok(!browser.webNavigation.canGoBack,
- "webNavigation.canGoBack correctly cleared");
- ok(!browser.webNavigation.canGoForward,
- "webNavigation.canGoForward correctly cleared");
- ok(backButton.hasAttribute("disabled"), "Back button was disabled");
- ok(forwardButton.hasAttribute("disabled"), "Forward button was disabled");
- });
-});
diff --git a/browser/base/content/test/general/browser_refreshBlocker.js b/browser/base/content/test/general/browser_refreshBlocker.js
deleted file mode 100644
index ee274f2c2..000000000
--- a/browser/base/content/test/general/browser_refreshBlocker.js
+++ /dev/null
@@ -1,135 +0,0 @@
-"use strict";
-
-const META_PAGE = "http://example.org/browser/browser/base/content/test/general/refresh_meta.sjs"
-const HEADER_PAGE = "http://example.org/browser/browser/base/content/test/general/refresh_header.sjs"
-const TARGET_PAGE = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-const PREF = "accessibility.blockautorefresh";
-
-/**
- * Goes into the content, and simulates a meta-refresh header at a very
- * low level, and checks to see if it was blocked. This will always cancel
- * the refresh, regardless of whether or not the refresh was blocked.
- *
- * @param browser (<xul:browser>)
- * The browser to test for refreshing.
- * @param expectRefresh (bool)
- * Whether or not we expect the refresh attempt to succeed.
- * @returns Promise
- */
-function* attemptFakeRefresh(browser, expectRefresh) {
- yield ContentTask.spawn(browser, expectRefresh, function*(contentExpectRefresh) {
- let URI = docShell.QueryInterface(Ci.nsIWebNavigation).currentURI;
- let refresher = docShell.QueryInterface(Ci.nsIRefreshURI);
- refresher.refreshURI(URI, 0, false, true);
-
- Assert.equal(refresher.refreshPending, contentExpectRefresh,
- "Got the right refreshPending state");
-
- if (refresher.refreshPending) {
- // Cancel the pending refresh
- refresher.cancelRefreshURITimers();
- }
-
- // The RefreshBlocker will wait until onLocationChange has
- // been fired before it will show any notifications (see bug
- // 1246291), so we cause this to occur manually here.
- content.location = URI.spec + "#foo";
- });
-}
-
-/**
- * Tests that we can enable the blocking pref and block a refresh
- * from occurring while showing a notification bar. Also tests that
- * when we disable the pref, that refreshes can go through again.
- */
-add_task(function* test_can_enable_and_block() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TARGET_PAGE,
- }, function*(browser) {
- // By default, we should be able to reload the page.
- yield attemptFakeRefresh(browser, true);
-
- yield pushPrefs(["accessibility.blockautorefresh", true]);
-
- let notificationPromise =
- BrowserTestUtils.waitForNotificationBar(gBrowser, browser,
- "refresh-blocked");
-
- yield attemptFakeRefresh(browser, false);
-
- yield notificationPromise;
-
- yield pushPrefs(["accessibility.blockautorefresh", false]);
-
- // Page reloads should go through again.
- yield attemptFakeRefresh(browser, true);
- });
-});
-
-/**
- * Attempts a "real" refresh by opening a tab, and then sending it to
- * an SJS page that will attempt to cause a refresh. This will also pass
- * a delay amount to the SJS page. The refresh should be blocked, and
- * the notification should be shown. Once shown, the "Allow" button will
- * be clicked, and the refresh will go through. Finally, the helper will
- * close the tab and resolve the Promise.
- *
- * @param refreshPage (string)
- * The SJS page to use. Use META_PAGE for the <meta> tag refresh
- * case. Use HEADER_PAGE for the HTTP header case.
- * @param delay (int)
- * The amount, in ms, for the page to wait before attempting the
- * refresh.
- *
- * @returns Promise
- */
-function* testRealRefresh(refreshPage, delay) {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank",
- }, function*(browser) {
- yield pushPrefs(["accessibility.blockautorefresh", true]);
-
- browser.loadURI(refreshPage + "?p=" + TARGET_PAGE + "&d=" + delay);
- yield BrowserTestUtils.browserLoaded(browser);
-
- // Once browserLoaded resolves, all nsIWebProgressListener callbacks
- // should have fired, so the notification should be visible.
- let notificationBox = gBrowser.getNotificationBox(browser);
- let notification = notificationBox.currentNotification;
-
- ok(notification, "Notification should be visible");
- is(notification.value, "refresh-blocked",
- "Should be showing the right notification");
-
- // Then click the button to allow the refresh.
- let buttons = notification.querySelectorAll(".notification-button");
- is(buttons.length, 1, "Should have one button.");
-
- // Prepare a Promise that should resolve when the refresh goes through
- let refreshPromise = BrowserTestUtils.browserLoaded(browser);
- buttons[0].click();
-
- yield refreshPromise;
- });
-}
-
-/**
- * Tests the meta-tag case for both short and longer delay times.
- */
-add_task(function* test_can_allow_refresh() {
- yield testRealRefresh(META_PAGE, 0);
- yield testRealRefresh(META_PAGE, 100);
- yield testRealRefresh(META_PAGE, 500);
-});
-
-/**
- * Tests that when a HTTP header case for both short and longer
- * delay times.
- */
-add_task(function* test_can_block_refresh_from_header() {
- yield testRealRefresh(HEADER_PAGE, 0);
- yield testRealRefresh(HEADER_PAGE, 100);
- yield testRealRefresh(HEADER_PAGE, 500);
-});
diff --git a/browser/base/content/test/general/browser_registerProtocolHandler_notification.html b/browser/base/content/test/general/browser_registerProtocolHandler_notification.html
deleted file mode 100644
index 241b03b95..000000000
--- a/browser/base/content/test/general/browser_registerProtocolHandler_notification.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <title>Protocol registrar page</title>
- <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
- <meta content="utf-8" http-equiv="encoding">
- </head>
- <body>
- <script type="text/javascript">
- navigator.registerProtocolHandler("testprotocol",
- "https://example.com/foobar?uri=%s",
- "Test Protocol");
- </script>
- </body>
-</html>
diff --git a/browser/base/content/test/general/browser_registerProtocolHandler_notification.js b/browser/base/content/test/general/browser_registerProtocolHandler_notification.js
deleted file mode 100644
index b30ece0f6..000000000
--- a/browser/base/content/test/general/browser_registerProtocolHandler_notification.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
- let notificationValue = "Protocol Registration: testprotocol";
- let testURI = "http://example.com/browser/" +
- "browser/base/content/test/general/browser_registerProtocolHandler_notification.html";
-
- waitForCondition(function() {
- // Do not start until the notification is up
- let notificationBox = window.gBrowser.getNotificationBox();
- let notification = notificationBox.getNotificationWithValue(notificationValue);
- return notification;
- },
- function() {
-
- let notificationBox = window.gBrowser.getNotificationBox();
- let notification = notificationBox.getNotificationWithValue(notificationValue);
- ok(notification, "Notification box should be displayed");
- if (notification == null) {
- finish();
- return;
- }
- is(notification.type, "info", "We expect this notification to have the type of 'info'.");
- isnot(notification.image, null, "We expect this notification to have an icon.");
-
- let buttons = notification.getElementsByClassName("notification-button-default");
- is(buttons.length, 1, "We expect see one default button.");
-
- buttons = notification.getElementsByClassName("notification-button");
- is(buttons.length, 1, "We expect see one button.");
-
- let button = buttons[0];
- isnot(button.label, null, "We expect the add button to have a label.");
- todo_isnot(button.accesskey, null, "We expect the add button to have a accesskey.");
-
- finish();
- }, "Still can not get notification after retry 100 times.", 100);
-
- window.gBrowser.selectedBrowser.loadURI(testURI);
-}
diff --git a/browser/base/content/test/general/browser_relatedTabs.js b/browser/base/content/test/general/browser_relatedTabs.js
deleted file mode 100644
index 97cf51d84..000000000
--- a/browser/base/content/test/general/browser_relatedTabs.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* 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/. */
-
-add_task(function*() {
- is(gBrowser.tabs.length, 1, "one tab is open initially");
-
- // Add several new tabs in sequence, interrupted by selecting a
- // different tab, moving a tab around and closing a tab,
- // returning a list of opened tabs for verifying the expected order.
- // The new tab behaviour is documented in bug 465673
- let tabs = [];
- function addTab(aURL, aReferrer) {
- let tab = gBrowser.addTab(aURL, {referrerURI: aReferrer});
- tabs.push(tab);
- return BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- }
-
- yield addTab("http://mochi.test:8888/#0");
- gBrowser.selectedTab = tabs[0];
- yield addTab("http://mochi.test:8888/#1");
- yield addTab("http://mochi.test:8888/#2", gBrowser.currentURI);
- yield addTab("http://mochi.test:8888/#3", gBrowser.currentURI);
- gBrowser.selectedTab = tabs[tabs.length - 1];
- gBrowser.selectedTab = tabs[0];
- yield addTab("http://mochi.test:8888/#4", gBrowser.currentURI);
- gBrowser.selectedTab = tabs[3];
- yield addTab("http://mochi.test:8888/#5", gBrowser.currentURI);
- gBrowser.removeTab(tabs.pop());
- yield addTab("about:blank", gBrowser.currentURI);
- gBrowser.moveTabTo(gBrowser.selectedTab, 1);
- yield addTab("http://mochi.test:8888/#6", gBrowser.currentURI);
- yield addTab();
- yield addTab("http://mochi.test:8888/#7");
-
- function testPosition(tabNum, expectedPosition, msg) {
- is(Array.indexOf(gBrowser.tabs, tabs[tabNum]), expectedPosition, msg);
- }
-
- testPosition(0, 3, "tab without referrer was opened to the far right");
- testPosition(1, 7, "tab without referrer was opened to the far right");
- testPosition(2, 5, "tab with referrer opened immediately to the right");
- testPosition(3, 1, "next tab with referrer opened further to the right");
- testPosition(4, 4, "tab selection changed, tab opens immediately to the right");
- testPosition(5, 6, "blank tab with referrer opens to the right of 3rd original tab where removed tab was");
- testPosition(6, 2, "tab has moved, new tab opens immediately to the right");
- testPosition(7, 8, "blank tab without referrer opens at the end");
- testPosition(8, 9, "tab without referrer opens at the end");
-
- tabs.forEach(gBrowser.removeTab, gBrowser);
-});
diff --git a/browser/base/content/test/general/browser_remoteTroubleshoot.js b/browser/base/content/test/general/browser_remoteTroubleshoot.js
deleted file mode 100644
index 5c939dbd0..000000000
--- a/browser/base/content/test/general/browser_remoteTroubleshoot.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* 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/. */
-
-var {WebChannel} = Cu.import("resource://gre/modules/WebChannel.jsm", {});
-
-const TEST_URL_TAIL = "example.com/browser/browser/base/content/test/general/test_remoteTroubleshoot.html"
-const TEST_URI_GOOD = Services.io.newURI("https://" + TEST_URL_TAIL, null, null);
-const TEST_URI_BAD = Services.io.newURI("http://" + TEST_URL_TAIL, null, null);
-const TEST_URI_GOOD_OBJECT = Services.io.newURI("https://" + TEST_URL_TAIL + "?object", null, null);
-
-// Creates a one-shot web-channel for the test data to be sent back from the test page.
-function promiseChannelResponse(channelID, originOrPermission) {
- return new Promise((resolve, reject) => {
- let channel = new WebChannel(channelID, originOrPermission);
- channel.listen((id, data, target) => {
- channel.stopListening();
- resolve(data);
- });
- });
-}
-
-// Loads the specified URI in a new tab and waits for it to send us data on our
-// test web-channel and resolves with that data.
-function promiseNewChannelResponse(uri) {
- let channelPromise = promiseChannelResponse("test-remote-troubleshooting-backchannel",
- uri);
- let tab = gBrowser.loadOneTab(uri.spec, { inBackground: false });
- return promiseTabLoaded(tab).then(
- () => channelPromise
- ).then(data => {
- gBrowser.removeTab(tab);
- return data;
- });
-}
-
-add_task(function*() {
- // We haven't set a permission yet - so even the "good" URI should fail.
- let got = yield promiseNewChannelResponse(TEST_URI_GOOD);
- // Should have no data.
- Assert.ok(got.message === undefined, "should have failed to get any data");
-
- // Add a permission manager entry for our URI.
- Services.perms.add(TEST_URI_GOOD,
- "remote-troubleshooting",
- Services.perms.ALLOW_ACTION);
- registerCleanupFunction(() => {
- Services.perms.remove(TEST_URI_GOOD, "remote-troubleshooting");
- });
-
- // Try again - now we are expecting a response with the actual data.
- got = yield promiseNewChannelResponse(TEST_URI_GOOD);
-
- // Check some keys we expect to always get.
- Assert.ok(got.message.extensions, "should have extensions");
- Assert.ok(got.message.graphics, "should have graphics");
-
- // Check we have channel and build ID info:
- Assert.equal(got.message.application.buildID, Services.appinfo.appBuildID,
- "should have correct build ID");
-
- let updateChannel = null;
- try {
- updateChannel = Cu.import("resource://gre/modules/UpdateUtils.jsm", {}).UpdateUtils.UpdateChannel;
- } catch (ex) {}
- if (!updateChannel) {
- Assert.ok(!('updateChannel' in got.message.application),
- "should not have update channel where not available.");
- } else {
- Assert.equal(got.message.application.updateChannel, updateChannel,
- "should have correct update channel.");
- }
-
-
- // And check some keys we know we decline to return.
- Assert.ok(!got.message.modifiedPreferences, "should not have a modifiedPreferences key");
- Assert.ok(!got.message.crashes, "should not have crash info");
-
- // Now a http:// URI - should get nothing even with the permission setup.
- got = yield promiseNewChannelResponse(TEST_URI_BAD);
- Assert.ok(got.message === undefined, "should have failed to get any data");
-
- // Check that the page can send an object as well if it's in the whitelist
- let webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist";
- let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref);
- let newWhitelist = origWhitelist + " https://example.com";
- Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref(webchannelWhitelistPref);
- });
- got = yield promiseNewChannelResponse(TEST_URI_GOOD_OBJECT);
- Assert.ok(got.message, "should have gotten some data back");
-});
diff --git a/browser/base/content/test/general/browser_remoteWebNavigation_postdata.js b/browser/base/content/test/general/browser_remoteWebNavigation_postdata.js
deleted file mode 100644
index 451323f50..000000000
--- a/browser/base/content/test/general/browser_remoteWebNavigation_postdata.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* 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/. */
-
-Cu.import("resource://gre/modules/BrowserUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-function makeInputStream(aString) {
- let stream = Cc["@mozilla.org/io/string-input-stream;1"]
- .createInstance(Ci.nsIStringInputStream);
- stream.data = aString;
- return stream; // XPConnect will QI this to nsIInputStream for us.
-}
-
-add_task(function* test_remoteWebNavigation_postdata() {
- let obj = {};
- Cu.import("resource://testing-common/httpd.js", obj);
- Cu.import("resource://services-common/utils.js", obj);
-
- let server = new obj.HttpServer();
- server.start(-1);
-
- let loadDeferred = Promise.defer();
-
- server.registerPathHandler("/test", (request, response) => {
- let body = obj.CommonUtils.readBytesFromInputStream(request.bodyInputStream);
- is(body, "success", "request body is correct");
- is(request.method, "POST", "request was a post");
- response.write("Received from POST: " + body);
- loadDeferred.resolve();
- });
-
- let i = server.identity;
- let path = i.primaryScheme + "://" + i.primaryHost + ":" + i.primaryPort + "/test";
-
- let postdata =
- "Content-Length: 7\r\n" +
- "Content-Type: application/x-www-form-urlencoded\r\n" +
- "\r\n" +
- "success";
-
- openUILinkIn(path, "tab", null, makeInputStream(postdata));
-
- yield loadDeferred.promise;
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- let serverStoppedDeferred = Promise.defer();
- server.stop(function() { serverStoppedDeferred.resolve(); });
- yield serverStoppedDeferred.promise;
-});
diff --git a/browser/base/content/test/general/browser_removeTabsToTheEnd.js b/browser/base/content/test/general/browser_removeTabsToTheEnd.js
deleted file mode 100644
index 351085d74..000000000
--- a/browser/base/content/test/general/browser_removeTabsToTheEnd.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* 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/. */
-
-function test() {
- // Add two new tabs after the original tab. Pin the first one.
- let originalTab = gBrowser.selectedTab;
- let newTab1 = gBrowser.addTab();
- gBrowser.addTab();
- gBrowser.pinTab(newTab1);
-
- // Check that there is only one closable tab from originalTab to the end
- is(gBrowser.getTabsToTheEndFrom(originalTab).length, 1,
- "One unpinned tab to the right");
-
- // Remove tabs to the end
- gBrowser.removeTabsToTheEndFrom(originalTab);
- is(gBrowser.tabs.length, 2, "Length is 2");
- is(gBrowser.tabs[1], originalTab, "Starting tab is not removed");
- is(gBrowser.tabs[0], newTab1, "Pinned tab is not removed");
-
- // Remove pinned tab
- gBrowser.removeTab(newTab1);
-}
diff --git a/browser/base/content/test/general/browser_restore_isAppTab.js b/browser/base/content/test/general/browser_restore_isAppTab.js
deleted file mode 100644
index e20974d80..000000000
--- a/browser/base/content/test/general/browser_restore_isAppTab.js
+++ /dev/null
@@ -1,160 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
-const DUMMY = "http://example.com/browser/browser/base/content/test/general/dummy_page.html";
-
-function getMinidumpDirectory() {
- let dir = Services.dirsvc.get('ProfD', Ci.nsIFile);
- dir.append("minidumps");
- return dir;
-}
-
-// This observer is needed so we can clean up all evidence of the crash so
-// the testrunner thinks things are peachy.
-var CrashObserver = {
- observe: function(subject, topic, data) {
- is(topic, 'ipc:content-shutdown', 'Received correct observer topic.');
- ok(subject instanceof Ci.nsIPropertyBag2,
- 'Subject implements nsIPropertyBag2.');
- // we might see this called as the process terminates due to previous tests.
- // We are only looking for "abnormal" exits...
- if (!subject.hasKey("abnormal")) {
- info("This is a normal termination and isn't the one we are looking for...");
- return;
- }
-
- let dumpID;
- if ('nsICrashReporter' in Ci) {
- dumpID = subject.getPropertyAsAString('dumpID');
- ok(dumpID, "dumpID is present and not an empty string");
- }
-
- if (dumpID) {
- let minidumpDirectory = getMinidumpDirectory();
- let file = minidumpDirectory.clone();
- file.append(dumpID + '.dmp');
- file.remove(true);
- file = minidumpDirectory.clone();
- file.append(dumpID + '.extra');
- file.remove(true);
- }
- }
-}
-Services.obs.addObserver(CrashObserver, 'ipc:content-shutdown', false);
-
-registerCleanupFunction(() => {
- Services.obs.removeObserver(CrashObserver, 'ipc:content-shutdown');
-});
-
-function frameScript() {
- addMessageListener("Test:GetIsAppTab", function() {
- sendAsyncMessage("Test:IsAppTab", { isAppTab: docShell.isAppTab });
- });
-
- addMessageListener("Test:Crash", function() {
- privateNoteIntentionalCrash();
- Components.utils.import("resource://gre/modules/ctypes.jsm");
- let zero = new ctypes.intptr_t(8);
- let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
- badptr.contents
- });
-}
-
-function loadFrameScript(browser) {
- browser.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")();", true);
-}
-
-function isBrowserAppTab(browser) {
- return new Promise(resolve => {
- function listener({ data }) {
- browser.messageManager.removeMessageListener("Test:IsAppTab", listener);
- resolve(data.isAppTab);
- }
- // It looks like same-process messages may be reordered by the message
- // manager, so we need to wait one tick before sending the message.
- executeSoon(function () {
- browser.messageManager.addMessageListener("Test:IsAppTab", listener);
- browser.messageManager.sendAsyncMessage("Test:GetIsAppTab");
- });
- });
-}
-
-// Restarts the child process by crashing it then reloading the tab
-var restart = Task.async(function*(browser) {
- // If the tab isn't remote this would crash the main process so skip it
- if (!browser.isRemoteBrowser)
- return;
-
- // Make sure the main process has all of the current tab state before crashing
- yield TabStateFlusher.flush(browser);
-
- browser.messageManager.sendAsyncMessage("Test:Crash");
- yield promiseWaitForEvent(browser, "AboutTabCrashedLoad", false, true);
-
- let tab = gBrowser.getTabForBrowser(browser);
- SessionStore.reviveCrashedTab(tab);
-
- yield promiseTabLoaded(tab);
-});
-
-add_task(function* navigate() {
- let tab = gBrowser.addTab("about:robots");
- let browser = tab.linkedBrowser;
- gBrowser.selectedTab = tab;
- yield waitForDocLoadComplete();
- loadFrameScript(browser);
- let isAppTab = yield isBrowserAppTab(browser);
- ok(!isAppTab, "Docshell shouldn't think it is an app tab");
-
- gBrowser.pinTab(tab);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- gBrowser.loadURI(DUMMY);
- yield waitForDocLoadComplete();
- loadFrameScript(browser);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- gBrowser.unpinTab(tab);
- isAppTab = yield isBrowserAppTab(browser);
- ok(!isAppTab, "Docshell shouldn't think it is an app tab");
-
- gBrowser.pinTab(tab);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- gBrowser.loadURI("about:robots");
- yield waitForDocLoadComplete();
- loadFrameScript(browser);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* crash() {
- if (!gMultiProcessBrowser || !("nsICrashReporter" in Ci))
- return;
-
- let tab = gBrowser.addTab(DUMMY);
- let browser = tab.linkedBrowser;
- gBrowser.selectedTab = tab;
- yield waitForDocLoadComplete();
- loadFrameScript(browser);
- let isAppTab = yield isBrowserAppTab(browser);
- ok(!isAppTab, "Docshell shouldn't think it is an app tab");
-
- gBrowser.pinTab(tab);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- yield restart(browser);
- loadFrameScript(browser);
- isAppTab = yield isBrowserAppTab(browser);
- ok(isAppTab, "Docshell should think it is an app tab");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_sanitize-passwordDisabledHosts.js b/browser/base/content/test/general/browser_sanitize-passwordDisabledHosts.js
deleted file mode 100644
index 4f4f5c398..000000000
--- a/browser/base/content/test/general/browser_sanitize-passwordDisabledHosts.js
+++ /dev/null
@@ -1,39 +0,0 @@
-// Bug 474792 - Clear "Never remember passwords for this site" when
-// clearing site-specific settings in Clear Recent History dialog
-
-var tempScope = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tempScope);
-var Sanitizer = tempScope.Sanitizer;
-
-add_task(function*() {
- var pwmgr = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
-
- // Add a disabled host
- pwmgr.setLoginSavingEnabled("http://example.com", false);
- // Sanity check
- is(pwmgr.getLoginSavingEnabled("http://example.com"), false,
- "example.com should be disabled for password saving since we haven't cleared that yet.");
-
- // Set up the sanitizer to just clear siteSettings
- let s = new Sanitizer();
- s.ignoreTimespan = false;
- s.prefDomain = "privacy.cpd.";
- var itemPrefs = gPrefService.getBranch(s.prefDomain);
- itemPrefs.setBoolPref("history", false);
- itemPrefs.setBoolPref("downloads", false);
- itemPrefs.setBoolPref("cache", false);
- itemPrefs.setBoolPref("cookies", false);
- itemPrefs.setBoolPref("formdata", false);
- itemPrefs.setBoolPref("offlineApps", false);
- itemPrefs.setBoolPref("passwords", false);
- itemPrefs.setBoolPref("sessions", false);
- itemPrefs.setBoolPref("siteSettings", true);
-
- // Clear it
- yield s.sanitize();
-
- // Make sure it's gone
- is(pwmgr.getLoginSavingEnabled("http://example.com"), true,
- "example.com should be enabled for password saving again now that we've cleared.");
-});
diff --git a/browser/base/content/test/general/browser_sanitize-sitepermissions.js b/browser/base/content/test/general/browser_sanitize-sitepermissions.js
deleted file mode 100644
index 1b43d62fc..000000000
--- a/browser/base/content/test/general/browser_sanitize-sitepermissions.js
+++ /dev/null
@@ -1,52 +0,0 @@
-// Bug 380852 - Delete permission manager entries in Clear Recent History
-
-var tempScope = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tempScope);
-var Sanitizer = tempScope.Sanitizer;
-
-function countPermissions() {
- let result = 0;
- let enumerator = Services.perms.enumerator;
- while (enumerator.hasMoreElements()) {
- result++;
- enumerator.getNext();
- }
- return result;
-}
-
-add_task(function* test() {
- // sanitize before we start so we have a good baseline.
- // Set up the sanitizer to just clear siteSettings
- let s = new Sanitizer();
- s.ignoreTimespan = false;
- s.prefDomain = "privacy.cpd.";
- var itemPrefs = gPrefService.getBranch(s.prefDomain);
- itemPrefs.setBoolPref("history", false);
- itemPrefs.setBoolPref("downloads", false);
- itemPrefs.setBoolPref("cache", false);
- itemPrefs.setBoolPref("cookies", false);
- itemPrefs.setBoolPref("formdata", false);
- itemPrefs.setBoolPref("offlineApps", false);
- itemPrefs.setBoolPref("passwords", false);
- itemPrefs.setBoolPref("sessions", false);
- itemPrefs.setBoolPref("siteSettings", true);
- s.sanitize();
-
- // Count how many permissions we start with - some are defaults that
- // will not be sanitized.
- let numAtStart = countPermissions();
-
- // Add a permission entry
- var pm = Services.perms;
- pm.add(makeURI("http://example.com"), "testing", pm.ALLOW_ACTION);
-
- // Sanity check
- ok(pm.enumerator.hasMoreElements(), "Permission manager should have elements, since we just added one");
-
- // Clear it
- yield s.sanitize();
-
- // Make sure it's gone
- is(numAtStart, countPermissions(), "Permission manager should have the same count it started with");
-});
diff --git a/browser/base/content/test/general/browser_sanitize-timespans.js b/browser/base/content/test/general/browser_sanitize-timespans.js
deleted file mode 100644
index 3712c5e1c..000000000
--- a/browser/base/content/test/general/browser_sanitize-timespans.js
+++ /dev/null
@@ -1,733 +0,0 @@
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-requestLongerTimeout(2);
-
-// Bug 453440 - Test the timespan-based logic of the sanitizer code
-var now_mSec = Date.now();
-var now_uSec = now_mSec * 1000;
-
-const kMsecPerMin = 60 * 1000;
-const kUsecPerMin = 60 * 1000000;
-
-var tempScope = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tempScope);
-var Sanitizer = tempScope.Sanitizer;
-
-var FormHistory = (Components.utils.import("resource://gre/modules/FormHistory.jsm", {})).FormHistory;
-var Downloads = (Components.utils.import("resource://gre/modules/Downloads.jsm", {})).Downloads;
-
-function promiseFormHistoryRemoved() {
- let deferred = Promise.defer();
- Services.obs.addObserver(function onfh() {
- Services.obs.removeObserver(onfh, "satchel-storage-changed", false);
- deferred.resolve();
- }, "satchel-storage-changed", false);
- return deferred.promise;
-}
-
-function promiseDownloadRemoved(list) {
- let deferred = Promise.defer();
-
- let view = {
- onDownloadRemoved: function(download) {
- list.removeView(view);
- deferred.resolve();
- }
- };
-
- list.addView(view);
-
- return deferred.promise;
-}
-
-add_task(function* test() {
- yield setupDownloads();
- yield setupFormHistory();
- yield setupHistory();
- yield onHistoryReady();
-});
-
-function countEntries(name, message, check) {
- let deferred = Promise.defer();
-
- var obj = {};
- if (name !== null)
- obj.fieldname = name;
-
- let count;
- FormHistory.count(obj, { handleResult: result => count = result,
- handleError: function (error) {
- deferred.reject(error)
- throw new Error("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) {
- if (!reason) {
- check(count, message);
- deferred.resolve();
- }
- },
- });
-
- return deferred.promise;
-}
-
-function* onHistoryReady() {
- var hoursSinceMidnight = new Date().getHours();
- var minutesSinceMidnight = hoursSinceMidnight * 60 + new Date().getMinutes();
-
- // Should test cookies here, but nsICookieManager/nsICookieService
- // doesn't let us fake creation times. bug 463127
-
- let s = new Sanitizer();
- s.ignoreTimespan = false;
- s.prefDomain = "privacy.cpd.";
- var itemPrefs = gPrefService.getBranch(s.prefDomain);
- itemPrefs.setBoolPref("history", true);
- itemPrefs.setBoolPref("downloads", true);
- itemPrefs.setBoolPref("cache", false);
- itemPrefs.setBoolPref("cookies", false);
- itemPrefs.setBoolPref("formdata", true);
- itemPrefs.setBoolPref("offlineApps", false);
- itemPrefs.setBoolPref("passwords", false);
- itemPrefs.setBoolPref("sessions", false);
- itemPrefs.setBoolPref("siteSettings", false);
-
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
- let downloadPromise = promiseDownloadRemoved(publicList);
- let formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 10 minutes ago
- s.range = [now_uSec - 10*60*1000000, now_uSec];
- yield s.sanitize();
- s.range = null;
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://10minutes.com"))),
- "Pretend visit to 10minutes.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://1hour.com"))),
- "Pretend visit to 1hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://1hour10minutes.com"))),
- "Pretend visit to 1hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://2hour.com"))),
- "Pretend visit to 2hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://2hour10minutes.com"))),
- "Pretend visit to 2hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (minutesSinceMidnight > 10) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- let checkZero = function(num, message) { is(num, 0, message); }
- let checkOne = function(num, message) { is(num, 1, message); }
-
- yield countEntries("10minutes", "10minutes form entry should be deleted", checkZero);
- yield countEntries("1hour", "1hour form entry should still exist", checkOne);
- yield countEntries("1hour10minutes", "1hour10minutes form entry should still exist", checkOne);
- yield countEntries("2hour", "2hour form entry should still exist", checkOne);
- yield countEntries("2hour10minutes", "2hour10minutes form entry should still exist", checkOne);
- yield countEntries("4hour", "4hour form entry should still exist", checkOne);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (minutesSinceMidnight > 10)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-10-minutes")), "10 minute download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-1-hour")), "<1 hour download should still be present");
- ok((yield downloadExists(publicList, "fakefile-1-hour-10-minutes")), "1 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour")), "<2 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "2 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
-
- if (minutesSinceMidnight > 10)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 1 hour
- Sanitizer.prefs.setIntPref("timeSpan", 1);
- yield s.sanitize();
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://1hour.com"))),
- "Pretend visit to 1hour.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://1hour10minutes.com"))),
- "Pretend visit to 1hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://2hour.com"))),
- "Pretend visit to 2hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://2hour10minutes.com"))),
- "Pretend visit to 2hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (hoursSinceMidnight > 1) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("1hour", "1hour form entry should be deleted", checkZero);
- yield countEntries("1hour10minutes", "1hour10minutes form entry should still exist", checkOne);
- yield countEntries("2hour", "2hour form entry should still exist", checkOne);
- yield countEntries("2hour10minutes", "2hour10minutes form entry should still exist", checkOne);
- yield countEntries("4hour", "4hour form entry should still exist", checkOne);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (hoursSinceMidnight > 1)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-1-hour")), "<1 hour download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-1-hour-10-minutes")), "1 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour")), "<2 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "2 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
-
- if (hoursSinceMidnight > 1)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 1 hour 10 minutes
- s.range = [now_uSec - 70*60*1000000, now_uSec];
- yield s.sanitize();
- s.range = null;
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://1hour10minutes.com"))),
- "Pretend visit to 1hour10minutes.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://2hour.com"))),
- "Pretend visit to 2hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://2hour10minutes.com"))),
- "Pretend visit to 2hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (minutesSinceMidnight > 70) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("1hour10minutes", "1hour10minutes form entry should be deleted", checkZero);
- yield countEntries("2hour", "2hour form entry should still exist", checkOne);
- yield countEntries("2hour10minutes", "2hour10minutes form entry should still exist", checkOne);
- yield countEntries("4hour", "4hour form entry should still exist", checkOne);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (minutesSinceMidnight > 70)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-1-hour-10-minutes")), "1 hour 10 minute old download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour")), "<2 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "2 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
- if (minutesSinceMidnight > 70)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 2 hours
- Sanitizer.prefs.setIntPref("timeSpan", 2);
- yield s.sanitize();
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://2hour.com"))),
- "Pretend visit to 2hour.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://2hour10minutes.com"))),
- "Pretend visit to 2hour10minutes.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (hoursSinceMidnight > 2) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("2hour", "2hour form entry should be deleted", checkZero);
- yield countEntries("2hour10minutes", "2hour10minutes form entry should still exist", checkOne);
- yield countEntries("4hour", "4hour form entry should still exist", checkOne);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (hoursSinceMidnight > 2)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-2-hour")), "<2 hour old download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "2 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
- if (hoursSinceMidnight > 2)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 2 hours 10 minutes
- s.range = [now_uSec - 130*60*1000000, now_uSec];
- yield s.sanitize();
- s.range = null;
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://2hour10minutes.com"))),
- "Pretend visit to 2hour10minutes.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should should still exist");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (minutesSinceMidnight > 130) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("2hour10minutes", "2hour10minutes form entry should be deleted", checkZero);
- yield countEntries("4hour", "4hour form entry should still exist", checkOne);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (minutesSinceMidnight > 130)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "2 hour 10 minute old download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should still be present");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- if (minutesSinceMidnight > 130)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 4 hours
- Sanitizer.prefs.setIntPref("timeSpan", 3);
- yield s.sanitize();
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://4hour.com"))),
- "Pretend visit to 4hour.com should now be deleted");
- ok((yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should should still exist");
- if (hoursSinceMidnight > 4) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("4hour", "4hour form entry should be deleted", checkZero);
- yield countEntries("4hour10minutes", "4hour10minutes form entry should still exist", checkOne);
- if (hoursSinceMidnight > 4)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-4-hour")), "<4 hour old download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should still be present");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- if (hoursSinceMidnight > 4)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear 4 hours 10 minutes
- s.range = [now_uSec - 250*60*1000000, now_uSec];
- yield s.sanitize();
- s.range = null;
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://4hour10minutes.com"))),
- "Pretend visit to 4hour10minutes.com should now be deleted");
- if (minutesSinceMidnight > 250) {
- ok((yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should still exist");
- }
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
-
- yield countEntries("4hour10minutes", "4hour10minutes form entry should be deleted", checkZero);
- if (minutesSinceMidnight > 250)
- yield countEntries("today", "today form entry should still exist", checkOne);
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
-
- ok(!(yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "4 hour 10 minute download should now be deleted");
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
- if (minutesSinceMidnight > 250)
- ok((yield downloadExists(publicList, "fakefile-today")), "'Today' download should still be present");
-
- // The 'Today' download might have been already deleted, in which case we
- // should not wait for a download removal notification.
- if (minutesSinceMidnight > 250) {
- downloadPromise = promiseDownloadRemoved(publicList);
- } else {
- downloadPromise = Promise.resolve();
- }
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Clear Today
- Sanitizer.prefs.setIntPref("timeSpan", 4);
- yield s.sanitize();
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- // Be careful. If we add our objectss just before midnight, and sanitize
- // runs immediately after, they won't be expired. This is expected, but
- // we should not test in that case. We cannot just test for opposite
- // condition because we could cross midnight just one moment after we
- // cache our time, then we would have an even worse random failure.
- var today = isToday(new Date(now_mSec));
- if (today) {
- ok(!(yield promiseIsURIVisited(makeURI("http://today.com"))),
- "Pretend visit to today.com should now be deleted");
-
- yield countEntries("today", "today form entry should be deleted", checkZero);
- ok(!(yield downloadExists(publicList, "fakefile-today")), "'Today' download should now be deleted");
- }
-
- ok((yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should still exist");
- yield countEntries("b4today", "b4today form entry should still exist", checkOne);
- ok((yield downloadExists(publicList, "fakefile-old")), "Year old download should still be present");
-
- downloadPromise = promiseDownloadRemoved(publicList);
- formHistoryPromise = promiseFormHistoryRemoved();
-
- // Choose everything
- Sanitizer.prefs.setIntPref("timeSpan", 0);
- yield s.sanitize();
-
- yield formHistoryPromise;
- yield downloadPromise;
-
- ok(!(yield promiseIsURIVisited(makeURI("http://before-today.com"))),
- "Pretend visit to before-today.com should now be deleted");
-
- yield countEntries("b4today", "b4today form entry should be deleted", checkZero);
-
- ok(!(yield downloadExists(publicList, "fakefile-old")), "Year old download should now be deleted");
-}
-
-function setupHistory() {
- let deferred = Promise.defer();
-
- let places = [];
-
- function addPlace(aURI, aTitle, aVisitDate) {
- places.push({
- uri: aURI,
- title: aTitle,
- visits: [{
- visitDate: aVisitDate,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK
- }]
- });
- }
-
- addPlace(makeURI("http://10minutes.com/"), "10 minutes ago", now_uSec - 10 * kUsecPerMin);
- addPlace(makeURI("http://1hour.com/"), "Less than 1 hour ago", now_uSec - 45 * kUsecPerMin);
- addPlace(makeURI("http://1hour10minutes.com/"), "1 hour 10 minutes ago", now_uSec - 70 * kUsecPerMin);
- addPlace(makeURI("http://2hour.com/"), "Less than 2 hours ago", now_uSec - 90 * kUsecPerMin);
- addPlace(makeURI("http://2hour10minutes.com/"), "2 hours 10 minutes ago", now_uSec - 130 * kUsecPerMin);
- addPlace(makeURI("http://4hour.com/"), "Less than 4 hours ago", now_uSec - 180 * kUsecPerMin);
- addPlace(makeURI("http://4hour10minutes.com/"), "4 hours 10 minutesago", now_uSec - 250 * kUsecPerMin);
-
- let today = new Date();
- today.setHours(0);
- today.setMinutes(0);
- today.setSeconds(1);
- addPlace(makeURI("http://today.com/"), "Today", today.getTime() * 1000);
-
- let lastYear = new Date();
- lastYear.setFullYear(lastYear.getFullYear() - 1);
- addPlace(makeURI("http://before-today.com/"), "Before Today", lastYear.getTime() * 1000);
- PlacesUtils.asyncHistory.updatePlaces(places, {
- handleError: () => ok(false, "Unexpected error in adding visit."),
- handleResult: () => { },
- handleCompletion: () => deferred.resolve()
- });
-
- return deferred.promise;
-}
-
-function* setupFormHistory() {
-
- function searchEntries(terms, params) {
- let deferred = Promise.defer();
-
- let results = [];
- FormHistory.search(terms, params, { handleResult: result => results.push(result),
- handleError: function (error) {
- deferred.reject(error);
- throw new Error("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) { deferred.resolve(results); }
- });
- return deferred.promise;
- }
-
- function update(changes)
- {
- let deferred = Promise.defer();
- FormHistory.update(changes, { handleError: function (error) {
- deferred.reject(error);
- throw new Error("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) { deferred.resolve(); }
- });
- return deferred.promise;
- }
-
- // Make sure we've got a clean DB to start with, then add the entries we'll be testing.
- yield update(
- [{
- op: "remove"
- },
- {
- op : "add",
- fieldname : "10minutes",
- value : "10m"
- }, {
- op : "add",
- fieldname : "1hour",
- value : "1h"
- }, {
- op : "add",
- fieldname : "1hour10minutes",
- value : "1h10m"
- }, {
- op : "add",
- fieldname : "2hour",
- value : "2h"
- }, {
- op : "add",
- fieldname : "2hour10minutes",
- value : "2h10m"
- }, {
- op : "add",
- fieldname : "4hour",
- value : "4h"
- }, {
- op : "add",
- fieldname : "4hour10minutes",
- value : "4h10m"
- }, {
- op : "add",
- fieldname : "today",
- value : "1d"
- }, {
- op : "add",
- fieldname : "b4today",
- value : "1y"
- }]);
-
- // Artifically age the entries to the proper vintage.
- let timestamp = now_uSec - 10 * kUsecPerMin;
- let results = yield searchEntries(["guid"], { fieldname: "10minutes" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 45 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "1hour" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 70 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "1hour10minutes" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 90 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "2hour" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 130 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "2hour10minutes" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 180 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "4hour" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- timestamp = now_uSec - 250 * kUsecPerMin;
- results = yield searchEntries(["guid"], { fieldname: "4hour10minutes" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- let today = new Date();
- today.setHours(0);
- today.setMinutes(0);
- today.setSeconds(1);
- timestamp = today.getTime() * 1000;
- results = yield searchEntries(["guid"], { fieldname: "today" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- let lastYear = new Date();
- lastYear.setFullYear(lastYear.getFullYear() - 1);
- timestamp = lastYear.getTime() * 1000;
- results = yield searchEntries(["guid"], { fieldname: "b4today" });
- yield update({ op: "update", firstUsed: timestamp, guid: results[0].guid });
-
- var checks = 0;
- let checkOne = function(num, message) { is(num, 1, message); checks++; }
-
- // Sanity check.
- yield countEntries("10minutes", "Checking for 10minutes form history entry creation", checkOne);
- yield countEntries("1hour", "Checking for 1hour form history entry creation", checkOne);
- yield countEntries("1hour10minutes", "Checking for 1hour10minutes form history entry creation", checkOne);
- yield countEntries("2hour", "Checking for 2hour form history entry creation", checkOne);
- yield countEntries("2hour10minutes", "Checking for 2hour10minutes form history entry creation", checkOne);
- yield countEntries("4hour", "Checking for 4hour form history entry creation", checkOne);
- yield countEntries("4hour10minutes", "Checking for 4hour10minutes form history entry creation", checkOne);
- yield countEntries("today", "Checking for today form history entry creation", checkOne);
- yield countEntries("b4today", "Checking for b4today form history entry creation", checkOne);
- is(checks, 9, "9 checks made");
-}
-
-function* setupDownloads() {
-
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
-
- let download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
- target: "fakefile-10-minutes"
- });
- download.startTime = new Date(now_mSec - 10 * kMsecPerMin), // 10 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=453440",
- target: "fakefile-1-hour"
- });
- download.startTime = new Date(now_mSec - 45 * kMsecPerMin), // 45 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
- target: "fakefile-1-hour-10-minutes"
- });
- download.startTime = new Date(now_mSec - 70 * kMsecPerMin), // 70 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=453440",
- target: "fakefile-2-hour"
- });
- download.startTime = new Date(now_mSec - 90 * kMsecPerMin), // 90 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
- target: "fakefile-2-hour-10-minutes"
- });
- download.startTime = new Date(now_mSec - 130 * kMsecPerMin), // 130 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=453440",
- target: "fakefile-4-hour"
- });
- download.startTime = new Date(now_mSec - 180 * kMsecPerMin), // 180 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
- target: "fakefile-4-hour-10-minutes"
- });
- download.startTime = new Date(now_mSec - 250 * kMsecPerMin), // 250 minutes ago
- download.canceled = true;
- yield publicList.add(download);
-
- // Add "today" download
- let today = new Date();
- today.setHours(0);
- today.setMinutes(0);
- today.setSeconds(1);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=453440",
- target: "fakefile-today"
- });
- download.startTime = today, // 12:00:01 AM this morning
- download.canceled = true;
- yield publicList.add(download);
-
- // Add "before today" download
- let lastYear = new Date();
- lastYear.setFullYear(lastYear.getFullYear() - 1);
-
- download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=453440",
- target: "fakefile-old"
- });
- download.startTime = lastYear,
- download.canceled = true;
- yield publicList.add(download);
-
- // Confirm everything worked
- let downloads = yield publicList.getAll();
- is(downloads.length, 9, "9 Pretend downloads added");
-
- ok((yield downloadExists(publicList, "fakefile-old")), "Pretend download for everything case should exist");
- ok((yield downloadExists(publicList, "fakefile-10-minutes")), "Pretend download for 10-minutes case should exist");
- ok((yield downloadExists(publicList, "fakefile-1-hour")), "Pretend download for 1-hour case should exist");
- ok((yield downloadExists(publicList, "fakefile-1-hour-10-minutes")), "Pretend download for 1-hour-10-minutes case should exist");
- ok((yield downloadExists(publicList, "fakefile-2-hour")), "Pretend download for 2-hour case should exist");
- ok((yield downloadExists(publicList, "fakefile-2-hour-10-minutes")), "Pretend download for 2-hour-10-minutes case should exist");
- ok((yield downloadExists(publicList, "fakefile-4-hour")), "Pretend download for 4-hour case should exist");
- ok((yield downloadExists(publicList, "fakefile-4-hour-10-minutes")), "Pretend download for 4-hour-10-minutes case should exist");
- ok((yield downloadExists(publicList, "fakefile-today")), "Pretend download for Today case should exist");
-}
-
-/**
- * Checks to see if the downloads with the specified id exists.
- *
- * @param aID
- * The ids of the downloads to check.
- */
-let downloadExists = Task.async(function* (list, path) {
- let listArray = yield list.getAll();
- return listArray.some(i => i.target.path == path);
-});
-
-function isToday(aDate) {
- return aDate.getDate() == new Date().getDate();
-}
diff --git a/browser/base/content/test/general/browser_sanitizeDialog.js b/browser/base/content/test/general/browser_sanitizeDialog.js
deleted file mode 100644
index 50546be45..000000000
--- a/browser/base/content/test/general/browser_sanitizeDialog.js
+++ /dev/null
@@ -1,1027 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests the sanitize dialog (a.k.a. the clear recent history dialog).
- * See bug 480169.
- *
- * The purpose of this test is not to fully flex the sanitize timespan code;
- * browser/base/content/test/general/browser_sanitize-timespans.js does that. This
- * test checks the UI of the dialog and makes sure it's correctly connected to
- * the sanitize timespan code.
- *
- * Some of this code, especially the history creation parts, was taken from
- * browser/base/content/test/general/browser_sanitize-timespans.js.
- */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-var {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
-
-XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
- "resource://gre/modules/FormHistory.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
- "resource://gre/modules/Downloads.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Timer",
- "resource://gre/modules/Timer.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-var tempScope = {};
-Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", tempScope);
-var Sanitizer = tempScope.Sanitizer;
-
-const kMsecPerMin = 60 * 1000;
-const kUsecPerMin = 60 * 1000000;
-
-add_task(function* init() {
- requestLongerTimeout(3);
- yield blankSlate();
- registerCleanupFunction(function* () {
- yield blankSlate();
- yield PlacesTestUtils.promiseAsyncUpdates();
- });
-});
-
-/**
- * Initializes the dialog to its default state.
- */
-add_task(function* default_state() {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Select "Last Hour"
- this.selectDuration(Sanitizer.TIMESPAN_HOUR);
- // Hide details
- if (!this.getItemList().collapsed)
- this.toggleDetails();
- this.acceptDialog();
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * Cancels the dialog, makes sure history not cleared.
- */
-add_task(function* test_cancel() {
- // Add history (within the past hour)
- let uris = [];
- let places = [];
- let pURI;
- for (let i = 0; i < 30; i++) {
- pURI = makeURI("http://" + i + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(i)});
- uris.push(pURI);
- }
- yield PlacesTestUtils.addVisits(places);
-
- let wh = new WindowHelper();
- wh.onload = function () {
- this.selectDuration(Sanitizer.TIMESPAN_HOUR);
- this.checkPrefCheckbox("history", false);
- this.checkDetails(false);
-
- // Show details
- this.toggleDetails();
- this.checkDetails(true);
-
- // Hide details
- this.toggleDetails();
- this.checkDetails(false);
- this.cancelDialog();
- };
- wh.onunload = function* () {
- yield promiseHistoryClearedState(uris, false);
- yield blankSlate();
- yield promiseHistoryClearedState(uris, true);
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * Ensures that the combined history-downloads checkbox clears both history
- * visits and downloads when checked; the dialog respects simple timespan.
- */
-add_task(function* test_history_downloads_checked() {
- // Add downloads (within the past hour).
- let downloadIDs = [];
- for (let i = 0; i < 5; i++) {
- yield addDownloadWithMinutesAgo(downloadIDs, i);
- }
- // Add downloads (over an hour ago).
- let olderDownloadIDs = [];
- for (let i = 0; i < 5; i++) {
- yield addDownloadWithMinutesAgo(olderDownloadIDs, 61 + i);
- }
-
- // Add history (within the past hour).
- let uris = [];
- let places = [];
- let pURI;
- for (let i = 0; i < 30; i++) {
- pURI = makeURI("http://" + i + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(i)});
- uris.push(pURI);
- }
- // Add history (over an hour ago).
- let olderURIs = [];
- for (let i = 0; i < 5; i++) {
- pURI = makeURI("http://" + (61 + i) + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(61 + i)});
- olderURIs.push(pURI);
- }
- let promiseSanitized = promiseSanitizationComplete();
-
- yield PlacesTestUtils.addVisits(places);
-
- let wh = new WindowHelper();
- wh.onload = function () {
- this.selectDuration(Sanitizer.TIMESPAN_HOUR);
- this.checkPrefCheckbox("history", true);
- this.acceptDialog();
- };
- wh.onunload = function* () {
- intPrefIs("sanitize.timeSpan", Sanitizer.TIMESPAN_HOUR,
- "timeSpan pref should be hour after accepting dialog with " +
- "hour selected");
- boolPrefIs("cpd.history", true,
- "history pref should be true after accepting dialog with " +
- "history checkbox checked");
- boolPrefIs("cpd.downloads", true,
- "downloads pref should be true after accepting dialog with " +
- "history checkbox checked");
-
- yield promiseSanitized;
-
- // History visits and downloads within one hour should be cleared.
- yield promiseHistoryClearedState(uris, true);
- yield ensureDownloadsClearedState(downloadIDs, true);
-
- // Visits and downloads > 1 hour should still exist.
- yield promiseHistoryClearedState(olderURIs, false);
- yield ensureDownloadsClearedState(olderDownloadIDs, false);
-
- // OK, done, cleanup after ourselves.
- yield blankSlate();
- yield promiseHistoryClearedState(olderURIs, true);
- yield ensureDownloadsClearedState(olderDownloadIDs, true);
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * Ensures that the combined history-downloads checkbox removes neither
- * history visits nor downloads when not checked.
- */
-add_task(function* test_history_downloads_unchecked() {
- // Add form entries
- let formEntries = [];
-
- for (let i = 0; i < 5; i++) {
- formEntries.push((yield promiseAddFormEntryWithMinutesAgo(i)));
- }
-
-
- // Add downloads (within the past hour).
- let downloadIDs = [];
- for (let i = 0; i < 5; i++) {
- yield addDownloadWithMinutesAgo(downloadIDs, i);
- }
-
- // Add history, downloads, form entries (within the past hour).
- let uris = [];
- let places = [];
- let pURI;
- for (let i = 0; i < 5; i++) {
- pURI = makeURI("http://" + i + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(i)});
- uris.push(pURI);
- }
-
- yield PlacesTestUtils.addVisits(places);
- let wh = new WindowHelper();
- wh.onload = function () {
- is(this.isWarningPanelVisible(), false,
- "Warning panel should be hidden after previously accepting dialog " +
- "with a predefined timespan");
- this.selectDuration(Sanitizer.TIMESPAN_HOUR);
-
- // Remove only form entries, leave history (including downloads).
- this.checkPrefCheckbox("history", false);
- this.checkPrefCheckbox("formdata", true);
- this.acceptDialog();
- };
- wh.onunload = function* () {
- intPrefIs("sanitize.timeSpan", Sanitizer.TIMESPAN_HOUR,
- "timeSpan pref should be hour after accepting dialog with " +
- "hour selected");
- boolPrefIs("cpd.history", false,
- "history pref should be false after accepting dialog with " +
- "history checkbox unchecked");
- boolPrefIs("cpd.downloads", false,
- "downloads pref should be false after accepting dialog with " +
- "history checkbox unchecked");
-
- // Of the three only form entries should be cleared.
- yield promiseHistoryClearedState(uris, false);
- yield ensureDownloadsClearedState(downloadIDs, false);
-
- for (let entry of formEntries) {
- let exists = yield formNameExists(entry);
- is(exists, false, "form entry " + entry + " should no longer exist");
- }
-
- // OK, done, cleanup after ourselves.
- yield blankSlate();
- yield promiseHistoryClearedState(uris, true);
- yield ensureDownloadsClearedState(downloadIDs, true);
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * Ensures that the "Everything" duration option works.
- */
-add_task(function* test_everything() {
- // Add history.
- let uris = [];
- let places = [];
- let pURI;
- // within past hour, within past two hours, within past four hours and
- // outside past four hours
- [10, 70, 130, 250].forEach(function(aValue) {
- pURI = makeURI("http://" + aValue + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(aValue)});
- uris.push(pURI);
- });
-
- let promiseSanitized = promiseSanitizationComplete();
-
- yield PlacesTestUtils.addVisits(places);
- let wh = new WindowHelper();
- wh.onload = function () {
- is(this.isWarningPanelVisible(), false,
- "Warning panel should be hidden after previously accepting dialog " +
- "with a predefined timespan");
- this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
- this.checkPrefCheckbox("history", true);
- this.checkDetails(true);
-
- // Hide details
- this.toggleDetails();
- this.checkDetails(false);
-
- // Show details
- this.toggleDetails();
- this.checkDetails(true);
-
- this.acceptDialog();
- };
- wh.onunload = function* () {
- yield promiseSanitized;
- intPrefIs("sanitize.timeSpan", Sanitizer.TIMESPAN_EVERYTHING,
- "timeSpan pref should be everything after accepting dialog " +
- "with everything selected");
-
- yield promiseHistoryClearedState(uris, true);
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * Ensures that the "Everything" warning is visible on dialog open after
- * the previous test.
- */
-add_task(function* test_everything_warning() {
- // Add history.
- let uris = [];
- let places = [];
- let pURI;
- // within past hour, within past two hours, within past four hours and
- // outside past four hours
- [10, 70, 130, 250].forEach(function(aValue) {
- pURI = makeURI("http://" + aValue + "-minutes-ago.com/");
- places.push({uri: pURI, visitDate: visitTimeForMinutesAgo(aValue)});
- uris.push(pURI);
- });
-
- let promiseSanitized = promiseSanitizationComplete();
-
- yield PlacesTestUtils.addVisits(places);
- let wh = new WindowHelper();
- wh.onload = function () {
- is(this.isWarningPanelVisible(), true,
- "Warning panel should be visible after previously accepting dialog " +
- "with clearing everything");
- this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
- this.checkPrefCheckbox("history", true);
- this.acceptDialog();
- };
- wh.onunload = function* () {
- intPrefIs("sanitize.timeSpan", Sanitizer.TIMESPAN_EVERYTHING,
- "timeSpan pref should be everything after accepting dialog " +
- "with everything selected");
-
- yield promiseSanitized;
-
- yield promiseHistoryClearedState(uris, true);
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-/**
- * The next three tests checks that when a certain history item cannot be
- * cleared then the checkbox should be both disabled and unchecked.
- * In addition, we ensure that this behavior does not modify the preferences.
- */
-add_task(function* test_cannot_clear_history() {
- // Add form entries
- let formEntries = [ (yield promiseAddFormEntryWithMinutesAgo(10)) ];
-
- let promiseSanitized = promiseSanitizationComplete();
-
- // Add history.
- let pURI = makeURI("http://" + 10 + "-minutes-ago.com/");
- yield PlacesTestUtils.addVisits({uri: pURI, visitDate: visitTimeForMinutesAgo(10)});
- let uris = [ pURI ];
-
- let wh = new WindowHelper();
- wh.onload = function() {
- // Check that the relevant checkboxes are enabled
- var cb = this.win.document.querySelectorAll(
- "#itemList > [preference='privacy.cpd.formdata']");
- ok(cb.length == 1 && !cb[0].disabled, "There is formdata, checkbox to " +
- "clear formdata should be enabled.");
-
- cb = this.win.document.querySelectorAll(
- "#itemList > [preference='privacy.cpd.history']");
- ok(cb.length == 1 && !cb[0].disabled, "There is history, checkbox to " +
- "clear history should be enabled.");
-
- this.checkAllCheckboxes();
- this.acceptDialog();
- };
- wh.onunload = function* () {
- yield promiseSanitized;
-
- yield promiseHistoryClearedState(uris, true);
-
- let exists = yield formNameExists(formEntries[0]);
- is(exists, false, "form entry " + formEntries[0] + " should no longer exist");
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-add_task(function* test_no_formdata_history_to_clear() {
- let promiseSanitized = promiseSanitizationComplete();
- let wh = new WindowHelper();
- wh.onload = function() {
- boolPrefIs("cpd.history", true,
- "history pref should be true after accepting dialog with " +
- "history checkbox checked");
- boolPrefIs("cpd.formdata", true,
- "formdata pref should be true after accepting dialog with " +
- "formdata checkbox checked");
-
- var cb = this.win.document.querySelectorAll(
- "#itemList > [preference='privacy.cpd.history']");
- ok(cb.length == 1 && !cb[0].disabled && cb[0].checked,
- "There is no history, but history checkbox should always be enabled " +
- "and will be checked from previous preference.");
-
- this.acceptDialog();
- }
- wh.open();
- yield wh.promiseClosed;
- yield promiseSanitized;
-});
-
-add_task(function* test_form_entries() {
- let formEntry = (yield promiseAddFormEntryWithMinutesAgo(10));
-
- let promiseSanitized = promiseSanitizationComplete();
-
- let wh = new WindowHelper();
- wh.onload = function() {
- boolPrefIs("cpd.formdata", true,
- "formdata pref should persist previous value after accepting " +
- "dialog where you could not clear formdata.");
-
- var cb = this.win.document.querySelectorAll(
- "#itemList > [preference='privacy.cpd.formdata']");
-
- info("There exists formEntries so the checkbox should be in sync with the pref.");
- is(cb.length, 1, "There is only one checkbox for form data");
- ok(!cb[0].disabled, "The checkbox is enabled");
- ok(cb[0].checked, "The checkbox is checked");
-
- this.acceptDialog();
- };
- wh.onunload = function* () {
- yield promiseSanitized;
- let exists = yield formNameExists(formEntry);
- is(exists, false, "form entry " + formEntry + " should no longer exist");
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-
-/**
- * Ensure that toggling details persists
- * across dialog openings.
- */
-add_task(function* test_toggling_details_persists() {
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Check all items and select "Everything"
- this.checkAllCheckboxes();
- this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
-
- // Hide details
- this.toggleDetails();
- this.checkDetails(false);
- this.acceptDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should remain closed because all items are checked.
- this.checkDetails(false);
-
- // Uncheck history.
- this.checkPrefCheckbox("history", false);
- this.acceptDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should be open because not all items are checked.
- this.checkDetails(true);
-
- // Modify the Site Preferences item state (bug 527820)
- this.checkAllCheckboxes();
- this.checkPrefCheckbox("siteSettings", false);
- this.acceptDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should be open because not all items are checked.
- this.checkDetails(true);
-
- // Hide details
- this.toggleDetails();
- this.checkDetails(false);
- this.cancelDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should be open because not all items are checked.
- this.checkDetails(true);
-
- // Select another duration
- this.selectDuration(Sanitizer.TIMESPAN_HOUR);
- // Hide details
- this.toggleDetails();
- this.checkDetails(false);
- this.acceptDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should not be open because "Last Hour" is selected
- this.checkDetails(false);
-
- this.cancelDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
- {
- let wh = new WindowHelper();
- wh.onload = function () {
- // Details should have remained closed
- this.checkDetails(false);
-
- // Show details
- this.toggleDetails();
- this.checkDetails(true);
- this.cancelDialog();
- };
- wh.open();
- yield wh.promiseClosed;
- }
-});
-
-// Test for offline cache deletion
-add_task(function* test_offline_cache() {
- // Prepare stuff, we will work with www.example.com
- var URL = "http://www.example.com";
- var URI = makeURI(URL);
- var principal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(URI);
-
- // Give www.example.com privileges to store offline data
- Services.perms.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
- Services.perms.addFromPrincipal(principal, "offline-app", Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
-
- // Store something to the offline cache
- var appcacheserv = Cc["@mozilla.org/network/application-cache-service;1"]
- .getService(Ci.nsIApplicationCacheService);
- var appcachegroupid = appcacheserv.buildGroupIDForInfo(makeURI(URL + "/manifest"), LoadContextInfo.default);
- var appcache = appcacheserv.createApplicationCache(appcachegroupid);
- var storage = Services.cache2.appCacheStorage(LoadContextInfo.default, appcache);
-
- // Open the dialog
- let wh = new WindowHelper();
- wh.onload = function () {
- this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
- // Show details
- this.toggleDetails();
- // Clear only offlineApps
- this.uncheckAllCheckboxes();
- this.checkPrefCheckbox("offlineApps", true);
- this.acceptDialog();
- };
- wh.onunload = function () {
- // Check if the cache has been deleted
- var size = -1;
- var visitor = {
- onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
- {
- size = aConsumption;
- }
- };
- storage.asyncVisitStorage(visitor, false);
- // Offline cache visit happens synchronously, since it's forwarded to the old code
- is(size, 0, "offline application cache entries evicted");
- };
-
- var cacheListener = {
- onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
- onCacheEntryAvailable: function (entry, isnew, unused, status) {
- is(status, Cr.NS_OK);
- var stream = entry.openOutputStream(0);
- var content = "content";
- stream.write(content, content.length);
- stream.close();
- entry.close();
- wh.open();
- }
- };
-
- storage.asyncOpenURI(makeURI(URL), "", Ci.nsICacheStorage.OPEN_TRUNCATE, cacheListener);
- yield wh.promiseClosed;
-});
-
-// Test for offline apps permission deletion
-add_task(function* test_offline_apps_permissions() {
- // Prepare stuff, we will work with www.example.com
- var URL = "http://www.example.com";
- var URI = makeURI(URL);
- var principal = Services.scriptSecurityManager.createCodebasePrincipal(URI, {});
-
- let promiseSanitized = promiseSanitizationComplete();
-
- // Open the dialog
- let wh = new WindowHelper();
- wh.onload = function () {
- this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
- // Show details
- this.toggleDetails();
- // Clear only offlineApps
- this.uncheckAllCheckboxes();
- this.checkPrefCheckbox("siteSettings", true);
- this.acceptDialog();
- };
- wh.onunload = function* () {
- yield promiseSanitized;
-
- // Check all has been deleted (privileges, data, cache)
- is(Services.perms.testPermissionFromPrincipal(principal, "offline-app"), 0, "offline-app permissions removed");
- };
- wh.open();
- yield wh.promiseClosed;
-});
-
-var now_mSec = Date.now();
-var now_uSec = now_mSec * 1000;
-
-/**
- * This wraps the dialog and provides some convenience methods for interacting
- * with it.
- *
- * @param aWin
- * The dialog's nsIDOMWindow
- */
-function WindowHelper(aWin) {
- this.win = aWin;
- this.promiseClosed = new Promise(resolve => { this._resolveClosed = resolve });
-}
-
-WindowHelper.prototype = {
- /**
- * "Presses" the dialog's OK button.
- */
- acceptDialog: function () {
- is(this.win.document.documentElement.getButton("accept").disabled, false,
- "Dialog's OK button should not be disabled");
- this.win.document.documentElement.acceptDialog();
- },
-
- /**
- * "Presses" the dialog's Cancel button.
- */
- cancelDialog: function () {
- this.win.document.documentElement.cancelDialog();
- },
-
- /**
- * Ensures that the details progressive disclosure button and the item list
- * hidden by it match up. Also makes sure the height of the dialog is
- * sufficient for the item list and warning panel.
- *
- * @param aShouldBeShown
- * True if you expect the details to be shown and false if hidden
- */
- checkDetails: function (aShouldBeShown) {
- let button = this.getDetailsButton();
- let list = this.getItemList();
- let hidden = list.hidden || list.collapsed;
- is(hidden, !aShouldBeShown,
- "Details should be " + (aShouldBeShown ? "shown" : "hidden") +
- " but were actually " + (hidden ? "hidden" : "shown"));
- let dir = hidden ? "down" : "up";
- is(button.className, "expander-" + dir,
- "Details button should be " + dir + " because item list is " +
- (hidden ? "" : "not ") + "hidden");
- let height = 0;
- if (!hidden) {
- ok(list.boxObject.height > 30, "listbox has sufficient size")
- height += list.boxObject.height;
- }
- if (this.isWarningPanelVisible())
- height += this.getWarningPanel().boxObject.height;
- ok(height < this.win.innerHeight,
- "Window should be tall enough to fit warning panel and item list");
- },
-
- /**
- * (Un)checks a history scope checkbox (browser & download history,
- * form history, etc.).
- *
- * @param aPrefName
- * The final portion of the checkbox's privacy.cpd.* preference name
- * @param aCheckState
- * True if the checkbox should be checked, false otherwise
- */
- checkPrefCheckbox: function (aPrefName, aCheckState) {
- var pref = "privacy.cpd." + aPrefName;
- var cb = this.win.document.querySelectorAll(
- "#itemList > [preference='" + pref + "']");
- is(cb.length, 1, "found checkbox for " + pref + " preference");
- if (cb[0].checked != aCheckState)
- cb[0].click();
- },
-
- /**
- * Makes sure all the checkboxes are checked.
- */
- _checkAllCheckboxesCustom: function (check) {
- var cb = this.win.document.querySelectorAll("#itemList > [preference]");
- ok(cb.length > 1, "found checkboxes for preferences");
- for (var i = 0; i < cb.length; ++i) {
- var pref = this.win.document.getElementById(cb[i].getAttribute("preference"));
- if (!!pref.value ^ check)
- cb[i].click();
- }
- },
-
- checkAllCheckboxes: function () {
- this._checkAllCheckboxesCustom(true);
- },
-
- uncheckAllCheckboxes: function () {
- this._checkAllCheckboxesCustom(false);
- },
-
- /**
- * @return The details progressive disclosure button
- */
- getDetailsButton: function () {
- return this.win.document.getElementById("detailsExpander");
- },
-
- /**
- * @return The dialog's duration dropdown
- */
- getDurationDropdown: function () {
- return this.win.document.getElementById("sanitizeDurationChoice");
- },
-
- /**
- * @return The item list hidden by the details progressive disclosure button
- */
- getItemList: function () {
- return this.win.document.getElementById("itemList");
- },
-
- /**
- * @return The clear-everything warning box
- */
- getWarningPanel: function () {
- return this.win.document.getElementById("sanitizeEverythingWarningBox");
- },
-
- /**
- * @return True if the "Everything" warning panel is visible (as opposed to
- * the tree)
- */
- isWarningPanelVisible: function () {
- return !this.getWarningPanel().hidden;
- },
-
- /**
- * Opens the clear recent history dialog. Before calling this, set
- * this.onload to a function to execute onload. It should close the dialog
- * when done so that the tests may continue. Set this.onunload to a function
- * to execute onunload. this.onunload is optional. If it returns true, the
- * caller is expected to call waitForAsyncUpdates at some point; if false is
- * returned, waitForAsyncUpdates is called automatically.
- */
- open: function () {
- let wh = this;
-
- function windowObserver(aSubject, aTopic, aData) {
- if (aTopic != "domwindowopened")
- return;
-
- Services.ww.unregisterNotification(windowObserver);
-
- var loaded = false;
- let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
-
- win.addEventListener("load", function onload(event) {
- win.removeEventListener("load", onload, false);
-
- if (win.name !== "SanitizeDialog")
- return;
-
- wh.win = win;
- loaded = true;
- executeSoon(() => wh.onload());
- }, false);
-
- win.addEventListener("unload", function onunload(event) {
- if (win.name !== "SanitizeDialog") {
- win.removeEventListener("unload", onunload, false);
- return;
- }
-
- // Why is unload fired before load?
- if (!loaded)
- return;
-
- win.removeEventListener("unload", onunload, false);
- wh.win = win;
-
- // Some exceptions that reach here don't reach the test harness, but
- // ok()/is() do...
- Task.spawn(function* () {
- if (wh.onunload) {
- yield wh.onunload();
- }
- yield PlacesTestUtils.promiseAsyncUpdates();
- wh._resolveClosed();
- });
- }, false);
- }
- Services.ww.registerNotification(windowObserver);
- Services.ww.openWindow(null,
- "chrome://browser/content/sanitize.xul",
- "SanitizeDialog",
- "chrome,titlebar,dialog,centerscreen,modal",
- null);
- },
-
- /**
- * Selects a duration in the duration dropdown.
- *
- * @param aDurVal
- * One of the Sanitizer.TIMESPAN_* values
- */
- selectDuration: function (aDurVal) {
- this.getDurationDropdown().value = aDurVal;
- if (aDurVal === Sanitizer.TIMESPAN_EVERYTHING) {
- is(this.isWarningPanelVisible(), true,
- "Warning panel should be visible for TIMESPAN_EVERYTHING");
- }
- else {
- is(this.isWarningPanelVisible(), false,
- "Warning panel should not be visible for non-TIMESPAN_EVERYTHING");
- }
- },
-
- /**
- * Toggles the details progressive disclosure button.
- */
- toggleDetails: function () {
- this.getDetailsButton().click();
- }
-};
-
-function promiseSanitizationComplete() {
- return promiseTopicObserved("sanitizer-sanitization-complete");
-}
-
-/**
- * Adds a download to history.
- *
- * @param aMinutesAgo
- * The download will be downloaded this many minutes ago
- */
-function* addDownloadWithMinutesAgo(aExpectedPathList, aMinutesAgo) {
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
-
- let name = "fakefile-" + aMinutesAgo + "-minutes-ago";
- let download = yield Downloads.createDownload({
- source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
- target: name
- });
- download.startTime = new Date(now_mSec - (aMinutesAgo * kMsecPerMin));
- download.canceled = true;
- publicList.add(download);
-
- ok((yield downloadExists(name)),
- "Sanity check: download " + name +
- " should exist after creating it");
-
- aExpectedPathList.push(name);
-}
-
-/**
- * Adds a form entry to history.
- *
- * @param aMinutesAgo
- * The entry will be added this many minutes ago
- */
-function promiseAddFormEntryWithMinutesAgo(aMinutesAgo) {
- let name = aMinutesAgo + "-minutes-ago";
-
- // Artifically age the entry to the proper vintage.
- let timestamp = now_uSec - (aMinutesAgo * kUsecPerMin);
-
- return new Promise((resolve, reject) =>
- FormHistory.update({ op: "add", fieldname: name, value: "dummy", firstUsed: timestamp },
- { handleError: function (error) {
- reject();
- throw new Error("Error occurred updating form history: " + error);
- },
- handleCompletion: function (reason) {
- resolve(name);
- }
- })
- )
-}
-
-/**
- * Checks if a form entry exists.
- */
-function formNameExists(name)
-{
- return new Promise((resolve, reject) => {
- let count = 0;
- FormHistory.count({ fieldname: name },
- { handleResult: result => count = result,
- handleError: function (error) {
- reject(error);
- throw new Error("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) {
- if (!reason) {
- resolve(count);
- }
- }
- });
- });
-}
-
-/**
- * Removes all history visits, downloads, and form entries.
- */
-function* blankSlate() {
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
- let downloads = yield publicList.getAll();
- for (let download of downloads) {
- yield publicList.remove(download);
- yield download.finalize(true);
- }
-
- yield new Promise((resolve, reject) => {
- FormHistory.update({op: "remove"}, {
- handleCompletion(reason) {
- if (!reason) {
- resolve();
- }
- },
- handleError(error) {
- reject(error);
- throw new Error("Error occurred updating form history: " + error);
- }
- });
- });
-
- yield PlacesTestUtils.clearHistory();
-}
-
-/**
- * Ensures that the given pref is the expected value.
- *
- * @param aPrefName
- * The pref's sub-branch under the privacy branch
- * @param aExpectedVal
- * The pref's expected value
- * @param aMsg
- * Passed to is()
- */
-function boolPrefIs(aPrefName, aExpectedVal, aMsg) {
- is(gPrefService.getBoolPref("privacy." + aPrefName), aExpectedVal, aMsg);
-}
-
-/**
- * Checks to see if the download with the specified path exists.
- *
- * @param aPath
- * The path of the download to check
- * @return True if the download exists, false otherwise
- */
-function* downloadExists(aPath) {
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
- let listArray = yield publicList.getAll();
- return listArray.some(i => i.target.path == aPath);
-}
-
-/**
- * Ensures that the specified downloads are either cleared or not.
- *
- * @param aDownloadIDs
- * Array of download database IDs
- * @param aShouldBeCleared
- * True if each download should be cleared, false otherwise
- */
-function* ensureDownloadsClearedState(aDownloadIDs, aShouldBeCleared) {
- let niceStr = aShouldBeCleared ? "no longer" : "still";
- for (let id of aDownloadIDs) {
- is((yield downloadExists(id)), !aShouldBeCleared,
- "download " + id + " should " + niceStr + " exist");
- }
-}
-
-/**
- * Ensures that the given pref is the expected value.
- *
- * @param aPrefName
- * The pref's sub-branch under the privacy branch
- * @param aExpectedVal
- * The pref's expected value
- * @param aMsg
- * Passed to is()
- */
-function intPrefIs(aPrefName, aExpectedVal, aMsg) {
- is(gPrefService.getIntPref("privacy." + aPrefName), aExpectedVal, aMsg);
-}
-
-/**
- * Creates a visit time.
- *
- * @param aMinutesAgo
- * The visit will be visited this many minutes ago
- */
-function visitTimeForMinutesAgo(aMinutesAgo) {
- return now_uSec - aMinutesAgo * kUsecPerMin;
-}
diff --git a/browser/base/content/test/general/browser_save_link-perwindowpb.js b/browser/base/content/test/general/browser_save_link-perwindowpb.js
deleted file mode 100644
index 5c99ba32a..000000000
--- a/browser/base/content/test/general/browser_save_link-perwindowpb.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.init(window);
-
-// Trigger a save of a link in public mode, then trigger an identical save
-// in private mode and ensure that the second request is differentiated from
-// the first by checking that cookies set by the first response are not sent
-// during the second request.
-function triggerSave(aWindow, aCallback) {
- info("started triggerSave");
- var fileName;
- let testBrowser = aWindow.gBrowser.selectedBrowser;
- // This page sets a cookie if and only if a cookie does not exist yet
- let testURI = "http://mochi.test:8888/browser/browser/base/content/test/general/bug792517-2.html";
- testBrowser.loadURI(testURI);
- BrowserTestUtils.browserLoaded(testBrowser, false, testURI)
- .then(() => {
- waitForFocus(function () {
- info("register to handle popupshown");
- aWindow.document.addEventListener("popupshown", contextMenuOpened, false);
-
- BrowserTestUtils.synthesizeMouseAtCenter("#fff", {type: "contextmenu", button: 2}, testBrowser);
- info("right clicked!");
- }, aWindow);
- });
-
- function contextMenuOpened(event) {
- info("contextMenuOpened");
- aWindow.document.removeEventListener("popupshown", contextMenuOpened);
-
- // Create the folder the link will be saved into.
- var destDir = createTemporarySaveDirectory();
- var destFile = destDir.clone();
-
- MockFilePicker.displayDirectory = destDir;
- MockFilePicker.showCallback = function(fp) {
- info("showCallback");
- fileName = fp.defaultString;
- info("fileName: " + fileName);
- destFile.append (fileName);
- MockFilePicker.returnFiles = [destFile];
- MockFilePicker.filterIndex = 1; // kSaveAsType_URL
- info("done showCallback");
- };
-
- mockTransferCallback = function(downloadSuccess) {
- info("mockTransferCallback");
- onTransferComplete(aWindow, downloadSuccess, destDir);
- destDir.remove(true);
- ok(!destDir.exists(), "Destination dir should be removed");
- ok(!destFile.exists(), "Destination file should be removed");
- mockTransferCallback = null;
- info("done mockTransferCallback");
- }
-
- // Select "Save Link As" option from context menu
- var saveLinkCommand = aWindow.document.getElementById("context-savelink");
- info("saveLinkCommand: " + saveLinkCommand);
- saveLinkCommand.doCommand();
-
- event.target.hidePopup();
- info("popup hidden");
- }
-
- function onTransferComplete(aWindow2, downloadSuccess, destDir) {
- ok(downloadSuccess, "Link should have been downloaded successfully");
- aWindow2.close();
-
- executeSoon(() => aCallback());
- }
-}
-
-function test() {
- info("Start the test");
- waitForExplicitFinish();
-
- var gNumSet = 0;
- function testOnWindow(options, callback) {
- info("testOnWindow(" + options + ")");
- var win = OpenBrowserWindow(options);
- info("got " + win);
- whenDelayedStartupFinished(win, () => callback(win));
- }
-
- function whenDelayedStartupFinished(aWindow, aCallback) {
- info("whenDelayedStartupFinished");
- Services.obs.addObserver(function obs(aSubject, aTopic) {
- info("whenDelayedStartupFinished, got topic: " + aTopic + ", got subject: " + aSubject + ", waiting for " + aWindow);
- if (aWindow == aSubject) {
- Services.obs.removeObserver(obs, aTopic);
- executeSoon(aCallback);
- info("whenDelayedStartupFinished found our window");
- }
- }, "browser-delayed-startup-finished", false);
- }
-
- mockTransferRegisterer.register();
-
- registerCleanupFunction(function () {
- info("Running the cleanup code");
- mockTransferRegisterer.unregister();
- MockFilePicker.cleanup();
- Services.obs.removeObserver(observer, "http-on-modify-request");
- Services.obs.removeObserver(observer, "http-on-examine-response");
- info("Finished running the cleanup code");
- });
-
- function observer(subject, topic, state) {
- info("observer called with " + topic);
- if (topic == "http-on-modify-request") {
- onModifyRequest(subject);
- } else if (topic == "http-on-examine-response") {
- onExamineResponse(subject);
- }
- }
-
- function onExamineResponse(subject) {
- let channel = subject.QueryInterface(Ci.nsIHttpChannel);
- info("onExamineResponse with " + channel.URI.spec);
- if (channel.URI.spec != "http://mochi.test:8888/browser/browser/base/content/test/general/bug792517.sjs") {
- info("returning");
- return;
- }
- try {
- let cookies = channel.getResponseHeader("set-cookie");
- // From browser/base/content/test/general/bug792715.sjs, we receive a Set-Cookie
- // header with foopy=1 when there are no cookies for that domain.
- is(cookies, "foopy=1", "Cookie should be foopy=1");
- gNumSet += 1;
- info("gNumSet = " + gNumSet);
- } catch (ex) {
- if (ex.result == Cr.NS_ERROR_NOT_AVAILABLE) {
- info("onExamineResponse caught NOTAVAIL" + ex);
- } else {
- info("ionExamineResponse caught " + ex);
- }
- }
- }
-
- function onModifyRequest(subject) {
- let channel = subject.QueryInterface(Ci.nsIHttpChannel);
- info("onModifyRequest with " + channel.URI.spec);
- if (channel.URI.spec != "http://mochi.test:8888/browser/browser/base/content/test/general/bug792517.sjs") {
- return;
- }
- try {
- let cookies = channel.getRequestHeader("cookie");
- info("cookies: " + cookies);
- // From browser/base/content/test/general/bug792715.sjs, we should never send a
- // cookie because we are making only 2 requests: one in public mode, and
- // one in private mode.
- throw "We should never send a cookie in this test";
- } catch (ex) {
- if (ex.result == Cr.NS_ERROR_NOT_AVAILABLE) {
- info("onModifyRequest caught NOTAVAIL" + ex);
- } else {
- info("ionModifyRequest caught " + ex);
- }
- }
- }
-
- Services.obs.addObserver(observer, "http-on-modify-request", false);
- Services.obs.addObserver(observer, "http-on-examine-response", false);
-
- testOnWindow(undefined, function(win) {
- // The first save from a regular window sets a cookie.
- triggerSave(win, function() {
- is(gNumSet, 1, "1 cookie should be set");
-
- // The second save from a private window also sets a cookie.
- testOnWindow({private: true}, function(win2) {
- triggerSave(win2, function() {
- is(gNumSet, 2, "2 cookies should be set");
- finish();
- });
- });
- });
- });
-}
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
- this);
-
-function createTemporarySaveDirectory() {
- var saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
- saveDir.append("testsavedir");
- if (!saveDir.exists()) {
- info("create testsavedir!");
- saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- }
- info("return from createTempSaveDir: " + saveDir.path);
- return saveDir;
-}
diff --git a/browser/base/content/test/general/browser_save_link_when_window_navigates.js b/browser/base/content/test/general/browser_save_link_when_window_navigates.js
deleted file mode 100644
index 2fd10b00e..000000000
--- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js
+++ /dev/null
@@ -1,173 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.init(window);
-
-const SAVE_PER_SITE_PREF = "browser.download.lastDir.savePerSite";
-const ALWAYS_DOWNLOAD_DIR_PREF = "browser.download.useDownloadDir";
-const UCT_URI = "chrome://mozapps/content/downloads/unknownContentType.xul";
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
- this);
-
-function createTemporarySaveDirectory() {
- var saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
- saveDir.append("testsavedir");
- if (!saveDir.exists()) {
- info("create testsavedir!");
- saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- }
- info("return from createTempSaveDir: " + saveDir.path);
- return saveDir;
-}
-
-function triggerSave(aWindow, aCallback) {
- info("started triggerSave, persite downloads: " + (Services.prefs.getBoolPref(SAVE_PER_SITE_PREF) ? "on" : "off"));
- var fileName;
- let testBrowser = aWindow.gBrowser.selectedBrowser;
- let testURI = "http://mochi.test:8888/browser/browser/base/content/test/general/navigating_window_with_download.html";
- windowObserver.setCallback(onUCTDialog);
- testBrowser.loadURI(testURI);
-
- // Create the folder the link will be saved into.
- var destDir = createTemporarySaveDirectory();
- var destFile = destDir.clone();
-
- MockFilePicker.displayDirectory = destDir;
- MockFilePicker.showCallback = function(fp) {
- info("showCallback");
- fileName = fp.defaultString;
- info("fileName: " + fileName);
- destFile.append (fileName);
- MockFilePicker.returnFiles = [destFile];
- MockFilePicker.filterIndex = 1; // kSaveAsType_URL
- info("done showCallback");
- };
-
- mockTransferCallback = function(downloadSuccess) {
- info("mockTransferCallback");
- onTransferComplete(aWindow, downloadSuccess, destDir);
- destDir.remove(true);
- ok(!destDir.exists(), "Destination dir should be removed");
- ok(!destFile.exists(), "Destination file should be removed");
- mockTransferCallback = null;
- info("done mockTransferCallback");
- }
-
- function onUCTDialog(dialog) {
- function doLoad() {
- content.document.querySelector('iframe').remove();
- }
- testBrowser.messageManager.loadFrameScript("data:,(" + doLoad.toString() + ")()", false);
- executeSoon(continueDownloading);
- }
-
- function continueDownloading() {
- let windows = Services.wm.getEnumerator("");
- while (windows.hasMoreElements()) {
- let win = windows.getNext();
- if (win.location && win.location.href == UCT_URI) {
- win.document.documentElement._fireButtonEvent("accept");
- win.close();
- return;
- }
- }
- ok(false, "No Unknown Content Type dialog yet?");
- }
-
- function onTransferComplete(aWindow2, downloadSuccess) {
- ok(downloadSuccess, "Link should have been downloaded successfully");
- aWindow2.close();
-
- executeSoon(aCallback);
- }
-}
-
-
-var windowObserver = {
- setCallback: function(aCallback) {
- if (this._callback) {
- ok(false, "Should only be dealing with one callback at a time.");
- }
- this._callback = aCallback;
- },
- observe: function(aSubject, aTopic, aData) {
- if (aTopic != "domwindowopened") {
- return;
- }
-
- let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
-
- win.addEventListener("load", function onLoad(event) {
- win.removeEventListener("load", onLoad, false);
-
- if (win.location == UCT_URI) {
- SimpleTest.executeSoon(function() {
- if (windowObserver._callback) {
- windowObserver._callback(win);
- delete windowObserver._callback;
- } else {
- ok(false, "Unexpected UCT dialog!");
- }
- });
- }
- }, false);
- }
-};
-
-Services.ww.registerNotification(windowObserver);
-
-function test() {
- waitForExplicitFinish();
-
- function testOnWindow(options, callback) {
- info("testOnWindow(" + options + ")");
- var win = OpenBrowserWindow(options);
- info("got " + win);
- whenDelayedStartupFinished(win, () => callback(win));
- }
-
- function whenDelayedStartupFinished(aWindow, aCallback) {
- info("whenDelayedStartupFinished");
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- info("whenDelayedStartupFinished, got topic: " + aTopic + ", got subject: " + aSubject + ", waiting for " + aWindow);
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- executeSoon(aCallback);
- info("whenDelayedStartupFinished found our window");
- }
- }, "browser-delayed-startup-finished", false);
- }
-
- mockTransferRegisterer.register();
-
- registerCleanupFunction(function () {
- info("Running the cleanup code");
- mockTransferRegisterer.unregister();
- MockFilePicker.cleanup();
- Services.ww.unregisterNotification(windowObserver);
- Services.prefs.clearUserPref(ALWAYS_DOWNLOAD_DIR_PREF);
- Services.prefs.clearUserPref(SAVE_PER_SITE_PREF);
- info("Finished running the cleanup code");
- });
-
- Services.prefs.setBoolPref(ALWAYS_DOWNLOAD_DIR_PREF, false);
- testOnWindow(undefined, function(win) {
- let windowGonePromise = promiseWindowWillBeClosed(win);
- Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, true);
- triggerSave(win, function() {
- windowGonePromise.then(function() {
- Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, false);
- testOnWindow(undefined, function(win2) {
- triggerSave(win2, finish);
- });
- });
- });
- });
-}
-
diff --git a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js
deleted file mode 100644
index e7ed5fa34..000000000
--- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/* 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/. */
-
-function createTemporarySaveDirectory() {
- var saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
- saveDir.append("testsavedir");
- if (!saveDir.exists())
- saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- return saveDir;
-}
-
-function promiseNoCacheEntry(filename) {
- return new Promise((resolve, reject) => {
- Visitor.prototype = {
- onCacheStorageInfo: function(num, consumption)
- {
- info("disk storage contains " + num + " entries");
- },
- onCacheEntryInfo: function(uri)
- {
- let urispec = uri.asciiSpec;
- info(urispec);
- is(urispec.includes(filename), false, "web content present in disk cache");
- },
- onCacheEntryVisitCompleted: function()
- {
- resolve();
- }
- };
- function Visitor() {}
-
- let cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- let {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", null);
- let storage = cache.diskCacheStorage(LoadContextInfo.default, false);
- storage.asyncVisitStorage(new Visitor(), true /* Do walk entries */);
- });
-}
-
-function promiseImageDownloaded() {
- return new Promise((resolve, reject) => {
- let fileName;
- let MockFilePicker = SpecialPowers.MockFilePicker;
- MockFilePicker.init(window);
-
- function onTransferComplete(downloadSuccess) {
- ok(downloadSuccess, "Image file should have been downloaded successfully " + fileName);
-
- // Give the request a chance to finish and create a cache entry
- resolve(fileName);
- }
-
- // Create the folder the image will be saved into.
- var destDir = createTemporarySaveDirectory();
- var destFile = destDir.clone();
-
- MockFilePicker.displayDirectory = destDir;
- MockFilePicker.showCallback = function(fp) {
- fileName = fp.defaultString;
- destFile.append (fileName);
- MockFilePicker.returnFiles = [destFile];
- MockFilePicker.filterIndex = 1; // kSaveAsType_URL
- };
-
- mockTransferCallback = onTransferComplete;
- mockTransferRegisterer.register();
-
- registerCleanupFunction(function () {
- mockTransferCallback = null;
- mockTransferRegisterer.unregister();
- MockFilePicker.cleanup();
- destDir.remove(true);
- });
-
- });
-}
-
-add_task(function* () {
- let testURI = "http://mochi.test:8888/browser/browser/base/content/test/general/bug792517.html";
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let tab = yield BrowserTestUtils.openNewForegroundTab(privateWindow.gBrowser, testURI);
-
- let contextMenu = privateWindow.document.getElementById("contentAreaContextMenu");
- let popupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- let popupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- yield BrowserTestUtils.synthesizeMouseAtCenter("#img", {
- type: "contextmenu",
- button: 2
- }, tab.linkedBrowser);
- yield popupShown;
-
- let cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- cache.clear();
-
- let imageDownloaded = promiseImageDownloaded();
- // Select "Save Image As" option from context menu
- privateWindow.document.getElementById("context-saveimage").doCommand();
-
- contextMenu.hidePopup();
- yield popupHidden;
-
- // wait for image download
- let fileName = yield imageDownloaded;
- yield promiseNoCacheEntry(fileName);
-
- yield BrowserTestUtils.closeWindow(privateWindow);
-});
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
- this);
diff --git a/browser/base/content/test/general/browser_save_video.js b/browser/base/content/test/general/browser_save_video.js
deleted file mode 100644
index e81286b7a..000000000
--- a/browser/base/content/test/general/browser_save_video.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.init(window);
-
-/**
- * TestCase for bug 564387
- * <https://bugzilla.mozilla.org/show_bug.cgi?id=564387>
- */
-add_task(function* () {
- var fileName;
-
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/general/web_video.html");
- yield loadPromise;
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown");
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#video1",
- { type: "contextmenu", button: 2 },
- gBrowser.selectedBrowser);
- info("context menu click on video1");
-
- yield popupShownPromise;
-
- info("context menu opened on video1");
-
- // Create the folder the video will be saved into.
- var destDir = createTemporarySaveDirectory();
- var destFile = destDir.clone();
-
- MockFilePicker.displayDirectory = destDir;
- MockFilePicker.showCallback = function(fp) {
- fileName = fp.defaultString;
- destFile.append(fileName);
- MockFilePicker.returnFiles = [destFile];
- MockFilePicker.filterIndex = 1; // kSaveAsType_URL
- };
-
- let transferCompletePromise = new Promise((resolve) => {
- function onTransferComplete(downloadSuccess) {
- ok(downloadSuccess, "Video file should have been downloaded successfully");
-
- is(fileName, "web-video1-expectedName.ogv",
- "Video file name is correctly retrieved from Content-Disposition http header");
- resolve();
- }
-
- mockTransferCallback = onTransferComplete;
- mockTransferRegisterer.register();
- });
-
- registerCleanupFunction(function () {
- mockTransferRegisterer.unregister();
- MockFilePicker.cleanup();
- destDir.remove(true);
- });
-
- // Select "Save Video As" option from context menu
- var saveVideoCommand = document.getElementById("context-savevideo");
- saveVideoCommand.doCommand();
- info("context-savevideo command executed");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- contextMenu.hidePopup();
- yield popupHiddenPromise;
-
- yield transferCompletePromise;
-});
-
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
- this);
-
-function createTemporarySaveDirectory() {
- var saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
- saveDir.append("testsavedir");
- if (!saveDir.exists())
- saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- return saveDir;
-}
diff --git a/browser/base/content/test/general/browser_save_video_frame.js b/browser/base/content/test/general/browser_save_video_frame.js
deleted file mode 100644
index e9b8a0475..000000000
--- a/browser/base/content/test/general/browser_save_video_frame.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const VIDEO_URL = "http://mochi.test:8888/browser/browser/base/content/test/general/web_video.html";
-
-/**
- * mockTransfer.js provides a utility that lets us mock out
- * the "Save File" dialog.
- */
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
- this);
-
-/**
- * Creates and returns an nsIFile for a new temporary save
- * directory.
- *
- * @return nsIFile
- */
-function createTemporarySaveDirectory() {
- let saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
- saveDir.append("testsavedir");
- if (!saveDir.exists())
- saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- return saveDir;
-}
-/**
- * MockTransfer exposes a "mockTransferCallback" global which
- * allows us to define a callback to be called once the mock file
- * selector has selected where to save the file.
- */
-function waitForTransferComplete() {
- return new Promise((resolve) => {
- mockTransferCallback = () => {
- ok(true, "Transfer completed");
- resolve();
- }
- });
-}
-
-/**
- * Given some browser, loads a framescript that right-clicks
- * on the video1 element to spawn a contextmenu.
- */
-function rightClickVideo(browser) {
- let frame_script = () => {
- const Ci = Components.interfaces;
- let utils = content.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
-
- let document = content.document;
- let video = document.getElementById("video1");
- let rect = video.getBoundingClientRect();
-
- /* Synthesize a click in the center of the video. */
- let left = rect.left + (rect.width / 2);
- let top = rect.top + (rect.height / 2);
-
- utils.sendMouseEvent("contextmenu", left, top,
- 2, /* aButton */
- 1, /* aClickCount */
- 0 /* aModifiers */);
- };
- let mm = browser.messageManager;
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", true);
-}
-
-/**
- * Loads a page with a <video> element, right-clicks it and chooses
- * to save a frame screenshot to the disk. Completes once we've
- * verified that the frame has been saved to disk.
- */
-add_task(function*() {
- let MockFilePicker = SpecialPowers.MockFilePicker;
- MockFilePicker.init(window);
-
- // Create the folder the video will be saved into.
- let destDir = createTemporarySaveDirectory();
- let destFile = destDir.clone();
-
- MockFilePicker.displayDirectory = destDir;
- MockFilePicker.showCallback = function(fp) {
- destFile.append(fp.defaultString);
- MockFilePicker.returnFiles = [destFile];
- MockFilePicker.filterIndex = 1; // kSaveAsType_URL
- };
-
- mockTransferRegisterer.register();
-
- // Make sure that we clean these things up when we're done.
- registerCleanupFunction(function () {
- mockTransferRegisterer.unregister();
- MockFilePicker.cleanup();
- destDir.remove(true);
- });
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- info("Loading video tab");
- yield promiseTabLoadEvent(tab, VIDEO_URL);
- info("Video tab loaded.");
-
- let context = document.getElementById("contentAreaContextMenu");
- let popupPromise = promisePopupShown(context);
-
- info("Synthesizing right-click on video element");
- rightClickVideo(browser);
- info("Waiting for popup to fire popupshown.");
- yield popupPromise;
- info("Popup fired popupshown");
-
- let saveSnapshotCommand = document.getElementById("context-video-saveimage");
- let promiseTransfer = waitForTransferComplete()
- info("Firing save snapshot command");
- saveSnapshotCommand.doCommand();
- context.hidePopup();
- info("Waiting for transfer completion");
- yield promiseTransfer;
- info("Transfer complete");
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_scope.js b/browser/base/content/test/general/browser_scope.js
deleted file mode 100644
index f8141e5f6..000000000
--- a/browser/base/content/test/general/browser_scope.js
+++ /dev/null
@@ -1,10 +0,0 @@
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: this.docShell is null");
-
-function test() {
- ok(!!gBrowser, "gBrowser exists");
- is(gBrowser, getBrowser(), "both ways of getting tabbrowser work");
-}
diff --git a/browser/base/content/test/general/browser_selectTabAtIndex.js b/browser/base/content/test/general/browser_selectTabAtIndex.js
deleted file mode 100644
index b6578aec0..000000000
--- a/browser/base/content/test/general/browser_selectTabAtIndex.js
+++ /dev/null
@@ -1,81 +0,0 @@
-"use strict";
-
-function test() {
- const isLinux = navigator.platform.indexOf("Linux") == 0;
-
- function assertTab(expectedTab) {
- is(gBrowser.tabContainer.selectedIndex, expectedTab,
- `tab index ${expectedTab} should be selected`);
- }
-
- function sendAccelKey(key) {
- // Make sure the keystroke goes to chrome.
- document.activeElement.blur();
- EventUtils.synthesizeKey(key.toString(), { altKey: isLinux, accelKey: !isLinux });
- }
-
- function createTabs(count) {
- for (let n = 0; n < count; n++)
- gBrowser.addTab();
- }
-
- function testKey(key, expectedTab) {
- sendAccelKey(key);
- assertTab(expectedTab);
- }
-
- function testIndex(index, expectedTab) {
- gBrowser.selectTabAtIndex(index);
- assertTab(expectedTab);
- }
-
- // Create fewer tabs than our 9 number keys.
- is(gBrowser.tabs.length, 1, "should have 1 tab");
- createTabs(4);
- is(gBrowser.tabs.length, 5, "should have 5 tabs");
-
- // Test keyboard shortcuts. Order tests so that no two test cases have the
- // same expected tab in a row. This ensures that tab selection actually
- // changed the selected tab.
- testKey(8, 4);
- testKey(1, 0);
- testKey(2, 1);
- testKey(4, 3);
- testKey(9, 4);
-
- // Test index selection.
- testIndex(0, 0);
- testIndex(4, 4);
- testIndex(-5, 0);
- testIndex(5, 4);
- testIndex(-4, 1);
- testIndex(1, 1);
- testIndex(-1, 4);
- testIndex(9, 4);
-
- // Create more tabs than our 9 number keys.
- createTabs(10);
- is(gBrowser.tabs.length, 15, "should have 15 tabs");
-
- // Test keyboard shortcuts.
- testKey(2, 1);
- testKey(1, 0);
- testKey(4, 3);
- testKey(8, 7);
- testKey(9, 14);
-
- // Test index selection.
- testIndex(-15, 0);
- testIndex(14, 14);
- testIndex(-14, 1);
- testIndex(15, 14);
- testIndex(-1, 14);
- testIndex(0, 0);
- testIndex(1, 1);
- testIndex(9, 9);
-
- // Clean up tabs.
- for (let n = 15; n > 1; n--)
- gBrowser.removeTab(gBrowser.selectedTab, {skipPermitUnload: true});
- is(gBrowser.tabs.length, 1, "should have 1 tab");
-}
diff --git a/browser/base/content/test/general/browser_selectpopup.js b/browser/base/content/test/general/browser_selectpopup.js
deleted file mode 100644
index d34254d1c..000000000
--- a/browser/base/content/test/general/browser_selectpopup.js
+++ /dev/null
@@ -1,563 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test checks that a <select> with an <optgroup> opens and can be navigated
-// in a child process. This is different than single-process as a <menulist> is used
-// to implement the dropdown list.
-
-requestLongerTimeout(2);
-
-const XHTML_DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
-
-const PAGECONTENT =
- "<html xmlns='http://www.w3.org/1999/xhtml'>" +
- "<body onload='gChangeEvents = 0;gInputEvents = 0; document.body.firstChild.focus()'><select oninput='gInputEvents++' onchange='gChangeEvents++'>" +
- " <optgroup label='First Group'>" +
- " <option value='One'>One</option>" +
- " <option value='Two'>Two</option>" +
- " </optgroup>" +
- " <option value='Three'>Three</option>" +
- " <optgroup label='Second Group' disabled='true'>" +
- " <option value='Four'>Four</option>" +
- " <option value='Five'>Five</option>" +
- " </optgroup>" +
- " <option value='Six' disabled='true'>Six</option>" +
- " <optgroup label='Third Group'>" +
- " <option value='Seven'> Seven </option>" +
- " <option value='Eight'>&nbsp;&nbsp;Eight&nbsp;&nbsp;</option>" +
- " </optgroup></select><input />Text" +
- "</body></html>";
-
-const PAGECONTENT_SMALL =
- "<html>" +
- "<body><select id='one'>" +
- " <option value='One'>One</option>" +
- " <option value='Two'>Two</option>" +
- "</select><select id='two'>" +
- " <option value='Three'>Three</option>" +
- " <option value='Four'>Four</option>" +
- "</select><select id='three'>" +
- " <option value='Five'>Five</option>" +
- " <option value='Six'>Six</option>" +
- "</select></body></html>";
-
-const PAGECONTENT_SOMEHIDDEN =
- "<html><head><style>.hidden { display: none; }</style></head>" +
- "<body><select id='one'>" +
- " <option value='One' style='display: none;'>OneHidden</option>" +
- " <option value='Two' class='hidden'>TwoHidden</option>" +
- " <option value='Three'>ThreeVisible</option>" +
- " <option value='Four'style='display: table;'>FourVisible</option>" +
- " <option value='Five'>FiveVisible</option>" +
- " <optgroup label='GroupHidden' class='hidden'>" +
- " <option value='Four'>Six.OneHidden</option>" +
- " <option value='Five' style='display: block;'>Six.TwoHidden</option>" +
- " </optgroup>" +
- " <option value='Six' class='hidden' style='display: block;'>SevenVisible</option>" +
- "</select></body></html>";
-
-const PAGECONTENT_TRANSLATED =
- "<html><body>" +
- "<div id='div'>" +
- "<iframe id='frame' width='320' height='295' style='border: none;'" +
- " src='data:text/html,<select id=select autofocus><option>he he he</option><option>boo boo</option><option>baz baz</option></select>'" +
- "</iframe>" +
- "</div></body></html>";
-
-function openSelectPopup(selectPopup, withMouse, selector = "select", win = window)
-{
- let popupShownPromise = BrowserTestUtils.waitForEvent(selectPopup, "popupshown");
-
- if (withMouse) {
- return Promise.all([popupShownPromise,
- BrowserTestUtils.synthesizeMouseAtCenter(selector, { }, win.gBrowser.selectedBrowser)]);
- }
-
- EventUtils.synthesizeKey("KEY_ArrowDown", { altKey: true, code: "ArrowDown" }, win);
- return popupShownPromise;
-}
-
-function hideSelectPopup(selectPopup, mode = "enter", win = window)
-{
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(selectPopup, "popuphidden");
-
- if (mode == "escape") {
- EventUtils.synthesizeKey("KEY_Escape", { code: "Escape" }, win);
- }
- else if (mode == "enter") {
- EventUtils.synthesizeKey("KEY_Enter", { code: "Enter" }, win);
- }
- else if (mode == "click") {
- EventUtils.synthesizeMouseAtCenter(selectPopup.lastChild, { }, win);
- }
-
- return popupHiddenPromise;
-}
-
-function getInputEvents()
-{
- return ContentTask.spawn(gBrowser.selectedBrowser, {}, function() {
- return content.wrappedJSObject.gInputEvents;
- });
-}
-
-function getChangeEvents()
-{
- return ContentTask.spawn(gBrowser.selectedBrowser, {}, function() {
- return content.wrappedJSObject.gChangeEvents;
- });
-}
-
-function* doSelectTests(contentType, dtd)
-{
- const pageUrl = "data:" + contentType + "," + escape(dtd + "\n" + PAGECONTENT);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- let menulist = document.getElementById("ContentSelectDropdown");
- let selectPopup = menulist.menupopup;
-
- yield openSelectPopup(selectPopup);
-
- let isWindows = navigator.platform.indexOf("Win") >= 0;
-
- is(menulist.selectedIndex, 1, "Initial selection");
- is(selectPopup.firstChild.localName, "menucaption", "optgroup is caption");
- is(selectPopup.firstChild.getAttribute("label"), "First Group", "optgroup label");
- is(selectPopup.childNodes[1].localName, "menuitem", "option is menuitem");
- is(selectPopup.childNodes[1].getAttribute("label"), "One", "option label");
-
- EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
- is(menulist.menuBoxObject.activeChild, menulist.getItemAtIndex(2), "Select item 2");
- is(menulist.selectedIndex, isWindows ? 2 : 1, "Select item 2 selectedIndex");
-
- EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
- is(menulist.menuBoxObject.activeChild, menulist.getItemAtIndex(3), "Select item 3");
- is(menulist.selectedIndex, isWindows ? 3 : 1, "Select item 3 selectedIndex");
-
- EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
-
- // On Windows, one can navigate on disabled menuitems
- is(menulist.menuBoxObject.activeChild, menulist.getItemAtIndex(9),
- "Skip optgroup header and disabled items select item 7");
- is(menulist.selectedIndex, isWindows ? 9 : 1, "Select or skip disabled item selectedIndex");
-
- for (let i = 0; i < 10; i++) {
- is(menulist.getItemAtIndex(i).disabled, i >= 4 && i <= 7, "item " + i + " disabled")
- }
-
- EventUtils.synthesizeKey("KEY_ArrowUp", { code: "ArrowUp" });
- is(menulist.menuBoxObject.activeChild, menulist.getItemAtIndex(3), "Select item 3 again");
- is(menulist.selectedIndex, isWindows ? 3 : 1, "Select item 3 selectedIndex");
-
- is((yield getInputEvents()), 0, "Before closed - number of input events");
- is((yield getChangeEvents()), 0, "Before closed - number of change events");
-
- EventUtils.synthesizeKey("a", { accelKey: true });
- yield ContentTask.spawn(gBrowser.selectedBrowser, { isWindows }, function(args) {
- Assert.equal(String(content.getSelection()), args.isWindows ? "Text" : "",
- "Select all while popup is open");
- });
-
- // Backspace should not go back
- let handleKeyPress = function(event) {
- ok(false, "Should not get keypress event");
- }
- window.addEventListener("keypress", handleKeyPress);
- EventUtils.synthesizeKey("VK_BACK_SPACE", { });
- window.removeEventListener("keypress", handleKeyPress);
-
- yield hideSelectPopup(selectPopup);
-
- is(menulist.selectedIndex, 3, "Item 3 still selected");
- is((yield getInputEvents()), 1, "After closed - number of input events");
- is((yield getChangeEvents()), 1, "After closed - number of change events");
-
- // Opening and closing the popup without changing the value should not fire a change event.
- yield openSelectPopup(selectPopup, true);
- yield hideSelectPopup(selectPopup, "escape");
- is((yield getInputEvents()), 1, "Open and close with no change - number of input events");
- is((yield getChangeEvents()), 1, "Open and close with no change - number of change events");
- EventUtils.synthesizeKey("VK_TAB", { });
- EventUtils.synthesizeKey("VK_TAB", { shiftKey: true });
- is((yield getInputEvents()), 1, "Tab away from select with no change - number of input events");
- is((yield getChangeEvents()), 1, "Tab away from select with no change - number of change events");
-
- yield openSelectPopup(selectPopup, true);
- EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
- yield hideSelectPopup(selectPopup, "escape");
- is((yield getInputEvents()), isWindows ? 2 : 1, "Open and close with change - number of input events");
- is((yield getChangeEvents()), isWindows ? 2 : 1, "Open and close with change - number of change events");
- EventUtils.synthesizeKey("VK_TAB", { });
- EventUtils.synthesizeKey("VK_TAB", { shiftKey: true });
- is((yield getInputEvents()), isWindows ? 2 : 1, "Tab away from select with change - number of input events");
- is((yield getChangeEvents()), isWindows ? 2 : 1, "Tab away from select with change - number of change events");
-
- is(selectPopup.lastChild.previousSibling.label, "Seven", "Spaces collapsed");
- is(selectPopup.lastChild.label, "\xA0\xA0Eight\xA0\xA0", "Non-breaking spaces not collapsed");
-
- yield BrowserTestUtils.removeTab(tab);
-}
-
-add_task(function*() {
- yield doSelectTests("text/html", "");
-});
-
-add_task(function*() {
- yield doSelectTests("application/xhtml+xml", XHTML_DTD);
-});
-
-// This test opens a select popup and removes the content node of a popup while
-// The popup should close if its node is removed.
-add_task(function*() {
- const pageUrl = "data:text/html," + escape(PAGECONTENT_SMALL);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- let menulist = document.getElementById("ContentSelectDropdown");
- let selectPopup = menulist.menupopup;
-
- // First, try it when a different <select> element than the one that is open is removed
- yield openSelectPopup(selectPopup, true, "#one");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function() {
- content.document.body.removeChild(content.document.getElementById("two"));
- });
-
- // Wait a bit just to make sure the popup won't close.
- yield new Promise(resolve => setTimeout(resolve, 1000));
-
- is(selectPopup.state, "open", "Different popup did not affect open popup");
-
- yield hideSelectPopup(selectPopup);
-
- // Next, try it when the same <select> element than the one that is open is removed
- yield openSelectPopup(selectPopup, true, "#three");
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(selectPopup, "popuphidden");
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function() {
- content.document.body.removeChild(content.document.getElementById("three"));
- });
- yield popupHiddenPromise;
-
- ok(true, "Popup hidden when select is removed");
-
- // Finally, try it when the tab is closed while the select popup is open.
- yield openSelectPopup(selectPopup, true, "#one");
-
- popupHiddenPromise = BrowserTestUtils.waitForEvent(selectPopup, "popuphidden");
- yield BrowserTestUtils.removeTab(tab);
- yield popupHiddenPromise;
-
- ok(true, "Popup hidden when tab is closed");
-});
-
-// This test opens a select popup that is isn't a frame and has some translations applied.
-add_task(function*() {
- const pageUrl = "data:text/html," + escape(PAGECONTENT_TRANSLATED);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- let menulist = document.getElementById("ContentSelectDropdown");
- let selectPopup = menulist.menupopup;
-
- // First, get the position of the select popup when no translations have been applied.
- yield openSelectPopup(selectPopup, false);
-
- let rect = selectPopup.getBoundingClientRect();
- let expectedX = rect.left;
- let expectedY = rect.top;
-
- yield hideSelectPopup(selectPopup);
-
- // Iterate through a set of steps which each add more translation to the select's expected position.
- let steps = [
- [ "div", "transform: translateX(7px) translateY(13px);", 7, 13 ],
- [ "frame", "border-top: 5px solid green; border-left: 10px solid red; border-right: 35px solid blue;", 10, 5 ],
- [ "frame", "border: none; padding-left: 6px; padding-right: 12px; padding-top: 2px;", -4, -3 ],
- [ "select", "margin: 9px; transform: translateY(-3px);", 9, 6 ],
- ];
-
- for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
- let step = steps[stepIndex];
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, step, function*(contentStep) {
- return new Promise(resolve => {
- let changedWin = content;
-
- let elem;
- if (contentStep[0] == "select") {
- changedWin = content.document.getElementById("frame").contentWindow;
- elem = changedWin.document.getElementById("select");
- }
- else {
- elem = content.document.getElementById(contentStep[0]);
- }
-
- changedWin.addEventListener("MozAfterPaint", function onPaint() {
- changedWin.removeEventListener("MozAfterPaint", onPaint);
- resolve();
- });
-
- elem.style = contentStep[1];
- elem.getBoundingClientRect();
- });
- });
-
- yield openSelectPopup(selectPopup, false);
-
- expectedX += step[2];
- expectedY += step[3];
-
- let popupRect = selectPopup.getBoundingClientRect();
- is(popupRect.left, expectedX, "step " + (stepIndex + 1) + " x");
- is(popupRect.top, expectedY, "step " + (stepIndex + 1) + " y");
-
- yield hideSelectPopup(selectPopup);
- }
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-// Test that we get the right events when a select popup is changed.
-add_task(function* test_event_order() {
- const URL = "data:text/html," + escape(PAGECONTENT_SMALL);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: URL,
- }, function*(browser) {
- let menulist = document.getElementById("ContentSelectDropdown");
- let selectPopup = menulist.menupopup;
-
- // According to https://html.spec.whatwg.org/#the-select-element,
- // we want to fire input, change, and then click events on the
- // <select> (in that order) when it has changed.
- let expectedEnter = [
- {
- type: "input",
- cancelable: false,
- targetIsOption: false,
- },
- {
- type: "change",
- cancelable: false,
- targetIsOption: false,
- },
- ];
-
- let expectedClick = [
- {
- type: "mousedown",
- cancelable: true,
- targetIsOption: true,
- },
- {
- type: "mouseup",
- cancelable: true,
- targetIsOption: true,
- },
- {
- type: "input",
- cancelable: false,
- targetIsOption: false,
- },
- {
- type: "change",
- cancelable: false,
- targetIsOption: false,
- },
- {
- type: "click",
- cancelable: true,
- targetIsOption: true,
- },
- ];
-
- for (let mode of ["enter", "click"]) {
- let expected = mode == "enter" ? expectedEnter : expectedClick;
- yield openSelectPopup(selectPopup, true, mode == "enter" ? "#one" : "#two");
-
- let eventsPromise = ContentTask.spawn(browser, [mode, expected], function*([contentMode, contentExpected]) {
- return new Promise((resolve) => {
- function onEvent(event) {
- select.removeEventListener(event.type, onEvent);
- Assert.ok(contentExpected.length, "Unexpected event " + event.type);
- let expectation = contentExpected.shift();
- Assert.equal(event.type, expectation.type,
- "Expected the right event order");
- Assert.ok(event.bubbles, "All of these events should bubble");
- Assert.equal(event.cancelable, expectation.cancelable,
- "Cancellation property should match");
- Assert.equal(event.target.localName,
- expectation.targetIsOption ? "option" : "select",
- "Target matches");
- if (!contentExpected.length) {
- resolve();
- }
- }
-
- let select = content.document.getElementById(contentMode == "enter" ? "one" : "two");
- for (let event of ["input", "change", "mousedown", "mouseup", "click"]) {
- select.addEventListener(event, onEvent);
- }
- });
- });
-
- EventUtils.synthesizeKey("KEY_ArrowDown", { code: "ArrowDown" });
- yield hideSelectPopup(selectPopup, mode);
- yield eventsPromise;
- }
- });
-});
-
-function* performLargePopupTests(win)
-{
- let browser = win.gBrowser.selectedBrowser;
-
- yield ContentTask.spawn(browser, null, function*() {
- let doc = content.document;
- let select = doc.getElementById("one");
- for (var i = 0; i < 180; i++) {
- select.add(new content.Option("Test" + i));
- }
-
- select.options[60].selected = true;
- select.focus();
- });
-
- let selectPopup = win.document.getElementById("ContentSelectDropdown").menupopup;
- let browserRect = browser.getBoundingClientRect();
-
- let positions = [
- "margin-top: 300px;",
- "position: fixed; bottom: 100px;",
- "width: 100%; height: 9999px;"
- ];
-
- let position;
- while (true) {
- yield openSelectPopup(selectPopup, false, "select", win);
-
- let rect = selectPopup.getBoundingClientRect();
- ok(rect.top >= browserRect.top, "Popup top position in within browser area");
- ok(rect.bottom <= browserRect.bottom, "Popup bottom position in within browser area");
-
- // Don't check the scroll position for the last step as the popup will be cut off.
- if (positions.length > 0) {
- let cs = win.getComputedStyle(selectPopup);
- let bpBottom = parseFloat(cs.paddingBottom) + parseFloat(cs.borderBottomWidth);
-
- is(selectPopup.childNodes[60].getBoundingClientRect().bottom,
- selectPopup.getBoundingClientRect().bottom - bpBottom,
- "Popup scroll at correct position " + bpBottom);
- }
-
- yield hideSelectPopup(selectPopup, "enter", win);
-
- position = positions.shift();
- if (!position) {
- break;
- }
-
- let contentPainted = BrowserTestUtils.contentPainted(browser);
- yield ContentTask.spawn(browser, position, function*(contentPosition) {
- let select = content.document.getElementById("one");
- select.setAttribute("style", contentPosition);
- select.getBoundingClientRect();
- });
- yield contentPainted;
- }
-}
-
-// This test checks select elements with a large number of options to ensure that
-// the popup appears within the browser area.
-add_task(function* test_large_popup() {
- const pageUrl = "data:text/html," + escape(PAGECONTENT_SMALL);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- yield* performLargePopupTests(window);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-// This test checks the same as the previous test but in a new smaller window.
-add_task(function* test_large_popup_in_small_window() {
- let newwin = yield BrowserTestUtils.openNewBrowserWindow({ width: 400, height: 400 });
-
- const pageUrl = "data:text/html," + escape(PAGECONTENT_SMALL);
- let browserLoadedPromise = BrowserTestUtils.browserLoaded(newwin.gBrowser.selectedBrowser);
- yield BrowserTestUtils.loadURI(newwin.gBrowser.selectedBrowser, pageUrl);
- yield browserLoadedPromise;
-
- newwin.gBrowser.selectedBrowser.focus();
-
- yield* performLargePopupTests(newwin);
-
- yield BrowserTestUtils.closeWindow(newwin);
-});
-
-// This test checks that a mousemove event is fired correctly at the menu and
-// not at the browser, ensuring that any mouse capture has been cleared.
-add_task(function* test_mousemove_correcttarget() {
- const pageUrl = "data:text/html," + escape(PAGECONTENT_SMALL);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- let selectPopup = document.getElementById("ContentSelectDropdown").menupopup;
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(selectPopup, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter("#one", { type: "mousedown" }, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- yield new Promise(resolve => {
- window.addEventListener("mousemove", function checkForMouseMove(event) {
- window.removeEventListener("mousemove", checkForMouseMove, true);
- is(event.target.localName.indexOf("menu"), 0, "mouse over menu");
- resolve();
- }, true);
-
- EventUtils.synthesizeMouseAtCenter(selectPopup.firstChild, { type: "mousemove" });
- });
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#one", { type: "mouseup" }, gBrowser.selectedBrowser);
-
- yield hideSelectPopup(selectPopup);
-
- // The popup should be closed when fullscreen mode is entered or exited.
- for (let steps = 0; steps < 2; steps++) {
- yield openSelectPopup(selectPopup, true);
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(selectPopup, "popuphidden");
- let sizeModeChanged = BrowserTestUtils.waitForEvent(window, "sizemodechange");
- BrowserFullScreen();
- yield sizeModeChanged;
- yield popupHiddenPromise;
- }
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-// This test checks when a <select> element has some options with altered display values.
-add_task(function* test_somehidden() {
- const pageUrl = "data:text/html," + escape(PAGECONTENT_SOMEHIDDEN);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageUrl);
-
- let selectPopup = document.getElementById("ContentSelectDropdown").menupopup;
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(selectPopup, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter("#one", { type: "mousedown" }, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- // The exact number is not needed; just ensure the height is larger than 4 items to accomodate any popup borders.
- ok(selectPopup.getBoundingClientRect().height >= selectPopup.lastChild.getBoundingClientRect().height * 4, "Height contains at least 4 items");
- ok(selectPopup.getBoundingClientRect().height < selectPopup.lastChild.getBoundingClientRect().height * 5, "Height doesn't contain 5 items");
-
- // The label contains the substring 'Visible' for items that are visible.
- // Otherwise, it is expected to be display: none.
- is(selectPopup.parentNode.itemCount, 9, "Correct number of items");
- let child = selectPopup.firstChild;
- let idx = 1;
- while (child) {
- is(getComputedStyle(child).display, child.label.indexOf("Visible") > 0 ? "-moz-box" : "none",
- "Item " + (idx++) + " is visible");
- child = child.nextSibling;
- }
-
- yield hideSelectPopup(selectPopup, "escape");
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/general/browser_ssl_error_reports.js b/browser/base/content/test/general/browser_ssl_error_reports.js
deleted file mode 100644
index b1b1c8b84..000000000
--- a/browser/base/content/test/general/browser_ssl_error_reports.js
+++ /dev/null
@@ -1,174 +0,0 @@
-"use strict";
-
-const URL_REPORTS = "https://example.com/browser/browser/base/content/test/general/ssl_error_reports.sjs?";
-const URL_BAD_CHAIN = "https://badchain.include-subdomains.pinning.example.com/";
-const URL_NO_CERT = "https://fail-handshake.example.com/";
-const URL_BAD_CERT = "https://expired.example.com/";
-const URL_BAD_STS_CERT = "https://badchain.include-subdomains.pinning.example.com:443/";
-const ROOT = getRootDirectory(gTestPath);
-const PREF_REPORT_ENABLED = "security.ssl.errorReporting.enabled";
-const PREF_REPORT_AUTOMATIC = "security.ssl.errorReporting.automatic";
-const PREF_REPORT_URL = "security.ssl.errorReporting.url";
-
-SimpleTest.requestCompleteLog();
-
-Services.prefs.setIntPref("security.cert_pinning.enforcement_level", 2);
-
-function cleanup() {
- Services.prefs.clearUserPref(PREF_REPORT_ENABLED);
- Services.prefs.clearUserPref(PREF_REPORT_AUTOMATIC);
- Services.prefs.clearUserPref(PREF_REPORT_URL);
-}
-
-registerCleanupFunction(() => {
- Services.prefs.clearUserPref("security.cert_pinning.enforcement_level");
- cleanup();
-});
-
-add_task(function* test_send_report_neterror() {
- yield testSendReportAutomatically(URL_BAD_CHAIN, "succeed", "neterror");
- yield testSendReportAutomatically(URL_NO_CERT, "nocert", "neterror");
- yield testSetAutomatic(URL_NO_CERT, "nocert", "neterror");
-});
-
-
-add_task(function* test_send_report_certerror() {
- yield testSendReportAutomatically(URL_BAD_CERT, "badcert", "certerror");
- yield testSetAutomatic(URL_BAD_CERT, "badcert", "certerror");
-});
-
-add_task(function* test_send_disabled() {
- Services.prefs.setBoolPref(PREF_REPORT_ENABLED, false);
- Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, true);
- Services.prefs.setCharPref(PREF_REPORT_URL, "https://example.com/invalid");
-
- // Check with enabled=false but automatic=true.
- yield testSendReportDisabled(URL_NO_CERT, "neterror");
- yield testSendReportDisabled(URL_BAD_CERT, "certerror");
-
- Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, false);
-
- // Check again with both prefs false.
- yield testSendReportDisabled(URL_NO_CERT, "neterror");
- yield testSendReportDisabled(URL_BAD_CERT, "certerror");
- cleanup();
-});
-
-function* testSendReportAutomatically(testURL, suffix, errorURISuffix) {
- Services.prefs.setBoolPref(PREF_REPORT_ENABLED, true);
- Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, true);
- Services.prefs.setCharPref(PREF_REPORT_URL, URL_REPORTS + suffix);
-
- // Add a tab and wait until it's loaded.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- let browser = tab.linkedBrowser;
-
- // Load the page and wait for the error report submission.
- let promiseStatus = createReportResponseStatusPromise(URL_REPORTS + suffix);
- browser.loadURI(testURL);
- yield promiseErrorPageLoaded(browser);
-
- ok(!isErrorStatus(yield promiseStatus),
- "SSL error report submitted successfully");
-
- // Check that we loaded the right error page.
- yield checkErrorPage(browser, errorURISuffix);
-
- // Cleanup.
- gBrowser.removeTab(tab);
- cleanup();
-}
-
-function* testSetAutomatic(testURL, suffix, errorURISuffix) {
- Services.prefs.setBoolPref(PREF_REPORT_ENABLED, true);
- Services.prefs.setBoolPref(PREF_REPORT_AUTOMATIC, false);
- Services.prefs.setCharPref(PREF_REPORT_URL, URL_REPORTS + suffix);
-
- // Add a tab and wait until it's loaded.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- let browser = tab.linkedBrowser;
-
- // Load the page.
- browser.loadURI(testURL);
- yield promiseErrorPageLoaded(browser);
-
- // Check that we loaded the right error page.
- yield checkErrorPage(browser, errorURISuffix);
-
- let statusPromise = createReportResponseStatusPromise(URL_REPORTS + suffix);
-
- // Click the checkbox, enable automatic error reports.
- yield ContentTask.spawn(browser, null, function* () {
- content.document.getElementById("automaticallyReportInFuture").click();
- });
-
- // Wait for the error report submission.
- yield statusPromise;
-
- let isAutomaticReportingEnabled = () =>
- Services.prefs.getBoolPref(PREF_REPORT_AUTOMATIC);
-
- // Check that the pref was flipped.
- ok(isAutomaticReportingEnabled(), "automatic SSL report submission enabled");
-
- // Disable automatic error reports.
- yield ContentTask.spawn(browser, null, function* () {
- content.document.getElementById("automaticallyReportInFuture").click();
- });
-
- // Check that the pref was flipped.
- ok(!isAutomaticReportingEnabled(), "automatic SSL report submission disabled");
-
- // Cleanup.
- gBrowser.removeTab(tab);
- cleanup();
-}
-
-function* testSendReportDisabled(testURL, errorURISuffix) {
- // Add a tab and wait until it's loaded.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- let browser = tab.linkedBrowser;
-
- // Load the page.
- browser.loadURI(testURL);
- yield promiseErrorPageLoaded(browser);
-
- // Check that we loaded the right error page.
- yield checkErrorPage(browser, errorURISuffix);
-
- // Check that the error reporting section is hidden.
- yield ContentTask.spawn(browser, null, function* () {
- let section = content.document.getElementById("certificateErrorReporting");
- Assert.equal(content.getComputedStyle(section).display, "none",
- "error reporting section should be hidden");
- });
-
- // Cleanup.
- gBrowser.removeTab(tab);
-}
-
-function isErrorStatus(status) {
- return status < 200 || status >= 300;
-}
-
-// use the observer service to see when a report is sent
-function createReportResponseStatusPromise(expectedURI) {
- return new Promise(resolve => {
- let observer = (subject, topic, data) => {
- subject.QueryInterface(Ci.nsIHttpChannel);
- let requestURI = subject.URI.spec;
- if (requestURI == expectedURI) {
- Services.obs.removeObserver(observer, "http-on-examine-response");
- resolve(subject.responseStatus);
- }
- };
- Services.obs.addObserver(observer, "http-on-examine-response", false);
- });
-}
-
-function checkErrorPage(browser, suffix) {
- return ContentTask.spawn(browser, { suffix }, function* (args) {
- let uri = content.document.documentURI;
- Assert.ok(uri.startsWith(`about:${args.suffix}`), "correct error page loaded");
- });
-}
diff --git a/browser/base/content/test/general/browser_star_hsts.js b/browser/base/content/test/general/browser_star_hsts.js
deleted file mode 100644
index c52e563bc..000000000
--- a/browser/base/content/test/general/browser_star_hsts.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var secureURL = "https://example.com/browser/browser/base/content/test/general/browser_star_hsts.sjs";
-var unsecureURL = "http://example.com/browser/browser/base/content/test/general/browser_star_hsts.sjs";
-
-add_task(function* test_star_redirect() {
- registerCleanupFunction(function() {
- // Ensure to remove example.com from the HSTS list.
- let sss = Cc["@mozilla.org/ssservice;1"]
- .getService(Ci.nsISiteSecurityService);
- sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS,
- NetUtil.newURI("http://example.com/"), 0);
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- gBrowser.removeCurrentTab();
- });
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- // This will add the page to the HSTS cache.
- yield promiseTabLoadEvent(tab, secureURL, secureURL);
- // This should transparently be redirected to the secure page.
- yield promiseTabLoadEvent(tab, unsecureURL, secureURL);
-
- yield promiseStarState(BookmarkingUI.STATUS_UNSTARRED);
-
- let promiseBookmark = promiseOnBookmarkItemAdded(gBrowser.currentURI);
- BookmarkingUI.star.click();
- // This resolves on the next tick, so the star should have already been
- // updated at that point.
- yield promiseBookmark;
-
- is(BookmarkingUI.status, BookmarkingUI.STATUS_STARRED, "The star is starred");
-});
-
-/**
- * Waits for the star to reflect the expected state.
- */
-function promiseStarState(aValue) {
- let deferred = Promise.defer();
- let expectedStatus = aValue ? BookmarkingUI.STATUS_STARRED
- : BookmarkingUI.STATUS_UNSTARRED;
- (function checkState() {
- if (BookmarkingUI.status == BookmarkingUI.STATUS_UPDATING ||
- BookmarkingUI.status != expectedStatus) {
- info("Waiting for star button change.");
- setTimeout(checkState, 1000);
- } else {
- deferred.resolve();
- }
- })();
- return deferred.promise;
-}
-
-/**
- * Starts a load in an existing tab and waits for it to finish (via some event).
- *
- * @param aTab
- * The tab to load into.
- * @param aUrl
- * The url to load.
- * @param [optional] aFinalURL
- * The url to wait for, same as aURL if not defined.
- * @return {Promise} resolved when the event is handled.
- */
-function promiseTabLoadEvent(aTab, aURL, aFinalURL)
-{
- if (!aFinalURL)
- aFinalURL = aURL;
- let deferred = Promise.defer();
- info("Wait for load tab event");
- aTab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != aTab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank" ||
- event.target.location.href != aFinalURL) {
- info("skipping spurious load event");
- return;
- }
- aTab.linkedBrowser.removeEventListener("load", load, true);
- info("Tab load event received");
- deferred.resolve();
- }, true, true);
- aTab.linkedBrowser.loadURI(aURL);
- return deferred.promise;
-}
diff --git a/browser/base/content/test/general/browser_star_hsts.sjs b/browser/base/content/test/general/browser_star_hsts.sjs
deleted file mode 100644
index 10c7aae12..000000000
--- a/browser/base/content/test/general/browser_star_hsts.sjs
+++ /dev/null
@@ -1,13 +0,0 @@
-/* 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/. */
-
-function handleRequest(request, response)
-{
- let page = "<!DOCTYPE html><html><body><p>HSTS page</p></body></html>";
- response.setStatusLine(request.httpVersion, "200", "OK");
- response.setHeader("Strict-Transport-Security", "max-age=60");
- response.setHeader("Content-Type", "text/html", false);
- response.setHeader("Content-Length", page.length + "", false);
- response.write(page);
-}
diff --git a/browser/base/content/test/general/browser_subframe_favicons_not_used.js b/browser/base/content/test/general/browser_subframe_favicons_not_used.js
deleted file mode 100644
index 7efe78d9b..000000000
--- a/browser/base/content/test/general/browser_subframe_favicons_not_used.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Make sure <link rel="..."> isn't respected in sub-frames. */
-
-function test() {
- waitForExplicitFinish();
-
- let testPath = getRootDirectory(gTestPath);
-
- let tab = gBrowser.addTab(testPath + "file_bug970276_popup1.html");
-
- tab.linkedBrowser.addEventListener("load", function() {
- tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- let expectedIcon = testPath + "file_bug970276_favicon1.ico";
- is(gBrowser.getIcon(tab), expectedIcon, "Correct icon.");
-
- gBrowser.removeTab(tab);
-
- finish();
- }, true);
-}
diff --git a/browser/base/content/test/general/browser_syncui.js b/browser/base/content/test/general/browser_syncui.js
deleted file mode 100644
index daf0fa497..000000000
--- a/browser/base/content/test/general/browser_syncui.js
+++ /dev/null
@@ -1,205 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var {Log} = Cu.import("resource://gre/modules/Log.jsm", {});
-var {Weave} = Cu.import("resource://services-sync/main.js", {});
-
-var stringBundle = Cc["@mozilla.org/intl/stringbundle;1"]
- .getService(Ci.nsIStringBundleService)
- .createBundle("chrome://weave/locale/services/sync.properties");
-
-// ensure test output sees log messages.
-Log.repository.getLogger("browserwindow.syncui").addAppender(new Log.DumpAppender());
-
-// Send the specified sync-related notification and return a promise that
-// resolves once gSyncUI._promiseUpateUI is complete and the UI is ready to check.
-function notifyAndPromiseUIUpdated(topic) {
- return new Promise(resolve => {
- // Instrument gSyncUI so we know when the update is complete.
- let oldPromiseUpdateUI = gSyncUI._promiseUpdateUI.bind(gSyncUI);
- gSyncUI._promiseUpdateUI = function() {
- return oldPromiseUpdateUI().then(() => {
- // Restore our override.
- gSyncUI._promiseUpdateUI = oldPromiseUpdateUI;
- // Resolve the promise so the caller knows the update is done.
- resolve();
- });
- };
- // Now send the notification.
- Services.obs.notifyObservers(null, topic, null);
- });
-}
-
-// Sync manages 3 broadcasters so the menus correctly reflect the Sync state.
-// Only one of these 3 should ever be visible - pass the ID of the broadcaster
-// you expect to be visible and it will check it's the only one that is.
-function checkBroadcasterVisible(broadcasterId) {
- let all = ["sync-reauth-state", "sync-setup-state", "sync-syncnow-state"];
- Assert.ok(all.indexOf(broadcasterId) >= 0, "valid id");
- for (let check of all) {
- let eltHidden = document.getElementById(check).hidden;
- Assert.equal(eltHidden, check == broadcasterId ? false : true, check);
- }
-}
-
-function promiseObserver(topic) {
- return new Promise(resolve => {
- let obs = (aSubject, aTopic, aData) => {
- Services.obs.removeObserver(obs, aTopic);
- resolve(aSubject);
- }
- Services.obs.addObserver(obs, topic, false);
- });
-}
-
-function checkButtonTooltips(stringPrefix) {
- for (let butId of ["PanelUI-remotetabs-syncnow", "PanelUI-fxa-icon"]) {
- let text = document.getElementById(butId).getAttribute("tooltiptext");
- let desc = `Text is "${text}", expecting it to start with "${stringPrefix}"`
- Assert.ok(text.startsWith(stringPrefix), desc);
- }
-}
-
-add_task(function* prepare() {
- // add the Sync button to the toolbar so we can get it!
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_NAVBAR);
- registerCleanupFunction(() => {
- CustomizableUI.removeWidgetFromArea("sync-button");
- });
-
- let xps = Components.classes["@mozilla.org/weave/service;1"]
- .getService(Components.interfaces.nsISupports)
- .wrappedJSObject;
- yield xps.whenLoaded();
- // Put Sync and the UI into a known state.
- Weave.Status.login = Weave.LOGIN_FAILED_NO_USERNAME;
- yield notifyAndPromiseUIUpdated("weave:service:login:error");
-
- checkBroadcasterVisible("sync-setup-state");
- checkButtonTooltips("Sign In To Sync");
- // mock out the "_needsSetup()" function so we don't short-circuit.
- let oldNeedsSetup = window.gSyncUI._needsSetup;
- window.gSyncUI._needsSetup = () => Promise.resolve(false);
- registerCleanupFunction(() => {
- window.gSyncUI._needsSetup = oldNeedsSetup;
- // and an observer to set the state back to what it should be now we've
- // restored the stub.
- Services.obs.notifyObservers(null, "weave:service:login:finish", null);
- });
- // and a notification to have the state change away from "needs setup"
- yield notifyAndPromiseUIUpdated("weave:service:login:finish");
- checkBroadcasterVisible("sync-syncnow-state");
- // open the sync-button panel so we can check elements in that.
- document.getElementById("sync-button").click();
-});
-
-add_task(function* testSyncNeedsVerification() {
- // mock out the "_needsVerification()" function
- let oldNeedsVerification = window.gSyncUI._needsVerification;
- window.gSyncUI._needsVerification = () => true;
- try {
- // a notification for the state change
- yield notifyAndPromiseUIUpdated("weave:service:login:finish");
- checkButtonTooltips("Verify");
- } finally {
- window.gSyncUI._needsVerification = oldNeedsVerification;
- }
-});
-
-
-add_task(function* testSyncLoginError() {
- checkBroadcasterVisible("sync-syncnow-state");
-
- // Pretend we are in a "login failed" error state
- Weave.Status.sync = Weave.LOGIN_FAILED;
- Weave.Status.login = Weave.LOGIN_FAILED_LOGIN_REJECTED;
- yield notifyAndPromiseUIUpdated("weave:ui:sync:error");
-
- // But the menu *should* reflect the login error.
- checkBroadcasterVisible("sync-reauth-state");
- // The tooltips for the buttons should also reflect it.
- checkButtonTooltips("Reconnect");
-
- // Now pretend we just had a successful login - the error notification should go away.
- Weave.Status.sync = Weave.STATUS_OK;
- Weave.Status.login = Weave.LOGIN_SUCCEEDED;
- yield notifyAndPromiseUIUpdated("weave:service:login:start");
- yield notifyAndPromiseUIUpdated("weave:service:login:finish");
- // The menus should be back to "all good"
- checkBroadcasterVisible("sync-syncnow-state");
-});
-
-function checkButtonsStatus(shouldBeActive) {
- for (let eid of [
- "sync-status", // the broadcaster itself.
- "sync-button", // the main sync button which observes the broadcaster
- "PanelUI-fxa-icon", // the sync icon in the fxa footer that observes it.
- ]) {
- let elt = document.getElementById(eid);
- if (shouldBeActive) {
- Assert.equal(elt.getAttribute("syncstatus"), "active", `${eid} should be active`);
- } else {
- Assert.ok(!elt.hasAttribute("syncstatus"), `${eid} should have no status attr`);
- }
- }
-}
-
-function* testButtonActions(startNotification, endNotification, expectActive = true) {
- checkButtonsStatus(false);
- // pretend a sync is starting.
- yield notifyAndPromiseUIUpdated(startNotification);
- checkButtonsStatus(expectActive);
- // and has stopped
- yield notifyAndPromiseUIUpdated(endNotification);
- checkButtonsStatus(false);
-}
-
-function *doTestButtonActivities() {
- // logins do not "activate" the spinner/button as they may block and make
- // the UI look like Sync is never completing.
- yield testButtonActions("weave:service:login:start", "weave:service:login:finish", false);
- yield testButtonActions("weave:service:login:start", "weave:service:login:error", false);
-
- // But notifications for Sync itself should activate it.
- yield testButtonActions("weave:service:sync:start", "weave:service:sync:finish");
- yield testButtonActions("weave:service:sync:start", "weave:service:sync:error");
-
- // and ensure the counters correctly handle multiple in-flight syncs
- yield notifyAndPromiseUIUpdated("weave:service:sync:start");
- checkButtonsStatus(true);
- // sync stops.
- yield notifyAndPromiseUIUpdated("weave:service:sync:finish");
- // Button should not be active.
- checkButtonsStatus(false);
-}
-
-add_task(function* testButtonActivitiesInNavBar() {
- // check the button's functionality while the button is in the NavBar - which
- // it already is.
- yield doTestButtonActivities();
-});
-
-add_task(function* testFormatLastSyncDateNow() {
- let now = new Date();
- let nowString = gSyncUI.formatLastSyncDate(now);
- Assert.equal(nowString, "Last sync: " + now.toLocaleDateString(undefined, {weekday: 'long', hour: 'numeric', minute: 'numeric'}));
-});
-
-add_task(function* testFormatLastSyncDateMonthAgo() {
- let monthAgo = new Date();
- monthAgo.setMonth(monthAgo.getMonth() - 1);
- let monthAgoString = gSyncUI.formatLastSyncDate(monthAgo);
- Assert.equal(monthAgoString, "Last sync: " + monthAgo.toLocaleDateString(undefined, {month: 'long', day: 'numeric'}));
-});
-
-add_task(function* testButtonActivitiesInPanel() {
- // check the button's functionality while the button is in the panel - it's
- // currently in the NavBar - move it to the panel and open it.
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- yield PanelUI.show();
- try {
- yield doTestButtonActivities();
- } finally {
- PanelUI.hide();
- }
-});
diff --git a/browser/base/content/test/general/browser_tabDrop.js b/browser/base/content/test/general/browser_tabDrop.js
deleted file mode 100644
index fd743e6dc..000000000
--- a/browser/base/content/test/general/browser_tabDrop.js
+++ /dev/null
@@ -1,103 +0,0 @@
-registerCleanupFunction(function* cleanup() {
- while (gBrowser.tabs.length > 1) {
- yield BrowserTestUtils.removeTab(gBrowser.tabs[gBrowser.tabs.length - 1]);
- }
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.removeEngine(engine);
-});
-
-let originalEngine;
-add_task(function* test_setup() {
- // Stop search-engine loads from hitting the network
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-});
-
-add_task(function*() { yield dropText("mochi.test/first", 1); });
-add_task(function*() { yield dropText("javascript:'bad'"); });
-add_task(function*() { yield dropText("jAvascript:'bad'"); });
-add_task(function*() { yield dropText("search this", 1); });
-add_task(function*() { yield dropText("mochi.test/second", 1); });
-add_task(function*() { yield dropText("data:text/html,bad"); });
-add_task(function*() { yield dropText("mochi.test/third", 1); });
-
-// Single text/plain item, with multiple links.
-add_task(function*() { yield dropText("mochi.test/1\nmochi.test/2", 2); });
-add_task(function*() { yield dropText("javascript:'bad1'\nmochi.test/3", 0); });
-add_task(function*() { yield dropText("mochi.test/4\ndata:text/html,bad1", 0); });
-
-// Multiple text/plain items, with single and multiple links.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/5"}],
- [{type: "text/plain",
- data: "mochi.test/6\nmochi.test/7"}]], 3);
-});
-
-// Single text/x-moz-url item, with multiple links.
-// "text/x-moz-url" has titles in even-numbered lines.
-add_task(function*() {
- yield drop([[{type: "text/x-moz-url",
- data: "mochi.test/8\nTITLE8\nmochi.test/9\nTITLE9"}]], 2);
-});
-
-// Single item with multiple types.
-add_task(function*() {
- yield drop([[{type: "text/plain",
- data: "mochi.test/10"},
- {type: "text/x-moz-url",
- data: "mochi.test/11\nTITLE11"}]], 1);
-});
-
-function dropText(text, expectedTabOpenCount=0) {
- return drop([[{type: "text/plain", data: text}]], expectedTabOpenCount);
-}
-
-function* drop(dragData, expectedTabOpenCount=0) {
- let dragDataString = JSON.stringify(dragData);
- info(`Starting test for datagData:${dragDataString}; expectedTabOpenCount:${expectedTabOpenCount}`);
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop");
- let actualTabOpenCount = 0;
- let openedTabs = [];
- let checkCount = function(event) {
- openedTabs.push(event.target);
- actualTabOpenCount++;
- return actualTabOpenCount == expectedTabOpenCount;
- };
- let awaitTabOpen = expectedTabOpenCount && BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen", false, checkCount);
- // A drop type of "link" onto an existing tab would normally trigger a
- // load in that same tab, but tabbrowser code in _getDragTargetTab treats
- // drops on the outer edges of a tab differently (loading a new tab
- // instead). Make events created by synthesizeDrop have all of their
- // coordinates set to 0 (screenX/screenY), so they're treated as drops
- // on the outer edge of the tab, thus they open new tabs.
- var event = {
- clientX: 0,
- clientY: 0,
- screenX: 0,
- screenY: 0,
- };
- EventUtils.synthesizeDrop(gBrowser.selectedTab, gBrowser.selectedTab, dragData, "link", window, undefined, event);
- let tabsOpened = false;
- if (awaitTabOpen) {
- yield awaitTabOpen;
- info("Got TabOpen event");
- tabsOpened = true;
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- }
- is(tabsOpened, !!expectedTabOpenCount, `Tabs for ${dragDataString} should only open if any of dropped items are valid`);
-
- yield awaitDrop;
- ok(true, "Got drop event");
-}
diff --git a/browser/base/content/test/general/browser_tabReorder.js b/browser/base/content/test/general/browser_tabReorder.js
deleted file mode 100644
index 9e0503e95..000000000
--- a/browser/base/content/test/general/browser_tabReorder.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- let initialTabsLength = gBrowser.tabs.length;
-
- let newTab1 = gBrowser.selectedTab = gBrowser.addTab("about:robots", {skipAnimation: true});
- let newTab2 = gBrowser.selectedTab = gBrowser.addTab("about:about", {skipAnimation: true});
- let newTab3 = gBrowser.selectedTab = gBrowser.addTab("about:config", {skipAnimation: true});
- registerCleanupFunction(function () {
- while (gBrowser.tabs.length > initialTabsLength) {
- gBrowser.removeTab(gBrowser.tabs[initialTabsLength]);
- }
- });
-
- is(gBrowser.tabs.length, initialTabsLength + 3, "new tabs are opened");
- is(gBrowser.tabs[initialTabsLength], newTab1, "newTab1 position is correct");
- is(gBrowser.tabs[initialTabsLength + 1], newTab2, "newTab2 position is correct");
- is(gBrowser.tabs[initialTabsLength + 2], newTab3, "newTab3 position is correct");
-
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- function dragAndDrop(tab1, tab2, copy) {
- let rect = tab2.getBoundingClientRect();
- let event = {
- ctrlKey: copy,
- altKey: copy,
- clientX: rect.left + rect.width / 2 + 10,
- clientY: rect.top + rect.height / 2,
- };
-
- EventUtils.synthesizeDrop(tab1, tab2, null, copy ? "copy" : "move", window, window, event);
- }
-
- dragAndDrop(newTab1, newTab2, false);
- is(gBrowser.tabs.length, initialTabsLength + 3, "tabs are still there");
- is(gBrowser.tabs[initialTabsLength], newTab2, "newTab2 and newTab1 are swapped");
- is(gBrowser.tabs[initialTabsLength + 1], newTab1, "newTab1 and newTab2 are swapped");
- is(gBrowser.tabs[initialTabsLength + 2], newTab3, "newTab3 stays same place");
-
- dragAndDrop(newTab2, newTab1, true);
- is(gBrowser.tabs.length, initialTabsLength + 4, "a tab is duplicated");
- is(gBrowser.tabs[initialTabsLength], newTab2, "newTab2 stays same place");
- is(gBrowser.tabs[initialTabsLength + 1], newTab1, "newTab1 stays same place");
- is(gBrowser.tabs[initialTabsLength + 3], newTab3, "a new tab is inserted before newTab3");
-}
diff --git a/browser/base/content/test/general/browser_tab_close_dependent_window.js b/browser/base/content/test/general/browser_tab_close_dependent_window.js
deleted file mode 100644
index ab8a960ac..000000000
--- a/browser/base/content/test/general/browser_tab_close_dependent_window.js
+++ /dev/null
@@ -1,24 +0,0 @@
-"use strict";
-
-add_task(function* closing_tab_with_dependents_should_close_window() {
- info("Opening window");
- let win = yield BrowserTestUtils.openNewBrowserWindow();
-
- info("Opening tab with data URI");
- let tab = yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, `data:text/html,<html%20onclick="W=window.open()"><body%20onbeforeunload="W.close()">`);
- info("Closing original tab in this window.");
- yield BrowserTestUtils.removeTab(win.gBrowser.tabs[0]);
- info("Clicking into the window");
- let depTabOpened = BrowserTestUtils.waitForEvent(win.gBrowser.tabContainer, "TabOpen");
- yield BrowserTestUtils.synthesizeMouse("html", 0, 0, {}, tab.linkedBrowser);
-
- let openedTab = (yield depTabOpened).target;
- info("Got opened tab");
-
- let windowClosedPromise = BrowserTestUtils.windowClosed(win);
- yield BrowserTestUtils.removeTab(tab);
- is(Cu.isDeadWrapper(openedTab) || openedTab.linkedBrowser == null, true, "Opened tab should also have closed");
- info("If we timeout now, the window failed to close - that shouldn't happen!");
- yield windowClosedPromise;
-});
-
diff --git a/browser/base/content/test/general/browser_tab_detach_restore.js b/browser/base/content/test/general/browser_tab_detach_restore.js
deleted file mode 100644
index d482edc26..000000000
--- a/browser/base/content/test/general/browser_tab_detach_restore.js
+++ /dev/null
@@ -1,34 +0,0 @@
-"use strict";
-
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
-add_task(function*() {
- let uri = "http://example.com/browser/browser/base/content/test/general/dummy_page.html";
-
- // Clear out the closed windows set to start
- while (SessionStore.getClosedWindowCount() > 0)
- SessionStore.forgetClosedWindow(0);
-
- let tab = gBrowser.addTab();
- tab.linkedBrowser.loadURI(uri);
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
-
- let key = tab.linkedBrowser.permanentKey;
- let win = gBrowser.replaceTabWithWindow(tab);
- yield new Promise(resolve => whenDelayedStartupFinished(win, resolve));
-
- is(win.gBrowser.selectedBrowser.permanentKey, key, "Should have properly copied the permanentKey");
- yield BrowserTestUtils.closeWindow(win);
-
- is(SessionStore.getClosedWindowCount(), 1, "Should have restore data for the closed window");
-
- win = SessionStore.undoCloseWindow(0);
- yield BrowserTestUtils.waitForEvent(win, "load");
- yield BrowserTestUtils.waitForEvent(win.gBrowser.tabs[0], "SSTabRestored");
-
- is(win.gBrowser.tabs.length, 1, "Should have restored one tab");
- is(win.gBrowser.selectedBrowser.currentURI.spec, uri, "Should have restored the right page");
-
- yield promiseWindowClosed(win);
-});
diff --git a/browser/base/content/test/general/browser_tab_drag_drop_perwindow.js b/browser/base/content/test/general/browser_tab_drag_drop_perwindow.js
deleted file mode 100644
index a8fc34083..000000000
--- a/browser/base/content/test/general/browser_tab_drag_drop_perwindow.js
+++ /dev/null
@@ -1,216 +0,0 @@
-/* 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/. */
-
-requestLongerTimeout(2);
-
-const EVENTUTILS_URL = "chrome://mochikit/content/tests/SimpleTest/EventUtils.js";
-var EventUtils = {};
-
-Services.scriptloader.loadSubScript(EVENTUTILS_URL, EventUtils);
-
-/**
- * Tests that tabs from Private Browsing windows cannot be dragged
- * into non-private windows, and vice-versa.
- */
-add_task(function* test_dragging_private_windows() {
- let normalWin = yield BrowserTestUtils.openNewBrowserWindow();
- let privateWin =
- yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- let normalTab =
- yield BrowserTestUtils.openNewForegroundTab(normalWin.gBrowser);
- let privateTab =
- yield BrowserTestUtils.openNewForegroundTab(privateWin.gBrowser);
-
- let effect = EventUtils.synthesizeDrop(normalTab, privateTab,
- [[{type: TAB_DROP_TYPE, data: normalTab}]],
- null, normalWin, privateWin);
- is(effect, "none", "Should not be able to drag a normal tab to a private window");
-
- effect = EventUtils.synthesizeDrop(privateTab, normalTab,
- [[{type: TAB_DROP_TYPE, data: privateTab}]],
- null, privateWin, normalWin);
- is(effect, "none", "Should not be able to drag a private tab to a normal window");
-
- normalWin.gBrowser.swapBrowsersAndCloseOther(normalTab, privateTab);
- is(normalWin.gBrowser.tabs.length, 2,
- "Prevent moving a normal tab to a private tabbrowser");
- is(privateWin.gBrowser.tabs.length, 2,
- "Prevent accepting a normal tab in a private tabbrowser");
-
- privateWin.gBrowser.swapBrowsersAndCloseOther(privateTab, normalTab);
- is(privateWin.gBrowser.tabs.length, 2,
- "Prevent moving a private tab to a normal tabbrowser");
- is(normalWin.gBrowser.tabs.length, 2,
- "Prevent accepting a private tab in a normal tabbrowser");
-
- yield BrowserTestUtils.closeWindow(normalWin);
- yield BrowserTestUtils.closeWindow(privateWin);
-});
-
-/**
- * Tests that tabs from e10s windows cannot be dragged into non-e10s
- * windows, and vice-versa.
- */
-add_task(function* test_dragging_e10s_windows() {
- if (!gMultiProcessBrowser) {
- return;
- }
-
- let remoteWin = yield BrowserTestUtils.openNewBrowserWindow({remote: true});
- let nonRemoteWin = yield BrowserTestUtils.openNewBrowserWindow({remote: false});
-
- let remoteTab =
- yield BrowserTestUtils.openNewForegroundTab(remoteWin.gBrowser);
- let nonRemoteTab =
- yield BrowserTestUtils.openNewForegroundTab(nonRemoteWin.gBrowser);
-
- let effect = EventUtils.synthesizeDrop(remoteTab, nonRemoteTab,
- [[{type: TAB_DROP_TYPE, data: remoteTab}]],
- null, remoteWin, nonRemoteWin);
- is(effect, "none", "Should not be able to drag a remote tab to a non-e10s window");
-
- effect = EventUtils.synthesizeDrop(nonRemoteTab, remoteTab,
- [[{type: TAB_DROP_TYPE, data: nonRemoteTab}]],
- null, nonRemoteWin, remoteWin);
- is(effect, "none", "Should not be able to drag a non-remote tab to an e10s window");
-
- remoteWin.gBrowser.swapBrowsersAndCloseOther(remoteTab, nonRemoteTab);
- is(remoteWin.gBrowser.tabs.length, 2,
- "Prevent moving a normal tab to a private tabbrowser");
- is(nonRemoteWin.gBrowser.tabs.length, 2,
- "Prevent accepting a normal tab in a private tabbrowser");
-
- nonRemoteWin.gBrowser.swapBrowsersAndCloseOther(nonRemoteTab, remoteTab);
- is(nonRemoteWin.gBrowser.tabs.length, 2,
- "Prevent moving a private tab to a normal tabbrowser");
- is(remoteWin.gBrowser.tabs.length, 2,
- "Prevent accepting a private tab in a normal tabbrowser");
-
- yield BrowserTestUtils.closeWindow(remoteWin);
- yield BrowserTestUtils.closeWindow(nonRemoteWin);
-});
-
-/**
- * Tests that remoteness-blacklisted tabs from e10s windows can
- * be dragged between e10s windows.
- */
-add_task(function* test_dragging_blacklisted() {
- if (!gMultiProcessBrowser) {
- return;
- }
-
- let remoteWin1 = yield BrowserTestUtils.openNewBrowserWindow({remote: true});
- remoteWin1.gBrowser.myID = "remoteWin1";
- let remoteWin2 = yield BrowserTestUtils.openNewBrowserWindow({remote: true});
- remoteWin2.gBrowser.myID = "remoteWin2";
-
- // Anything under chrome://mochitests/content/ will be blacklisted, and
- // open in the parent process.
- const BLACKLISTED_URL = getRootDirectory(gTestPath) +
- "browser_tab_drag_drop_perwindow.js";
- let blacklistedTab =
- yield BrowserTestUtils.openNewForegroundTab(remoteWin1.gBrowser,
- BLACKLISTED_URL);
-
- ok(blacklistedTab.linkedBrowser, "Newly created tab should have a browser.");
-
- ok(!blacklistedTab.linkedBrowser.isRemoteBrowser,
- `Expected a non-remote browser for URL: ${BLACKLISTED_URL}`);
-
- let otherTab =
- yield BrowserTestUtils.openNewForegroundTab(remoteWin2.gBrowser);
-
- let effect = EventUtils.synthesizeDrop(blacklistedTab, otherTab,
- [[{type: TAB_DROP_TYPE, data: blacklistedTab}]],
- null, remoteWin1, remoteWin2);
- is(effect, "move", "Should be able to drag the blacklisted tab.");
-
- // The synthesized drop should also do the work of swapping the
- // browsers, so no need to call swapBrowsersAndCloseOther manually.
-
- is(remoteWin1.gBrowser.tabs.length, 1,
- "Should have moved the blacklisted tab out of this window.");
- is(remoteWin2.gBrowser.tabs.length, 3,
- "Should have inserted the blacklisted tab into the other window.");
-
- // The currently selected tab in the second window should be the
- // one we just dragged in.
- let draggedBrowser = remoteWin2.gBrowser.selectedBrowser;
- ok(!draggedBrowser.isRemoteBrowser,
- "The browser we just dragged in should not be remote.");
-
- is(draggedBrowser.currentURI.spec, BLACKLISTED_URL,
- `Expected the URL of the dragged in tab to be ${BLACKLISTED_URL}`);
-
- yield BrowserTestUtils.closeWindow(remoteWin1);
- yield BrowserTestUtils.closeWindow(remoteWin2);
-});
-
-
-/**
- * Tests that tabs dragged between windows dispatch TabOpen and TabClose
- * events with the appropriate adoption details.
- */
-add_task(function* test_dragging_adoption_events() {
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(win1.gBrowser);
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(win2.gBrowser);
-
- let awaitCloseEvent = BrowserTestUtils.waitForEvent(tab1, "TabClose");
- let awaitOpenEvent = BrowserTestUtils.waitForEvent(win2, "TabOpen");
-
- let effect = EventUtils.synthesizeDrop(tab1, tab2,
- [[{type: TAB_DROP_TYPE, data: tab1}]],
- null, win1, win2);
- is(effect, "move", "Tab should be moved from win1 to win2.");
-
- let closeEvent = yield awaitCloseEvent;
- let openEvent = yield awaitOpenEvent;
-
- is(openEvent.detail.adoptedTab, tab1, "New tab adopted old tab");
- is(closeEvent.detail.adoptedBy, openEvent.target, "Old tab adopted by new tab");
-
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
-});
-
-
-/**
- * Tests that per-site zoom settings remain active after a tab is
- * dragged between windows.
- */
-add_task(function* test_dragging_zoom_handling() {
- const ZOOM_FACTOR = 1.62;
-
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(win1.gBrowser);
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(win2.gBrowser,
- "http://example.com/");
-
- win2.FullZoom.setZoom(ZOOM_FACTOR);
- FullZoomHelper.zoomTest(tab2, ZOOM_FACTOR,
- "Original tab should have correct zoom factor");
-
- let effect = EventUtils.synthesizeDrop(tab2, tab1,
- [[{type: TAB_DROP_TYPE, data: tab2}]],
- null, win2, win1);
- is(effect, "move", "Tab should be moved from win2 to win1.");
-
- // Delay slightly to make sure we've finished executing any promise
- // chains in the zoom code.
- yield new Promise(resolve => setTimeout(resolve, 0));
-
- FullZoomHelper.zoomTest(win1.gBrowser.selectedTab, ZOOM_FACTOR,
- "Dragged tab should have correct zoom factor");
-
- win1.FullZoom.reset();
-
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
-});
diff --git a/browser/base/content/test/general/browser_tab_dragdrop.js b/browser/base/content/test/general/browser_tab_dragdrop.js
deleted file mode 100644
index cfe996e1e..000000000
--- a/browser/base/content/test/general/browser_tab_dragdrop.js
+++ /dev/null
@@ -1,186 +0,0 @@
-function swapTabsAndCloseOther(a, b) {
- gBrowser.swapBrowsersAndCloseOther(gBrowser.tabs[b], gBrowser.tabs[a]);
-}
-
-var getClicks = function(tab) {
- return ContentTask.spawn(tab.linkedBrowser, {}, function() {
- return content.wrappedJSObject.clicks;
- });
-}
-
-var clickTest = Task.async(function*(tab) {
- let clicks = yield getClicks(tab);
-
- yield ContentTask.spawn(tab.linkedBrowser, {}, function() {
- let target = content.document.body;
- let rect = target.getBoundingClientRect();
- let left = (rect.left + rect.right) / 2;
- let top = (rect.top + rect.bottom) / 2;
-
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- let newClicks = yield getClicks(tab);
- is(newClicks, clicks + 1, "adding 1 more click on BODY");
-});
-
-function loadURI(tab, url) {
- tab.linkedBrowser.loadURI(url);
- return BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-}
-
-// Creates a framescript which caches the current object value from the plugin
-// in the page. checkObjectValue below verifies that the framescript is still
-// active for the browser and that the cached value matches that from the plugin
-// in the page which tells us the plugin hasn't been reinitialized.
-function* cacheObjectValue(browser) {
- yield ContentTask.spawn(browser, null, function*() {
- let plugin = content.document.wrappedJSObject.body.firstChild;
- info(`plugin is ${plugin}`);
- let win = content.document.defaultView;
- info(`win is ${win}`);
- win.objectValue = plugin.getObjectValue();
- info(`got objectValue: ${win.objectValue}`);
- win.checkObjectValueListener = () => {
- let result;
- let exception;
- try {
- result = plugin.checkObjectValue(win.objectValue);
- } catch (e) {
- exception = e.toString();
- }
- info(`sending plugin.checkObjectValue(objectValue): ${result}`);
- sendAsyncMessage("Test:CheckObjectValueResult", {
- result,
- exception
- });
- };
-
- addMessageListener("Test:CheckObjectValue", win.checkObjectValueListener);
- });
-}
-
-// Note, can't run this via registerCleanupFunction because it needs the
-// browser to still be alive and have a messageManager.
-function* cleanupObjectValue(browser) {
- info("entered cleanupObjectValue")
- yield ContentTask.spawn(browser, null, function*() {
- info("in cleanup function");
- let win = content.document.defaultView;
- info(`about to delete objectValue: ${win.objectValue}`);
- delete win.objectValue;
- removeMessageListener("Test:CheckObjectValue", win.checkObjectValueListener);
- info(`about to delete checkObjectValueListener: ${win.checkObjectValueListener}`);
- delete win.checkObjectValueListener;
- info(`deleted objectValue (${win.objectValue}) and checkObjectValueListener (${win.checkObjectValueListener})`);
- });
- info("exiting cleanupObjectValue")
-}
-
-// See the notes for cacheObjectValue above.
-function checkObjectValue(browser) {
- let mm = browser.messageManager;
-
- return new Promise((resolve, reject) => {
- let listener = ({ data }) => {
- mm.removeMessageListener("Test:CheckObjectValueResult", listener);
- if (data.result === null) {
- ok(false, "checkObjectValue threw an exception: " + data.exception);
- reject(data.exception);
- } else {
- resolve(data.result);
- }
- };
-
- mm.addMessageListener("Test:CheckObjectValueResult", listener);
- mm.sendAsyncMessage("Test:CheckObjectValue");
- });
-}
-
-add_task(function*() {
- let embed = '<embed type="application/x-test" allowscriptaccess="always" allowfullscreen="true" wmode="window" width="640" height="480"></embed>'
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED);
-
- // create a few tabs
- let tabs = [
- gBrowser.tabs[0],
- gBrowser.addTab("about:blank", {skipAnimation: true}),
- gBrowser.addTab("about:blank", {skipAnimation: true}),
- gBrowser.addTab("about:blank", {skipAnimation: true}),
- gBrowser.addTab("about:blank", {skipAnimation: true})
- ];
-
- // Initially 0 1 2 3 4
- yield loadURI(tabs[1], "data:text/html;charset=utf-8,<title>tab1</title><body>tab1<iframe>");
- yield loadURI(tabs[2], "data:text/plain;charset=utf-8,tab2");
- yield loadURI(tabs[3], "data:text/html;charset=utf-8,<title>tab3</title><body>tab3<iframe>");
- yield loadURI(tabs[4], "data:text/html;charset=utf-8,<body onload='clicks=0' onclick='++clicks'>"+embed);
- yield BrowserTestUtils.switchTab(gBrowser, tabs[3]);
-
- swapTabsAndCloseOther(2, 3); // now: 0 1 2 4
- is(gBrowser.tabs[1], tabs[1], "tab1");
- is(gBrowser.tabs[2], tabs[3], "tab3");
- is(gBrowser.tabs[3], tabs[4], "tab4");
- delete tabs[2];
-
- info("about to cacheObjectValue")
- yield cacheObjectValue(tabs[4].linkedBrowser);
- info("just finished cacheObjectValue")
-
- swapTabsAndCloseOther(3, 2); // now: 0 1 4
- is(Array.prototype.indexOf.call(gBrowser.tabs, gBrowser.selectedTab), 2,
- "The third tab should be selected");
- delete tabs[4];
-
-
- ok((yield checkObjectValue(gBrowser.tabs[2].linkedBrowser)), "same plugin instance");
-
- is(gBrowser.tabs[1], tabs[1], "tab1");
- is(gBrowser.tabs[2], tabs[3], "tab4");
-
- let clicks = yield getClicks(gBrowser.tabs[2]);
- is(clicks, 0, "no click on BODY so far");
- yield clickTest(gBrowser.tabs[2]);
-
- swapTabsAndCloseOther(2, 1); // now: 0 4
- is(gBrowser.tabs[1], tabs[1], "tab1");
- delete tabs[3];
-
- ok((yield checkObjectValue(gBrowser.tabs[1].linkedBrowser)), "same plugin instance");
- yield cleanupObjectValue(gBrowser.tabs[1].linkedBrowser);
-
- yield clickTest(gBrowser.tabs[1]);
-
- // Load a new document (about:blank) in tab4, then detach that tab into a new window.
- // In the new window, navigate back to the original document and click on its <body>,
- // verify that its onclick was called.
- is(Array.prototype.indexOf.call(gBrowser.tabs, gBrowser.selectedTab), 1,
- "The second tab should be selected");
- is(gBrowser.tabs[1], tabs[1],
- "The second tab in gBrowser.tabs should be equal to the second tab in our array");
- is(gBrowser.selectedTab, tabs[1],
- "The second tab in our array is the selected tab");
- yield loadURI(tabs[1], "about:blank");
- let key = tabs[1].linkedBrowser.permanentKey;
-
- let win = gBrowser.replaceTabWithWindow(tabs[1]);
- yield new Promise(resolve => whenDelayedStartupFinished(win, resolve));
- delete tabs[1];
-
- // Verify that the original window now only has the initial tab left in it.
- is(gBrowser.tabs[0], tabs[0], "tab0");
- is(gBrowser.tabs[0].linkedBrowser.currentURI.spec, "about:blank", "tab0 uri");
-
- let tab = win.gBrowser.tabs[0];
- is(tab.linkedBrowser.permanentKey, key, "Should have kept the key");
-
- let awaitPageShow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- win.gBrowser.goBack();
- yield awaitPageShow;
-
- yield clickTest(tab);
- promiseWindowClosed(win);
-});
diff --git a/browser/base/content/test/general/browser_tab_dragdrop2.js b/browser/base/content/test/general/browser_tab_dragdrop2.js
deleted file mode 100644
index 2ab622d8b..000000000
--- a/browser/base/content/test/general/browser_tab_dragdrop2.js
+++ /dev/null
@@ -1,57 +0,0 @@
-"use strict";
-
-const ROOT = getRootDirectory(gTestPath);
-const URI = ROOT + "browser_tab_dragdrop2_frame1.xul";
-
-// Load the test page (which runs some child popup tests) in a new window.
-// After the tests were run, tear off the tab into a new window and run popup
-// tests a second time. We don't care about tests results, exceptions and
-// crashes will be caught.
-add_task(function* () {
- // Open a new window.
- let args = "chrome,all,dialog=no";
- let win = window.openDialog(getBrowserURL(), "_blank", args, URI);
-
- // Wait until the tests were run.
- yield promiseTestsDone(win);
- ok(true, "tests succeeded");
-
- // Create a second tab so that we can move the original one out.
- win.gBrowser.addTab("about:blank", {skipAnimation: true});
-
- // Tear off the original tab.
- let browser = win.gBrowser.selectedBrowser;
- let tabClosed = promiseWaitForEvent(browser, "pagehide", true);
- let win2 = win.gBrowser.replaceTabWithWindow(win.gBrowser.tabs[0]);
-
- // Add a 'TestsDone' event listener to ensure that the docShells is properly
- // swapped to the new window instead of the page being loaded again. If this
- // works fine we should *NOT* see a TestsDone event.
- let onTestsDone = () => ok(false, "shouldn't run tests when tearing off");
- win2.addEventListener("TestsDone", onTestsDone);
-
- // Wait until the original tab is gone and the new window is ready.
- yield Promise.all([tabClosed, promiseDelayedStartupFinished(win2)]);
-
- // Remove the 'TestsDone' event listener as now
- // we're kicking off a new test run manually.
- win2.removeEventListener("TestsDone", onTestsDone);
-
- // Run tests once again.
- let promise = promiseTestsDone(win2);
- win2.content.test_panels();
- yield promise;
- ok(true, "tests succeeded a second time");
-
- // Cleanup.
- yield promiseWindowClosed(win2);
- yield promiseWindowClosed(win);
-});
-
-function promiseTestsDone(win) {
- return promiseWaitForEvent(win, "TestsDone");
-}
-
-function promiseDelayedStartupFinished(win) {
- return new Promise(resolve => whenDelayedStartupFinished(win, resolve));
-}
diff --git a/browser/base/content/test/general/browser_tab_dragdrop2_frame1.xul b/browser/base/content/test/general/browser_tab_dragdrop2_frame1.xul
deleted file mode 100644
index d11709942..000000000
--- a/browser/base/content/test/general/browser_tab_dragdrop2_frame1.xul
+++ /dev/null
@@ -1,169 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<!--
- XUL Widget Test for panels
- -->
-<window title="Titlebar" width="200" height="200"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
-
-<tree id="tree" seltype="single" width="100" height="100">
- <treecols>
- <treecol flex="1"/>
- <treecol flex="1"/>
- </treecols>
- <treechildren id="treechildren">
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- <treeitem><treerow><treecell label="One"/><treecell label="Two"/></treerow></treeitem>
- </treechildren>
-</tree>
-
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml" style="height: 300px; overflow: auto;"/>
-
- <!-- test code goes here -->
- <script type="application/javascript"><![CDATA[
-
-SimpleTest.waitForExplicitFinish();
-
-var currentTest = null;
-
-var i, waitSteps;
-var my_debug = false;
-function test_panels()
-{
- i = waitSteps = 0;
- checkTreeCoords();
-
- addEventListener("popupshown", popupShown, false);
- addEventListener("popuphidden", nextTest, false);
- return nextTest();
-}
-
-function nextTest()
-{
- ok(true,"popuphidden " + i)
- if (i == tests.length) {
- let details = {bubbles: true, cancelable: false};
- document.dispatchEvent(new CustomEvent("TestsDone", details));
- return i;
- }
-
- currentTest = tests[i];
- var panel = createPanel(currentTest.attrs);
- SimpleTest.waitForFocus(() => currentTest.test(panel));
- return i;
-}
-
-function popupShown(event)
-{
- var panel = event.target;
- if (waitSteps > 0 && navigator.platform.indexOf("Linux") >= 0 &&
- panel.boxObject.screenY == 210) {
- waitSteps--;
- setTimeout(popupShown, 10, event);
- return;
- }
- ++i;
-
- currentTest.result(currentTest.testname + " ", panel);
- panel.hidePopup();
-}
-
-function createPanel(attrs)
-{
- var panel = document.createElement("panel");
- for (var a in attrs) {
- panel.setAttribute(a, attrs[a]);
- }
-
- var button = document.createElement("button");
- panel.appendChild(button);
- button.label = "OK";
- button.width = 120;
- button.height = 40;
- button.setAttribute("style", "-moz-appearance: none; border: 0; margin: 0;");
- panel.setAttribute("style", "-moz-appearance: none; border: 0; margin: 0;");
- return document.documentElement.appendChild(panel);
-}
-
-function checkTreeCoords()
-{
- var tree = $("tree");
- var treechildren = $("treechildren");
- tree.currentIndex = 0;
- tree.treeBoxObject.scrollToRow(0);
- synthesizeMouse(treechildren, 10, tree.treeBoxObject.rowHeight + 2, { });
-
- tree.treeBoxObject.scrollToRow(2);
- synthesizeMouse(treechildren, 10, tree.treeBoxObject.rowHeight + 2, { });
-}
-
-var tests = [
- {
- testname: "normal panel",
- attrs: { },
- test: function(panel) {
- panel.openPopupAtScreen(200, 210);
- },
- result: function(testname, panel) {
- if (my_debug) alert(testname);
- var panelrect = panel.getBoundingClientRect();
- }
- },
- {
- // only noautohide panels support titlebars, so one shouldn't be shown here
- testname: "autohide panel with titlebar",
- attrs: { titlebar: "normal" },
- test: function(panel) {
- panel.openPopupAtScreen(200, 210);
- },
- result: function(testname, panel) {
- if (my_debug) alert(testname);
- var panelrect = panel.getBoundingClientRect();
- }
- },
- {
- testname: "noautohide panel with titlebar",
- attrs: { noautohide: true, titlebar: "normal" },
- test: function(panel) {
- waitSteps = 25;
- panel.openPopupAtScreen(200, 210);
- },
- result: function(testname, panel) {
- if (my_debug) alert(testname);
- var panelrect = panel.getBoundingClientRect();
-
- var gotMouseEvent = false;
- function mouseMoved(event)
- {
- gotMouseEvent = true;
- }
-
- panel.addEventListener("mousemove", mouseMoved, true);
- synthesizeMouse(panel, 10, 10, { type: "mousemove" });
- panel.removeEventListener("mousemove", mouseMoved, true);
-
- var tree = $("tree");
- tree.currentIndex = 0;
- panel.appendChild(tree);
- checkTreeCoords();
- }
- }
-];
-
-SimpleTest.waitForFocus(test_panels);
-
-]]>
-</script>
-
-</window>
diff --git a/browser/base/content/test/general/browser_tabbar_big_widgets.js b/browser/base/content/test/general/browser_tabbar_big_widgets.js
deleted file mode 100644
index 7a4c45138..000000000
--- a/browser/base/content/test/general/browser_tabbar_big_widgets.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const kButtonId = "test-tabbar-size-with-large-buttons";
-
-function test() {
- registerCleanupFunction(cleanup);
- let titlebar = document.getElementById("titlebar");
- let originalHeight = titlebar.getBoundingClientRect().height;
- let button = document.createElement("toolbarbutton");
- button.id = kButtonId;
- button.setAttribute("style", "min-height: 100px");
- gNavToolbox.palette.appendChild(button);
- CustomizableUI.addWidgetToArea(kButtonId, CustomizableUI.AREA_TABSTRIP);
- let currentHeight = titlebar.getBoundingClientRect().height;
- ok(currentHeight > originalHeight, "Titlebar should have grown");
- CustomizableUI.removeWidgetFromArea(kButtonId);
- currentHeight = titlebar.getBoundingClientRect().height;
- is(currentHeight, originalHeight, "Titlebar should have gone back to its original size.");
-}
-
-function cleanup() {
- let btn = document.getElementById(kButtonId);
- if (btn) {
- btn.remove();
- }
-}
-
diff --git a/browser/base/content/test/general/browser_tabfocus.js b/browser/base/content/test/general/browser_tabfocus.js
deleted file mode 100644
index 4042421e8..000000000
--- a/browser/base/content/test/general/browser_tabfocus.js
+++ /dev/null
@@ -1,565 +0,0 @@
-/*
- * This test checks that focus is adjusted properly when switching tabs.
- */
-
-var testPage1 = "<html id='html1'><body id='body1'><button id='button1'>Tab 1</button></body></html>";
-var testPage2 = "<html id='html2'><body id='body2'><button id='button2'>Tab 2</button></body></html>";
-var testPage3 = "<html id='html3'><body id='body3'><button id='button3'>Tab 3</button></body></html>";
-
-const fm = Services.focus;
-
-function EventStore() {
- this["main-window"] = [];
- this["window1"] = [];
- this["window2"] = [];
-}
-
-EventStore.prototype = {
- "push": function (event) {
- if (event.indexOf("1") > -1) {
- this["window1"].push(event);
- } else if (event.indexOf("2") > -1) {
- this["window2"].push(event);
- } else {
- this["main-window"].push(event);
- }
- }
-}
-
-var tab1 = null;
-var tab2 = null;
-var browser1 = null;
-var browser2 = null;
-var _lastfocus;
-var _lastfocuswindow = null;
-var actualEvents = new EventStore();
-var expectedEvents = new EventStore();
-var currentTestName = "";
-var _expectedElement = null;
-var _expectedWindow = null;
-
-var currentPromiseResolver = null;
-
-function* getFocusedElementForBrowser(browser, dontCheckExtraFocus = false)
-{
- if (gMultiProcessBrowser) {
- return new Promise((resolve, reject) => {
- messageManager.addMessageListener("Browser:GetCurrentFocus", function getCurrentFocus(message) {
- messageManager.removeMessageListener("Browser:GetCurrentFocus", getCurrentFocus);
- resolve(message.data.details);
- });
-
- // The dontCheckExtraFocus flag is used to indicate not to check some
- // additional focus related properties. This is needed as both URLs are
- // loaded using the same child process and share focus managers.
- browser.messageManager.sendAsyncMessage("Browser:GetFocusedElement",
- { dontCheckExtraFocus : dontCheckExtraFocus });
- });
- }
- var focusedWindow = {};
- var node = fm.getFocusedElementForWindow(browser.contentWindow, false, focusedWindow);
- return "Focus is " + (node ? node.id : "<none>");
-}
-
-function focusInChild()
-{
- var contentFM = Components.classes["@mozilla.org/focus-manager;1"].
- getService(Components.interfaces.nsIFocusManager);
-
- function getWindowDocId(target)
- {
- return (String(target.location).indexOf("1") >= 0) ? "window1" : "window2";
- }
-
- function eventListener(event) {
- var id;
- if (event.target instanceof Components.interfaces.nsIDOMWindow)
- id = getWindowDocId(event.originalTarget) + "-window";
- else if (event.target instanceof Components.interfaces.nsIDOMDocument)
- id = getWindowDocId(event.originalTarget) + "-document";
- else
- id = event.originalTarget.id;
- sendSyncMessage("Browser:FocusChanged", { details : event.type + ": " + id });
- }
-
- addEventListener("focus", eventListener, true);
- addEventListener("blur", eventListener, true);
-
- addMessageListener("Browser:ChangeFocus", function changeFocus(message) {
- content.document.getElementById(message.data.id)[message.data.type]();
- });
-
- addMessageListener("Browser:GetFocusedElement", function getFocusedElement(message) {
- var focusedWindow = {};
- var node = contentFM.getFocusedElementForWindow(content, false, focusedWindow);
- var details = "Focus is " + (node ? node.id : "<none>");
-
- /* Check focus manager properties. Add an error onto the string if they are
- not what is expected which will cause matching to fail in the parent process. */
- let doc = content.document;
- if (!message.data.dontCheckExtraFocus) {
- if (contentFM.focusedElement != node) {
- details += "<ERROR: focusedElement doesn't match>";
- }
- if (contentFM.focusedWindow && contentFM.focusedWindow != content) {
- details += "<ERROR: focusedWindow doesn't match>";
- }
- if ((contentFM.focusedWindow == content) != doc.hasFocus()) {
- details += "<ERROR: child hasFocus() is not correct>";
- }
- if ((contentFM.focusedElement && doc.activeElement != contentFM.focusedElement) ||
- (!contentFM.focusedElement && doc.activeElement != doc.body)) {
- details += "<ERROR: child activeElement is not correct>";
- }
- }
-
- sendSyncMessage("Browser:GetCurrentFocus", { details : details });
- });
-}
-
-function focusElementInChild(elementid, type)
-{
- let browser = (elementid.indexOf("1") >= 0) ? browser1 : browser2;
- if (gMultiProcessBrowser) {
- browser.messageManager.sendAsyncMessage("Browser:ChangeFocus",
- { id: elementid, type: type });
- }
- else {
- browser.contentDocument.getElementById(elementid)[type]();
- }
-}
-
-add_task(function*() {
- tab1 = gBrowser.addTab();
- browser1 = gBrowser.getBrowserForTab(tab1);
-
- tab2 = gBrowser.addTab();
- browser2 = gBrowser.getBrowserForTab(tab2);
-
- yield promiseTabLoadEvent(tab1, "data:text/html," + escape(testPage1));
- yield promiseTabLoadEvent(tab2, "data:text/html," + escape(testPage2));
-
- var childFocusScript = "data:,(" + focusInChild.toString() + ")();";
- browser1.messageManager.loadFrameScript(childFocusScript, true);
- browser2.messageManager.loadFrameScript(childFocusScript, true);
-
- gURLBar.focus();
- yield SimpleTest.promiseFocus();
-
- if (gMultiProcessBrowser) {
- messageManager.addMessageListener("Browser:FocusChanged", message => {
- actualEvents.push(message.data.details);
- compareFocusResults();
- });
- }
-
- _lastfocus = "urlbar";
- _lastfocuswindow = "main-window";
-
- window.addEventListener("focus", _browser_tabfocus_test_eventOccured, true);
- window.addEventListener("blur", _browser_tabfocus_test_eventOccured, true);
-
- // make sure that the focus initially starts out blank
- var focusedWindow = {};
-
- let focused = yield getFocusedElementForBrowser(browser1);
- is(focused, "Focus is <none>", "initial focus in tab 1");
-
- focused = yield getFocusedElementForBrowser(browser2);
- is(focused, "Focus is <none>", "initial focus in tab 2");
-
- is(document.activeElement, gURLBar.inputField, "focus after loading two tabs");
-
- yield* expectFocusShiftAfterTabSwitch(tab2, "window2", null, true,
- "after tab change, focus in new tab");
-
- focused = yield getFocusedElementForBrowser(browser2);
- is(focused, "Focus is <none>", "focusedElement after tab change, focus in new tab");
-
- // switching tabs when nothing in the new tab is focused
- // should focus the browser
- yield* expectFocusShiftAfterTabSwitch(tab1, "window1", null, true,
- "after tab change, focus in original tab");
-
- focused = yield getFocusedElementForBrowser(browser1);
- is(focused, "Focus is <none>", "focusedElement after tab change, focus in original tab");
-
- // focusing a button in the current tab should focus it
- yield expectFocusShift(() => focusElementInChild("button1", "focus"),
- "window1", "button1", true,
- "after button focused");
-
- focused = yield getFocusedElementForBrowser(browser1);
- is(focused, "Focus is button1", "focusedElement in first browser after button focused");
-
- // focusing a button in a background tab should not change the actual
- // focus, but should set the focus that would be in that background tab to
- // that button.
- yield expectFocusShift(() => focusElementInChild("button2", "focus"),
- "window1", "button1", false,
- "after button focus in unfocused tab");
-
- focused = yield getFocusedElementForBrowser(browser1, false);
- is(focused, "Focus is button1", "focusedElement in first browser after button focus in unfocused tab");
- focused = yield getFocusedElementForBrowser(browser2, true);
- is(focused, "Focus is button2", "focusedElement in second browser after button focus in unfocused tab");
-
- // switching tabs should now make the button in the other tab focused
- yield* expectFocusShiftAfterTabSwitch(tab2, "window2", "button2", true,
- "after tab change with button focused");
-
- // blurring an element in a background tab should not change the active
- // focus, but should clear the focus in that tab.
- yield expectFocusShift(() => focusElementInChild("button1", "blur"),
- "window2", "button2", false,
- "focusedWindow after blur in unfocused tab");
-
- focused = yield getFocusedElementForBrowser(browser1, true);
- is(focused, "Focus is <none>", "focusedElement in first browser after focus in unfocused tab");
- focused = yield getFocusedElementForBrowser(browser2, false);
- is(focused, "Focus is button2", "focusedElement in second browser after focus in unfocused tab");
-
- // When focus is in the tab bar, it should be retained there
- yield expectFocusShift(() => gBrowser.selectedTab.focus(),
- "main-window", "tab2", true,
- "focusing tab element");
- yield* expectFocusShiftAfterTabSwitch(tab1, "main-window", "tab1", true,
- "tab change when selected tab element was focused");
-
- let switchWaiter;
- if (gMultiProcessBrowser) {
- switchWaiter = new Promise((resolve, reject) => {
- gBrowser.addEventListener("TabSwitchDone", function listener() {
- gBrowser.removeEventListener("TabSwitchDone", listener);
- executeSoon(resolve);
- });
- });
- }
-
- yield* expectFocusShiftAfterTabSwitch(tab2, "main-window", "tab2", true,
- "another tab change when selected tab element was focused");
-
- // When this a remote browser, wait for the paint on the second browser so that
- // any post tab-switching stuff has time to complete before blurring the tab.
- // Otherwise, the _adjustFocusAfterTabSwitch in tabbrowser gets confused and
- // isn't sure what tab is really focused.
- if (gMultiProcessBrowser) {
- yield switchWaiter;
- }
-
- yield expectFocusShift(() => gBrowser.selectedTab.blur(),
- "main-window", null, true,
- "blurring tab element");
-
- // focusing the url field should switch active focus away from the browser but
- // not clear what would be the focus in the browser
- focusElementInChild("button1", "focus");
-
- yield expectFocusShift(() => gURLBar.focus(),
- "main-window", "urlbar", true,
- "focusedWindow after url field focused");
- focused = yield getFocusedElementForBrowser(browser1, true);
- is(focused, "Focus is button1", "focusedElement after url field focused, first browser");
- focused = yield getFocusedElementForBrowser(browser2, true);
- is(focused, "Focus is button2", "focusedElement after url field focused, second browser");
-
- yield expectFocusShift(() => gURLBar.blur(),
- "main-window", null, true,
- "blurring url field");
-
- // when a chrome element is focused, switching tabs to a tab with a button
- // with the current focus should focus the button
- yield* expectFocusShiftAfterTabSwitch(tab1, "window1", "button1", true,
- "after tab change, focus in url field, button focused in new tab");
-
- focused = yield getFocusedElementForBrowser(browser1, false);
- is(focused, "Focus is button1", "after switch tab, focus in unfocused tab, first browser");
- focused = yield getFocusedElementForBrowser(browser2, true);
- is(focused, "Focus is button2", "after switch tab, focus in unfocused tab, second browser");
-
- // blurring an element in the current tab should clear the active focus
- yield expectFocusShift(() => focusElementInChild("button1", "blur"),
- "window1", null, true,
- "after blur in focused tab");
-
- focused = yield getFocusedElementForBrowser(browser1, false);
- is(focused, "Focus is <none>", "focusedWindow after blur in focused tab, child");
- focusedWindow = {};
- is(fm.getFocusedElementForWindow(window, false, focusedWindow), browser1, "focusedElement after blur in focused tab, parent");
-
- // blurring an non-focused url field should have no effect
- yield expectFocusShift(() => gURLBar.blur(),
- "window1", null, false,
- "after blur in unfocused url field");
-
- focusedWindow = {};
- is(fm.getFocusedElementForWindow(window, false, focusedWindow), browser1, "focusedElement after blur in unfocused url field");
-
- // switch focus to a tab with a currently focused element
- yield* expectFocusShiftAfterTabSwitch(tab2, "window2", "button2", true,
- "after switch from unfocused to focused tab");
- focused = yield getFocusedElementForBrowser(browser2, true);
- is(focused, "Focus is button2", "focusedElement after switch from unfocused to focused tab");
-
- // clearing focus on the chrome window should switch the focus to the
- // chrome window
- yield expectFocusShift(() => fm.clearFocus(window),
- "main-window", null, true,
- "after switch to chrome with no focused element");
-
- focusedWindow = {};
- is(fm.getFocusedElementForWindow(window, false, focusedWindow), null, "focusedElement after switch to chrome with no focused element");
-
- // switch focus to another tab when neither have an active focus
- yield* expectFocusShiftAfterTabSwitch(tab1, "window1", null, true,
- "focusedWindow after tab switch from no focus to no focus");
-
- focused = yield getFocusedElementForBrowser(browser1, false);
- is(focused, "Focus is <none>", "after tab switch from no focus to no focus, first browser");
- focused = yield getFocusedElementForBrowser(browser2, true);
- is(focused, "Focus is button2", "after tab switch from no focus to no focus, second browser");
-
- // next, check whether navigating forward, focusing the urlbar and then
- // navigating back maintains the focus in the urlbar.
- yield expectFocusShift(() => focusElementInChild("button1", "focus"),
- "window1", "button1", true,
- "focus button");
-
- yield promiseTabLoadEvent(tab1, "data:text/html," + escape(testPage3));
-
- // now go back again
- gURLBar.focus();
-
- yield new Promise((resolve, reject) => {
- window.addEventListener("pageshow", function navigationOccured(event) {
- window.removeEventListener("pageshow", navigationOccured, true);
- resolve();
- }, true);
- document.getElementById('Browser:Back').doCommand();
- });
-
- is(window.document.activeElement, gURLBar.inputField, "urlbar still focused after navigating back");
-
- // Document navigation with F6 does not yet work in mutli-process browsers.
- if (!gMultiProcessBrowser) {
- gURLBar.focus();
- actualEvents = new EventStore();
- _lastfocus = "urlbar";
- _lastfocuswindow = "main-window";
-
- yield expectFocusShift(() => EventUtils.synthesizeKey("VK_F6", { }),
- "window1", "html1",
- true, "switch document forward with f6");
-
- EventUtils.synthesizeKey("VK_F6", { });
- is(fm.focusedWindow, window, "switch document forward again with f6");
-
- browser1.style.MozUserFocus = "ignore";
- browser1.clientWidth;
- EventUtils.synthesizeKey("VK_F6", { });
- is(fm.focusedWindow, window, "switch document forward again with f6 when browser non-focusable");
-
- browser1.style.MozUserFocus = "normal";
- browser1.clientWidth;
- }
-
- window.removeEventListener("focus", _browser_tabfocus_test_eventOccured, true);
- window.removeEventListener("blur", _browser_tabfocus_test_eventOccured, true);
-
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
-
- finish();
-});
-
-function _browser_tabfocus_test_eventOccured(event)
-{
- function getWindowDocId(target)
- {
- if (target == browser1.contentWindow || target == browser1.contentDocument) {
- return "window1";
- }
- if (target == browser2.contentWindow || target == browser2.contentDocument) {
- return "window2";
- }
- return "main-window";
- }
-
- var id;
-
- // Some focus events from the child bubble up? Ignore them.
- if (Cu.isCrossProcessWrapper(event.originalTarget))
- return;
-
- if (event.target instanceof Window)
- id = getWindowDocId(event.originalTarget) + "-window";
- else if (event.target instanceof Document)
- id = getWindowDocId(event.originalTarget) + "-document";
- else if (event.target.id == "urlbar" && event.originalTarget.localName == "input")
- id = "urlbar";
- else if (event.originalTarget.localName == "browser")
- id = (event.originalTarget == browser1) ? "browser1" : "browser2";
- else if (event.originalTarget.localName == "tab")
- id = (event.originalTarget == tab1) ? "tab1" : "tab2";
- else
- id = event.originalTarget.id;
-
- actualEvents.push(event.type + ": " + id);
- compareFocusResults();
-}
-
-function getId(element)
-{
- if (!element) {
- return null;
- }
-
- if (element.localName == "browser") {
- return element == browser1 ? "browser1" : "browser2";
- }
-
- if (element.localName == "tab") {
- return element == tab1 ? "tab1" : "tab2";
- }
-
- return (element.localName == "input") ? "urlbar" : element.id;
-}
-
-function compareFocusResults()
-{
- if (!currentPromiseResolver)
- return;
-
- let winIds = ["main-window", "window1", "window2"];
-
- for (let winId of winIds) {
- if (actualEvents[winId].length < expectedEvents[winId].length)
- return;
- }
-
- for (let winId of winIds) {
- for (let e = 0; e < expectedEvents.length; e++) {
- is(actualEvents[winId][e], expectedEvents[winId][e], currentTestName + " events [event " + e + "]");
- }
- actualEvents[winId] = [];
- }
-
- // Use executeSoon as this will be called during a focus/blur event handler
- executeSoon(() => {
- let matchWindow = window;
- if (gMultiProcessBrowser) {
- is(_expectedWindow, "main-window", "main-window is always expected");
- }
- else if (_expectedWindow != "main-window") {
- matchWindow = (_expectedWindow == "window1" ? browser1.contentWindow : browser2.contentWindow);
- }
-
- var focusedElement = fm.focusedElement;
- is(getId(focusedElement), _expectedElement, currentTestName + " focusedElement");
- is(fm.focusedWindow, matchWindow, currentTestName + " focusedWindow");
- var focusedWindow = {};
- is(getId(fm.getFocusedElementForWindow(matchWindow, false, focusedWindow)),
- _expectedElement, currentTestName + " getFocusedElementForWindow");
- is(focusedWindow.value, matchWindow, currentTestName + " getFocusedElementForWindow frame");
- is(matchWindow.document.hasFocus(), true, currentTestName + " hasFocus");
- var expectedActive = _expectedElement;
- if (!expectedActive) {
- expectedActive = matchWindow.document instanceof XULDocument ?
- "main-window" : getId(matchWindow.document.body);
- }
- is(getId(matchWindow.document.activeElement), expectedActive, currentTestName + " activeElement");
-
- currentPromiseResolver();
- currentPromiseResolver = null;
- });
-}
-
-function* expectFocusShiftAfterTabSwitch(tab, expectedWindow, expectedElement, focusChanged, testid)
-{
- let tabSwitchPromise = null;
- yield expectFocusShift(() => { tabSwitchPromise = BrowserTestUtils.switchTab(gBrowser, tab) },
- expectedWindow, expectedElement, focusChanged, testid)
- yield tabSwitchPromise;
-}
-
-function* expectFocusShift(callback, expectedWindow, expectedElement, focusChanged, testid)
-{
- currentPromiseResolver = null;
- currentTestName = testid;
-
- expectedEvents = new EventStore();
-
- if (focusChanged) {
- _expectedElement = expectedElement;
- _expectedWindow = expectedWindow;
-
- // When the content is in a child process, the expected element in the chrome window
- // will always be the urlbar or a browser element.
- if (gMultiProcessBrowser) {
- if (_expectedWindow == "window1") {
- _expectedElement = "browser1";
- }
- else if (_expectedWindow == "window2") {
- _expectedElement = "browser2";
- }
- _expectedWindow = "main-window";
- }
-
- if (gMultiProcessBrowser && _lastfocuswindow != "main-window" &&
- _lastfocuswindow != expectedWindow) {
- let browserid = _lastfocuswindow == "window1" ? "browser1" : "browser2";
- expectedEvents.push("blur: " + browserid);
- }
-
- var newElementIsFocused = (expectedElement && !expectedElement.startsWith("html"));
- if (newElementIsFocused && gMultiProcessBrowser &&
- _lastfocuswindow != "main-window" &&
- expectedWindow == "main-window") {
- // When switching from a child to a chrome element, the focus on the element will arrive first.
- expectedEvents.push("focus: " + expectedElement);
- newElementIsFocused = false;
- }
-
- if (_lastfocus && _lastfocus != _expectedElement)
- expectedEvents.push("blur: " + _lastfocus);
-
- if (_lastfocuswindow &&
- _lastfocuswindow != expectedWindow) {
-
- if (!gMultiProcessBrowser || _lastfocuswindow != "main-window") {
- expectedEvents.push("blur: " + _lastfocuswindow + "-document");
- expectedEvents.push("blur: " + _lastfocuswindow + "-window");
- }
- }
-
- if (expectedWindow && _lastfocuswindow != expectedWindow) {
- if (gMultiProcessBrowser && expectedWindow != "main-window") {
- let browserid = expectedWindow == "window1" ? "browser1" : "browser2";
- expectedEvents.push("focus: " + browserid);
- }
-
- if (!gMultiProcessBrowser || expectedWindow != "main-window") {
- expectedEvents.push("focus: " + expectedWindow + "-document");
- expectedEvents.push("focus: " + expectedWindow + "-window");
- }
- }
-
- if (newElementIsFocused) {
- expectedEvents.push("focus: " + expectedElement);
- }
-
- _lastfocus = expectedElement;
- _lastfocuswindow = expectedWindow;
- }
-
- return new Promise((resolve, reject) => {
- currentPromiseResolver = resolve;
- callback();
-
- // No events are expected, so resolve the promise immediately.
- if (expectedEvents["main-window"].length + expectedEvents["window1"].length + expectedEvents["window2"].length == 0) {
- currentPromiseResolver();
- currentPromiseResolver = null;
- }
- });
-}
diff --git a/browser/base/content/test/general/browser_tabkeynavigation.js b/browser/base/content/test/general/browser_tabkeynavigation.js
deleted file mode 100644
index d8e51f4b9..000000000
--- a/browser/base/content/test/general/browser_tabkeynavigation.js
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * This test checks that keyboard navigation for tabs isn't blocked by content
- */
-add_task(function* test() {
-
- let testPage1 = "data:text/html,<html id='tab1'><body><button id='button1'>Tab 1</button></body></html>";
- let testPage2 = "data:text/html,<html id='tab2'><body><button id='button2'>Tab 2</button><script>function preventDefault(event) { event.preventDefault(); event.stopImmediatePropagation(); } window.addEventListener('keydown', preventDefault, true); window.addEventListener('keypress', preventDefault, true);</script></body></html>";
- let testPage3 = "data:text/html,<html id='tab3'><body><button id='button3'>Tab 3</button></body></html>";
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage1);
- let browser1 = gBrowser.getBrowserForTab(tab1);
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage2);
- let tab3 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage3);
-
- // Kill the animation for simpler test.
- Services.prefs.setBoolPref("browser.tabs.animate", false);
-
- gBrowser.selectedTab = tab1;
- browser1.focus();
-
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated");
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+Tab on Tab1");
-
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true });
- is(gBrowser.selectedTab, tab3,
- "Tab3 should be activated by pressing Ctrl+Tab on Tab2");
-
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true, shiftKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+Shift+Tab on Tab3");
-
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true, shiftKey: true });
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated by pressing Ctrl+Shift+Tab on Tab2");
-
- gBrowser.selectedTab = tab1;
- browser1.focus();
-
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated");
- EventUtils.synthesizeKey("VK_PAGE_DOWN", { ctrlKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+PageDown on Tab1");
-
- EventUtils.synthesizeKey("VK_PAGE_DOWN", { ctrlKey: true });
- is(gBrowser.selectedTab, tab3,
- "Tab3 should be activated by pressing Ctrl+PageDown on Tab2");
-
- EventUtils.synthesizeKey("VK_PAGE_UP", { ctrlKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+PageUp on Tab3");
-
- EventUtils.synthesizeKey("VK_PAGE_UP", { ctrlKey: true });
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated by pressing Ctrl+PageUp on Tab2");
-
- if (gBrowser.mTabBox._handleMetaAltArrows) {
- gBrowser.selectedTab = tab1;
- browser1.focus();
-
- let ltr = window.getComputedStyle(gBrowser.mTabBox, "").direction == "ltr";
- let advanceKey = ltr ? "VK_RIGHT" : "VK_LEFT";
- let reverseKey = ltr ? "VK_LEFT" : "VK_RIGHT";
-
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated");
- EventUtils.synthesizeKey(advanceKey, { altKey: true, metaKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+" + advanceKey + " on Tab1");
-
- EventUtils.synthesizeKey(advanceKey, { altKey: true, metaKey: true });
- is(gBrowser.selectedTab, tab3,
- "Tab3 should be activated by pressing Ctrl+" + advanceKey + " on Tab2");
-
- EventUtils.synthesizeKey(reverseKey, { altKey: true, metaKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+" + reverseKey + " on Tab3");
-
- EventUtils.synthesizeKey(reverseKey, { altKey: true, metaKey: true });
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated by pressing Ctrl+" + reverseKey + " on Tab2");
- }
-
- gBrowser.selectedTab = tab2;
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated");
- is(gBrowser.tabContainer.selectedIndex, 2,
- "Tab2 index should be 2");
-
- EventUtils.synthesizeKey("VK_PAGE_DOWN", { ctrlKey: true, shiftKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated after Ctrl+Shift+PageDown");
- is(gBrowser.tabContainer.selectedIndex, 3,
- "Tab2 index should be 1 after Ctrl+Shift+PageDown");
-
- EventUtils.synthesizeKey("VK_PAGE_UP", { ctrlKey: true, shiftKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated after Ctrl+Shift+PageUp");
- is(gBrowser.tabContainer.selectedIndex, 2,
- "Tab2 index should be 2 after Ctrl+Shift+PageUp");
-
- if (navigator.platform.indexOf("Mac") == 0) {
- gBrowser.selectedTab = tab1;
- browser1.focus();
-
- // XXX Currently, Command + "{" and "}" don't work if keydown event is
- // consumed because following keypress event isn't fired.
-
- let ltr = window.getComputedStyle(gBrowser.mTabBox, "").direction == "ltr";
- let advanceKey = ltr ? "}" : "{";
- let reverseKey = ltr ? "{" : "}";
-
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated");
-
- EventUtils.synthesizeKey(advanceKey, { metaKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+" + advanceKey + " on Tab1");
-
- EventUtils.synthesizeKey(advanceKey, { metaKey: true });
- is(gBrowser.selectedTab, tab3,
- "Tab3 should be activated by pressing Ctrl+" + advanceKey + " on Tab2");
-
- EventUtils.synthesizeKey(reverseKey, { metaKey: true });
- is(gBrowser.selectedTab, tab2,
- "Tab2 should be activated by pressing Ctrl+" + reverseKey + " on Tab3");
-
- EventUtils.synthesizeKey(reverseKey, { metaKey: true });
- is(gBrowser.selectedTab, tab1,
- "Tab1 should be activated by pressing Ctrl+" + reverseKey + " on Tab2");
- } else {
- gBrowser.selectedTab = tab2;
- EventUtils.synthesizeKey("VK_F4", { type: "keydown", ctrlKey: true });
-
- isnot(gBrowser.selectedTab, tab2,
- "Tab2 should be closed by pressing Ctrl+F4 on Tab2");
- is(gBrowser.tabs.length, 3,
- "The count of tabs should be 3 since tab2 should be closed");
-
- // NOTE: keypress event shouldn't be fired since the keydown event should
- // be consumed by tab2.
- EventUtils.synthesizeKey("VK_F4", { type: "keyup", ctrlKey: true });
- is(gBrowser.tabs.length, 3,
- "The count of tabs should be 3 since renaming key events shouldn't close other tabs");
- }
-
- gBrowser.selectedTab = tab3;
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-
- Services.prefs.clearUserPref("browser.tabs.animate");
-});
diff --git a/browser/base/content/test/general/browser_tabopen_reflows.js b/browser/base/content/test/general/browser_tabopen_reflows.js
deleted file mode 100644
index 8e04cf12e..000000000
--- a/browser/base/content/test/general/browser_tabopen_reflows.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-XPCOMUtils.defineLazyGetter(this, "docShell", () => {
- return window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShell);
-});
-
-const EXPECTED_REFLOWS = [
- // tabbrowser.adjustTabstrip() call after tabopen animation has finished
- "adjustTabstrip@chrome://browser/content/tabbrowser.xml|" +
- "_handleNewTab@chrome://browser/content/tabbrowser.xml|" +
- "onxbltransitionend@chrome://browser/content/tabbrowser.xml|",
-
- // switching focus in updateCurrentBrowser() causes reflows
- "_adjustFocusAfterTabSwitch@chrome://browser/content/tabbrowser.xml|" +
- "updateCurrentBrowser@chrome://browser/content/tabbrowser.xml|" +
- "onselect@chrome://browser/content/browser.xul|",
-
- // switching focus in openLinkIn() causes reflows
- "openLinkIn@chrome://browser/content/utilityOverlay.js|" +
- "openUILinkIn@chrome://browser/content/utilityOverlay.js|" +
- "BrowserOpenTab@chrome://browser/content/browser.js|",
-
- // accessing element.scrollPosition in _fillTrailingGap() flushes layout
- "get_scrollPosition@chrome://global/content/bindings/scrollbox.xml|" +
- "_fillTrailingGap@chrome://browser/content/tabbrowser.xml|" +
- "_handleNewTab@chrome://browser/content/tabbrowser.xml|" +
- "onxbltransitionend@chrome://browser/content/tabbrowser.xml|",
-
- // SessionStore.getWindowDimensions()
- "ssi_getWindowDimension@resource:///modules/sessionstore/SessionStore.jsm|" +
- "ssi_updateWindowFeatures/<@resource:///modules/sessionstore/SessionStore.jsm|" +
- "ssi_updateWindowFeatures@resource:///modules/sessionstore/SessionStore.jsm|" +
- "ssi_collectWindowData@resource:///modules/sessionstore/SessionStore.jsm|",
-
- // selection change notification may cause querying the focused editor content
- // by IME and that will cause reflow.
- "select@chrome://global/content/bindings/textbox.xml|" +
- "focusAndSelectUrlBar@chrome://browser/content/browser.js|" +
- "openLinkIn@chrome://browser/content/utilityOverlay.js|" +
- "openUILinkIn@chrome://browser/content/utilityOverlay.js|" +
- "BrowserOpenTab@chrome://browser/content/browser.js|",
-
-];
-
-const PREF_PRELOAD = "browser.newtab.preload";
-const PREF_NEWTAB_DIRECTORYSOURCE = "browser.newtabpage.directory.source";
-
-/*
- * This test ensures that there are no unexpected
- * uninterruptible reflows when opening new tabs.
- */
-add_task(function*() {
- let DirectoryLinksProvider = Cu.import("resource:///modules/DirectoryLinksProvider.jsm", {}).DirectoryLinksProvider;
- let NewTabUtils = Cu.import("resource://gre/modules/NewTabUtils.jsm", {}).NewTabUtils;
- let Promise = Cu.import("resource://gre/modules/Promise.jsm", {}).Promise;
-
- // resolves promise when directory links are downloaded and written to disk
- function watchLinksChangeOnce() {
- let deferred = Promise.defer();
- let observer = {
- onManyLinksChanged: () => {
- DirectoryLinksProvider.removeObserver(observer);
- NewTabUtils.links.populateCache(() => {
- NewTabUtils.allPages.update();
- deferred.resolve();
- }, true);
- }
- };
- observer.onDownloadFail = observer.onManyLinksChanged;
- DirectoryLinksProvider.addObserver(observer);
- return deferred.promise;
- }
-
- let gOrigDirectorySource = Services.prefs.getCharPref(PREF_NEWTAB_DIRECTORYSOURCE);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref(PREF_PRELOAD);
- Services.prefs.setCharPref(PREF_NEWTAB_DIRECTORYSOURCE, gOrigDirectorySource);
- return watchLinksChangeOnce();
- });
-
- Services.prefs.setBoolPref(PREF_PRELOAD, false);
- // set directory source to dummy/empty links
- Services.prefs.setCharPref(PREF_NEWTAB_DIRECTORYSOURCE, 'data:application/json,{"test":1}');
-
- // run tests when directory source change completes
- yield watchLinksChangeOnce();
-
- // Perform a click in the top left of content to ensure the mouse isn't
- // hovering over any of the tiles
- let target = gBrowser.selectedBrowser;
- let rect = target.getBoundingClientRect();
- let left = rect.left + 1;
- let top = rect.top + 1;
-
- let utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
-
- // Add a reflow observer and open a new tab.
- docShell.addWeakReflowObserver(observer);
- BrowserOpenTab();
-
- // Wait until the tabopen animation has finished.
- yield waitForTransitionEnd();
-
- // Remove reflow observer and clean up.
- docShell.removeWeakReflowObserver(observer);
- gBrowser.removeCurrentTab();
-});
-
-var observer = {
- reflow: function (start, end) {
- // Gather information about the current code path.
- let path = (new Error().stack).split("\n").slice(1).map(line => {
- return line.replace(/:\d+:\d+$/, "");
- }).join("|");
- let pathWithLineNumbers = (new Error().stack).split("\n").slice(1).join("|");
-
- // Stack trace is empty. Reflow was triggered by native code.
- if (path === "") {
- return;
- }
-
- // Check if this is an expected reflow.
- for (let stack of EXPECTED_REFLOWS) {
- if (path.startsWith(stack)) {
- ok(true, "expected uninterruptible reflow '" + stack + "'");
- return;
- }
- }
-
- ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'");
- },
-
- reflowInterruptible: function (start, end) {
- // We're not interested in interruptible reflows.
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIReflowObserver,
- Ci.nsISupportsWeakReference])
-};
-
-function waitForTransitionEnd() {
- return new Promise(resolve => {
- let tab = gBrowser.selectedTab;
- tab.addEventListener("transitionend", function onEnd(event) {
- if (event.propertyName === "max-width") {
- tab.removeEventListener("transitionend", onEnd);
- resolve();
- }
- });
- });
-}
diff --git a/browser/base/content/test/general/browser_tabs_close_beforeunload.js b/browser/base/content/test/general/browser_tabs_close_beforeunload.js
deleted file mode 100644
index b867efd72..000000000
--- a/browser/base/content/test/general/browser_tabs_close_beforeunload.js
+++ /dev/null
@@ -1,49 +0,0 @@
-"use strict";
-
-SimpleTest.requestCompleteLog();
-
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
-
-const FIRST_TAB = getRootDirectory(gTestPath) + "close_beforeunload_opens_second_tab.html";
-const SECOND_TAB = getRootDirectory(gTestPath) + "close_beforeunload.html";
-
-add_task(function*() {
- info("Opening first tab");
- let firstTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, FIRST_TAB);
- let secondTabLoadedPromise;
- let secondTab;
- let tabOpened = new Promise(resolve => {
- info("Adding tabopen listener");
- gBrowser.tabContainer.addEventListener("TabOpen", function tabOpenListener(e) {
- info("Got tabopen, removing listener and waiting for load");
- gBrowser.tabContainer.removeEventListener("TabOpen", tabOpenListener, false, false);
- secondTab = e.target;
- secondTabLoadedPromise = BrowserTestUtils.browserLoaded(secondTab.linkedBrowser, false, SECOND_TAB);
- resolve();
- }, false, false);
- });
- info("Opening second tab using a click");
- yield ContentTask.spawn(firstTab.linkedBrowser, "", function*() {
- content.document.getElementsByTagName("a")[0].click();
- });
- info("Waiting for the second tab to be opened");
- yield tabOpened;
- info("Waiting for the load in that tab to finish");
- yield secondTabLoadedPromise;
-
- let closeBtn = document.getAnonymousElementByAttribute(secondTab, "anonid", "close-button");
- let closePromise = BrowserTestUtils.removeTab(secondTab, {dontRemove: true});
- info("closing second tab (which will self-close in beforeunload)");
- closeBtn.click();
- ok(secondTab.closing, "Second tab should be marked as closing synchronously.");
- yield closePromise;
- ok(secondTab.closing, "Second tab should still be marked as closing");
- ok(!secondTab.linkedBrowser, "Second tab's browser should be dead");
- ok(!firstTab.closing, "First tab should not be closing");
- ok(firstTab.linkedBrowser, "First tab's browser should be alive");
- info("closing first tab");
- yield BrowserTestUtils.removeTab(firstTab);
-
- ok(firstTab.closing, "First tab should be marked as closing");
- ok(!firstTab.linkedBrowser, "First tab's browser should be dead");
-});
diff --git a/browser/base/content/test/general/browser_tabs_isActive.js b/browser/base/content/test/general/browser_tabs_isActive.js
deleted file mode 100644
index 0725757e7..000000000
--- a/browser/base/content/test/general/browser_tabs_isActive.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test for the docshell active state of local and remote browsers.
-
-const kTestPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
-
-function promiseNewTabSwitched() {
- return new Promise(resolve => {
- gBrowser.addEventListener("TabSwitchDone", function onSwitch() {
- gBrowser.removeEventListener("TabSwitchDone", onSwitch);
- executeSoon(resolve);
- });
- });
-}
-
-function getParentTabState(aTab) {
- return aTab.linkedBrowser.docShellIsActive;
-}
-
-function getChildTabState(aTab) {
- return ContentTask.spawn(aTab.linkedBrowser, {}, function* () {
- return docShell.isActive;
- });
-}
-
-function checkState(parentSide, childSide, value, message) {
- is(parentSide, value, message + " (parent side)");
- is(childSide, value, message + " (child side)");
-}
-
-function waitForMs(aMs) {
- return new Promise((resolve) => {
- setTimeout(done, aMs);
- function done() {
- resolve(true);
- }
- });
-}
-
-add_task(function *() {
- let url = kTestPage;
- let originalTab = gBrowser.selectedTab; // test tab
- let newTab = gBrowser.addTab(url, {skipAnimation: true});
- let parentSide, childSide;
-
- // new tab added but not selected checks
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, false, "newly added " + url + " tab is not active");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, true, "original tab is active initially");
-
- // select the newly added tab and wait for TabSwitchDone event
- let tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = newTab;
- yield tabSwitchedPromise;
-
- if (Services.appinfo.browserTabsRemoteAutostart) {
- ok(newTab.linkedBrowser.isRemoteBrowser, "for testing we need a remote tab");
- }
-
- // check active state of both tabs
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, true, "newly added " + url + " tab is active after selection");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, false, "original tab is not active while unselected");
-
- // switch back to the original test tab and wait for TabSwitchDone event
- tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = originalTab;
- yield tabSwitchedPromise;
-
- // check active state of both tabs
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, false, "newly added " + url + " tab is not active after switch back");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, true, "original tab is active again after switch back");
-
- // switch to the new tab and wait for TabSwitchDone event
- tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = newTab;
- yield tabSwitchedPromise;
-
- // check active state of both tabs
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, true, "newly added " + url + " tab is not active after switch back");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, false, "original tab is active again after switch back");
-
- gBrowser.removeTab(newTab);
-});
-
-add_task(function *() {
- let url = "about:about";
- let originalTab = gBrowser.selectedTab; // test tab
- let newTab = gBrowser.addTab(url, {skipAnimation: true});
- let parentSide, childSide;
-
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, false, "newly added " + url + " tab is not active");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, true, "original tab is active initially");
-
- let tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = newTab;
- yield tabSwitchedPromise;
-
- if (Services.appinfo.browserTabsRemoteAutostart) {
- ok(!newTab.linkedBrowser.isRemoteBrowser, "for testing we need a local tab");
- }
-
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, true, "newly added " + url + " tab is active after selection");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, false, "original tab is not active while unselected");
-
- tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = originalTab;
- yield tabSwitchedPromise;
-
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, false, "newly added " + url + " tab is not active after switch back");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, true, "original tab is active again after switch back");
-
- tabSwitchedPromise = promiseNewTabSwitched();
- gBrowser.selectedTab = newTab;
- yield tabSwitchedPromise;
-
- parentSide = getParentTabState(newTab);
- childSide = yield getChildTabState(newTab);
- checkState(parentSide, childSide, true, "newly added " + url + " tab is not active after switch back");
- parentSide = getParentTabState(originalTab);
- childSide = yield getChildTabState(originalTab);
- checkState(parentSide, childSide, false, "original tab is active again after switch back");
-
- gBrowser.removeTab(newTab);
-});
diff --git a/browser/base/content/test/general/browser_tabs_owner.js b/browser/base/content/test/general/browser_tabs_owner.js
deleted file mode 100644
index 300d783ba..000000000
--- a/browser/base/content/test/general/browser_tabs_owner.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: gBrowser._finalizeTabSwitch is not a function");
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: gBrowser._finalizeTabSwitch is not a function");
-
-function test() {
- gBrowser.addTab();
- gBrowser.addTab();
- gBrowser.addTab();
-
- var tabs = gBrowser.tabs;
- var owner;
-
- is(tabs.length, 4, "4 tabs are open");
-
- owner = gBrowser.selectedTab = tabs[2];
- BrowserOpenTab();
- is(gBrowser.selectedTab, tabs[4], "newly opened tab is selected");
- gBrowser.removeCurrentTab();
- is(gBrowser.selectedTab, owner, "owner is selected");
-
- owner = gBrowser.selectedTab;
- BrowserOpenTab();
- gBrowser.selectedTab = tabs[1];
- gBrowser.selectedTab = tabs[4];
- gBrowser.removeCurrentTab();
- isnot(gBrowser.selectedTab, owner, "selecting a different tab clears the owner relation");
-
- owner = gBrowser.selectedTab;
- BrowserOpenTab();
- gBrowser.moveTabTo(gBrowser.selectedTab, 0);
- gBrowser.removeCurrentTab();
- is(gBrowser.selectedTab, owner, "owner relatitionship persists when tab is moved");
-
- while (tabs.length > 1)
- gBrowser.removeCurrentTab();
-}
diff --git a/browser/base/content/test/general/browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js b/browser/base/content/test/general/browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js
deleted file mode 100644
index f90f047d3..000000000
--- a/browser/base/content/test/general/browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js
+++ /dev/null
@@ -1,126 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const OPEN_LOCATION_PREF = "browser.link.open_newwindow";
-const NON_REMOTE_PAGE = "about:welcomeback";
-
-Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
-
-requestLongerTimeout(2);
-
-function frame_script() {
- content.document.body.innerHTML = `
- <a href="about:home" target="_blank" id="testAnchor">Open a window</a>
- `;
-
- let element = content.document.getElementById("testAnchor");
- element.click();
-}
-
-/**
- * Takes some browser in some window, and forces that browser
- * to become non-remote, and then navigates it to a page that
- * we're not supposed to be displaying remotely. Returns a
- * Promise that resolves when the browser is no longer remote.
- */
-function prepareNonRemoteBrowser(aWindow, browser) {
- browser.loadURI(NON_REMOTE_PAGE);
- return BrowserTestUtils.browserLoaded(browser);
-}
-
-registerCleanupFunction(() => {
- Services.prefs.clearUserPref(OPEN_LOCATION_PREF);
-});
-
-/**
- * Test that if we open a new tab from a link in a non-remote
- * browser in an e10s window, that the new tab will load properly.
- */
-add_task(function* test_new_tab() {
- let normalWindow = yield BrowserTestUtils.openNewBrowserWindow({
- remote: true,
- });
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({
- remote: true,
- private: true,
- });
-
- for (let testWindow of [normalWindow, privateWindow]) {
- yield promiseWaitForFocus(testWindow);
- let testBrowser = testWindow.gBrowser.selectedBrowser;
- info("Preparing non-remote browser");
- yield prepareNonRemoteBrowser(testWindow, testBrowser);
- info("Non-remote browser prepared - sending frame script");
-
- // Get our framescript ready
- let mm = testBrowser.messageManager;
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", true);
-
- let tabOpenEvent = yield waitForNewTabEvent(testWindow.gBrowser);
- let newTab = tabOpenEvent.target;
-
- yield promiseTabLoadEvent(newTab);
-
- // Our framescript opens to about:home which means that the
- // tab should eventually become remote.
- ok(newTab.linkedBrowser.isRemoteBrowser,
- "The opened browser never became remote.");
-
- testWindow.gBrowser.removeTab(newTab);
- }
-
- normalWindow.close();
- privateWindow.close();
-});
-
-/**
- * Test that if we open a new window from a link in a non-remote
- * browser in an e10s window, that the new window is not an e10s
- * window. Also tests with a private browsing window.
- */
-add_task(function* test_new_window() {
- let normalWindow = yield BrowserTestUtils.openNewBrowserWindow({
- remote: true
- }, true);
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({
- remote: true,
- private: true,
- }, true);
-
- // Fiddle with the prefs so that we open target="_blank" links
- // in new windows instead of new tabs.
- Services.prefs.setIntPref(OPEN_LOCATION_PREF,
- Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW);
-
- for (let testWindow of [normalWindow, privateWindow]) {
- yield promiseWaitForFocus(testWindow);
- let testBrowser = testWindow.gBrowser.selectedBrowser;
- yield prepareNonRemoteBrowser(testWindow, testBrowser);
-
- // Get our framescript ready
- let mm = testBrowser.messageManager;
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", true);
-
- // Click on the link in the browser, and wait for the new window.
- let {subject: newWindow} =
- yield promiseTopicObserved("browser-delayed-startup-finished");
-
- is(PrivateBrowsingUtils.isWindowPrivate(testWindow),
- PrivateBrowsingUtils.isWindowPrivate(newWindow),
- "Private browsing state of new window does not match the original!");
-
- let newTab = newWindow.gBrowser.selectedTab;
-
- yield promiseTabLoadEvent(newTab);
-
- // Our framescript opens to about:home which means that the
- // tab should eventually become remote.
- ok(newTab.linkedBrowser.isRemoteBrowser,
- "The opened browser never became remote.");
- newWindow.close();
- }
-
- normalWindow.close();
- privateWindow.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_1.js b/browser/base/content/test/general/browser_trackingUI_1.js
deleted file mode 100644
index 937d607af..000000000
--- a/browser/base/content/test/general/browser_trackingUI_1.js
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Test that the Tracking Protection section is visible in the Control Center
- * and has the correct state for the cases when:
- * 1) A page with no tracking elements is loaded.
- * 2) A page with tracking elements is loaded and they are blocked.
- * 3) A page with tracking elements is loaded and they are not blocked.
- * See also Bugs 1175327, 1043801, 1178985
- */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PREF = "privacy.trackingprotection.enabled";
-const PB_PREF = "privacy.trackingprotection.pbmode.enabled";
-const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-var TrackingProtection = null;
-var tabbrowser = null;
-
-var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-registerCleanupFunction(function() {
- TrackingProtection = tabbrowser = null;
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.prefs.clearUserPref(PREF);
- Services.prefs.clearUserPref(PB_PREF);
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-});
-
-function hidden(sel) {
- let win = tabbrowser.ownerGlobal;
- let el = win.document.querySelector(sel);
- let display = win.getComputedStyle(el).getPropertyValue("display", null);
- let opacity = win.getComputedStyle(el).getPropertyValue("opacity", null);
- return display === "none" || opacity === "0";
-}
-
-function clickButton(sel) {
- let win = tabbrowser.ownerGlobal;
- let el = win.document.querySelector(sel);
- el.doCommand();
-}
-
-function testBenignPage() {
- info("Non-tracking content must not be blocked");
- ok(!TrackingProtection.container.hidden, "The container is visible");
- ok(!TrackingProtection.content.hasAttribute("state"), "content: no state");
- ok(!TrackingProtection.icon.hasAttribute("state"), "icon: no state");
- ok(!TrackingProtection.icon.hasAttribute("tooltiptext"), "icon: no tooltip");
-
- ok(hidden("#tracking-protection-icon"), "icon is hidden");
- ok(hidden("#tracking-action-block"), "blockButton is hidden");
- ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
-
- // Make sure that the no tracking elements message appears
- ok(!hidden("#tracking-not-detected"), "labelNoTracking is visible");
- ok(hidden("#tracking-loaded"), "labelTrackingLoaded is hidden");
- ok(hidden("#tracking-blocked"), "labelTrackingBlocked is hidden");
-}
-
-function testTrackingPage(window) {
- info("Tracking content must be blocked");
- ok(!TrackingProtection.container.hidden, "The container is visible");
- is(TrackingProtection.content.getAttribute("state"), "blocked-tracking-content",
- 'content: state="blocked-tracking-content"');
- is(TrackingProtection.icon.getAttribute("state"), "blocked-tracking-content",
- 'icon: state="blocked-tracking-content"');
- is(TrackingProtection.icon.getAttribute("tooltiptext"),
- gNavigatorBundle.getString("trackingProtection.icon.activeTooltip"), "correct tooltip");
-
- ok(!hidden("#tracking-protection-icon"), "icon is visible");
- ok(hidden("#tracking-action-block"), "blockButton is hidden");
-
-
- if (PrivateBrowsingUtils.isWindowPrivate(window)) {
- ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
- ok(!hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is visible");
- } else {
- ok(!hidden("#tracking-action-unblock"), "unblockButton is visible");
- ok(hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is hidden");
- }
-
- // Make sure that the blocked tracking elements message appears
- ok(hidden("#tracking-not-detected"), "labelNoTracking is hidden");
- ok(hidden("#tracking-loaded"), "labelTrackingLoaded is hidden");
- ok(!hidden("#tracking-blocked"), "labelTrackingBlocked is visible");
-}
-
-function testTrackingPageUnblocked() {
- info("Tracking content must be white-listed and not blocked");
- ok(!TrackingProtection.container.hidden, "The container is visible");
- is(TrackingProtection.content.getAttribute("state"), "loaded-tracking-content",
- 'content: state="loaded-tracking-content"');
- is(TrackingProtection.icon.getAttribute("state"), "loaded-tracking-content",
- 'icon: state="loaded-tracking-content"');
- is(TrackingProtection.icon.getAttribute("tooltiptext"),
- gNavigatorBundle.getString("trackingProtection.icon.disabledTooltip"), "correct tooltip");
-
- ok(!hidden("#tracking-protection-icon"), "icon is visible");
- ok(!hidden("#tracking-action-block"), "blockButton is visible");
- ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
-
- // Make sure that the blocked tracking elements message appears
- ok(hidden("#tracking-not-detected"), "labelNoTracking is hidden");
- ok(!hidden("#tracking-loaded"), "labelTrackingLoaded is visible");
- ok(hidden("#tracking-blocked"), "labelTrackingBlocked is hidden");
-}
-
-function* testTrackingProtectionForTab(tab) {
- info("Load a test page not containing tracking elements");
- yield promiseTabLoadEvent(tab, BENIGN_PAGE);
- testBenignPage();
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- testTrackingPage(tab.ownerGlobal);
-
- info("Disable TP for the page (which reloads the page)");
- let tabReloadPromise = promiseTabLoadEvent(tab);
- clickButton("#tracking-action-unblock");
- yield tabReloadPromise;
- testTrackingPageUnblocked();
-
- info("Re-enable TP for the page (which reloads the page)");
- tabReloadPromise = promiseTabLoadEvent(tab);
- clickButton("#tracking-action-block");
- yield tabReloadPromise;
- testTrackingPage(tab.ownerGlobal);
-}
-
-add_task(function* testNormalBrowsing() {
- yield UrlClassifierTestUtils.addTestTrackers();
-
- tabbrowser = gBrowser;
- let tab = tabbrowser.selectedTab = tabbrowser.addTab();
-
- TrackingProtection = gBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
- is(TrackingProtection.enabled, Services.prefs.getBoolPref(PREF),
- "TP.enabled is based on the original pref value");
-
- Services.prefs.setBoolPref(PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- yield testTrackingProtectionForTab(tab);
-
- Services.prefs.setBoolPref(PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled after setting the pref");
-});
-
-add_task(function* testPrivateBrowsing() {
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- tabbrowser = privateWin.gBrowser;
- let tab = tabbrowser.selectedTab = tabbrowser.addTab();
-
- TrackingProtection = tabbrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the private window");
- is(TrackingProtection.enabled, Services.prefs.getBoolPref(PB_PREF),
- "TP.enabled is based on the pb pref value");
-
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- yield testTrackingProtectionForTab(tab);
-
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled after setting the pref");
-
- privateWin.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_2.js b/browser/base/content/test/general/browser_trackingUI_2.js
deleted file mode 100644
index 96ccb6c2e..000000000
--- a/browser/base/content/test/general/browser_trackingUI_2.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Test that the Tracking Protection section is never visible in the
- * Control Center when the feature is off.
- * See also Bugs 1175327, 1043801, 1178985.
- */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PREF = "privacy.trackingprotection.enabled";
-const PB_PREF = "privacy.trackingprotection.pbmode.enabled";
-const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-var TrackingProtection = null;
-var tabbrowser = null;
-
-var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-registerCleanupFunction(function() {
- TrackingProtection = tabbrowser = null;
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.prefs.clearUserPref(PREF);
- Services.prefs.clearUserPref(PB_PREF);
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-});
-
-function hidden(el) {
- let win = el.ownerGlobal;
- let display = win.getComputedStyle(el).getPropertyValue("display", null);
- let opacity = win.getComputedStyle(el).getPropertyValue("opacity", null);
-
- return display === "none" || opacity === "0";
-}
-
-add_task(function* testNormalBrowsing() {
- yield UrlClassifierTestUtils.addTestTrackers();
-
- tabbrowser = gBrowser;
- let {gIdentityHandler} = tabbrowser.ownerGlobal;
- let tab = tabbrowser.selectedTab = tabbrowser.addTab();
-
- TrackingProtection = tabbrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
- is(TrackingProtection.enabled, Services.prefs.getBoolPref(PREF),
- "TP.enabled is based on the original pref value");
-
- Services.prefs.setBoolPref(PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- Services.prefs.setBoolPref(PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled after setting the pref");
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- gIdentityHandler._identityBox.click();
- ok(hidden(TrackingProtection.container), "The container is hidden");
- gIdentityHandler._identityPopup.hidden = true;
-
- info("Load a test page not containing tracking elements");
- yield promiseTabLoadEvent(tab, BENIGN_PAGE);
- gIdentityHandler._identityBox.click();
- ok(hidden(TrackingProtection.container), "The container is hidden");
- gIdentityHandler._identityPopup.hidden = true;
-});
-
-add_task(function* testPrivateBrowsing() {
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- tabbrowser = privateWin.gBrowser;
- let {gIdentityHandler} = tabbrowser.ownerGlobal;
- let tab = tabbrowser.selectedTab = tabbrowser.addTab();
-
- TrackingProtection = tabbrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the private window");
- is(TrackingProtection.enabled, Services.prefs.getBoolPref(PB_PREF),
- "TP.enabled is based on the pb pref value");
-
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled after setting the pref");
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- gIdentityHandler._identityBox.click();
- ok(hidden(TrackingProtection.container), "The container is hidden");
- gIdentityHandler._identityPopup.hidden = true;
-
- info("Load a test page not containing tracking elements");
- gIdentityHandler._identityBox.click();
- yield promiseTabLoadEvent(tab, BENIGN_PAGE);
- ok(hidden(TrackingProtection.container), "The container is hidden");
- gIdentityHandler._identityPopup.hidden = true;
-
- privateWin.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_3.js b/browser/base/content/test/general/browser_trackingUI_3.js
deleted file mode 100644
index 63f8a13bc..000000000
--- a/browser/base/content/test/general/browser_trackingUI_3.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Test that the Tracking Protection is correctly enabled / disabled
- * in both normal and private windows given all possible states of the prefs:
- * privacy.trackingprotection.enabled
- * privacy.trackingprotection.pbmode.enabled
- * See also Bug 1178985.
- */
-
-const PREF = "privacy.trackingprotection.enabled";
-const PB_PREF = "privacy.trackingprotection.pbmode.enabled";
-
-registerCleanupFunction(function() {
- Services.prefs.clearUserPref(PREF);
- Services.prefs.clearUserPref(PB_PREF);
-});
-
-add_task(function* testNormalBrowsing() {
- let TrackingProtection = gBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
-
- Services.prefs.setBoolPref(PREF, true);
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(TrackingProtection.enabled, "TP is enabled (ENABLED=true,PB=false)");
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled (ENABLED=true,PB=true)");
-
- Services.prefs.setBoolPref(PREF, false);
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled (ENABLED=false,PB=false)");
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(!TrackingProtection.enabled, "TP is disabled (ENABLED=false,PB=true)");
-});
-
-add_task(function* testPrivateBrowsing() {
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- let TrackingProtection = privateWin.gBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
-
- Services.prefs.setBoolPref(PREF, true);
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(TrackingProtection.enabled, "TP is enabled (ENABLED=true,PB=false)");
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled (ENABLED=true,PB=true)");
-
- Services.prefs.setBoolPref(PREF, false);
- Services.prefs.setBoolPref(PB_PREF, false);
- ok(!TrackingProtection.enabled, "TP is disabled (ENABLED=false,PB=false)");
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled (ENABLED=false,PB=true)");
-
- privateWin.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_4.js b/browser/base/content/test/general/browser_trackingUI_4.js
deleted file mode 100644
index 93a06913e..000000000
--- a/browser/base/content/test/general/browser_trackingUI_4.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Test that the Tracking Protection icon is properly animated in the identity
- * block when loading tabs and switching between tabs.
- * See also Bug 1175858.
- */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PREF = "privacy.trackingprotection.enabled";
-const PB_PREF = "privacy.trackingprotection.pbmode.enabled";
-const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-var TrackingProtection = null;
-var tabbrowser = null;
-
-var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-registerCleanupFunction(function() {
- TrackingProtection = tabbrowser = null;
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.prefs.clearUserPref(PREF);
- Services.prefs.clearUserPref(PB_PREF);
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-});
-
-function waitForSecurityChange(numChanges = 1) {
- return new Promise(resolve => {
- let n = 0;
- let listener = {
- onSecurityChange: function() {
- n = n + 1;
- info ("Received onSecurityChange event " + n + " of " + numChanges);
- if (n >= numChanges) {
- tabbrowser.removeProgressListener(listener);
- resolve();
- }
- }
- };
- tabbrowser.addProgressListener(listener);
- });
-}
-
-function* testTrackingProtectionAnimation() {
- info("Load a test page not containing tracking elements");
- let benignTab = yield BrowserTestUtils.openNewForegroundTab(tabbrowser, BENIGN_PAGE);
-
- ok(!TrackingProtection.icon.hasAttribute("state"), "icon: no state");
- ok(TrackingProtection.icon.hasAttribute("animate"), "icon: animate");
-
- info("Load a test page containing tracking elements");
- let trackingTab = yield BrowserTestUtils.openNewForegroundTab(tabbrowser, TRACKING_PAGE);
-
- ok(TrackingProtection.icon.hasAttribute("state"), "icon: state");
- ok(TrackingProtection.icon.hasAttribute("animate"), "icon: animate");
-
- info("Switch from tracking -> benign tab");
- let securityChanged = waitForSecurityChange();
- tabbrowser.selectedTab = benignTab;
- yield securityChanged;
-
- ok(!TrackingProtection.icon.hasAttribute("state"), "icon: no state");
- ok(!TrackingProtection.icon.hasAttribute("animate"), "icon: no animate");
-
- info("Switch from benign -> tracking tab");
- securityChanged = waitForSecurityChange();
- tabbrowser.selectedTab = trackingTab;
- yield securityChanged;
-
- ok(TrackingProtection.icon.hasAttribute("state"), "icon: state");
- ok(!TrackingProtection.icon.hasAttribute("animate"), "icon: no animate");
-
- info("Reload tracking tab");
- securityChanged = waitForSecurityChange(2);
- tabbrowser.reload();
- yield securityChanged;
-
- ok(TrackingProtection.icon.hasAttribute("state"), "icon: state");
- ok(TrackingProtection.icon.hasAttribute("animate"), "icon: animate");
-}
-
-add_task(function* testNormalBrowsing() {
- yield UrlClassifierTestUtils.addTestTrackers();
-
- tabbrowser = gBrowser;
-
- TrackingProtection = gBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
-
- Services.prefs.setBoolPref(PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- yield testTrackingProtectionAnimation();
-});
-
-add_task(function* testPrivateBrowsing() {
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- tabbrowser = privateWin.gBrowser;
-
- TrackingProtection = tabbrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the private window");
-
- Services.prefs.setBoolPref(PB_PREF, true);
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- yield testTrackingProtectionAnimation();
-
- privateWin.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_5.js b/browser/base/content/test/general/browser_trackingUI_5.js
deleted file mode 100644
index 23164a5b2..000000000
--- a/browser/base/content/test/general/browser_trackingUI_5.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that sites added to the Tracking Protection whitelist in private
-// browsing mode don't persist once the private browsing window closes.
-
-const PB_PREF = "privacy.trackingprotection.pbmode.enabled";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-var TrackingProtection = null;
-var browser = null;
-var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-registerCleanupFunction(function() {
- TrackingProtection = browser = null;
- UrlClassifierTestUtils.cleanupTestTrackers();
-});
-
-function hidden(sel) {
- let win = browser.ownerGlobal;
- let el = win.document.querySelector(sel);
- let display = win.getComputedStyle(el).getPropertyValue("display", null);
- return display === "none";
-}
-
-function identityPopupState() {
- let win = browser.ownerGlobal;
- return win.document.getElementById("identity-popup").state;
-}
-
-function clickButton(sel) {
- let win = browser.ownerGlobal;
- let el = win.document.querySelector(sel);
- el.doCommand();
-}
-
-function testTrackingPage(window) {
- info("Tracking content must be blocked");
- ok(!TrackingProtection.container.hidden, "The container is visible");
- is(TrackingProtection.content.getAttribute("state"), "blocked-tracking-content",
- 'content: state="blocked-tracking-content"');
- is(TrackingProtection.icon.getAttribute("state"), "blocked-tracking-content",
- 'icon: state="blocked-tracking-content"');
-
- ok(!hidden("#tracking-protection-icon"), "icon is visible");
- ok(hidden("#tracking-action-block"), "blockButton is hidden");
-
- ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
- ok(!hidden("#tracking-action-unblock-private"), "unblockButtonPrivate is visible");
-
- // Make sure that the blocked tracking elements message appears
- ok(hidden("#tracking-not-detected"), "labelNoTracking is hidden");
- ok(hidden("#tracking-loaded"), "labelTrackingLoaded is hidden");
- ok(!hidden("#tracking-blocked"), "labelTrackingBlocked is visible");
-}
-
-function testTrackingPageUnblocked() {
- info("Tracking content must be white-listed and not blocked");
- ok(!TrackingProtection.container.hidden, "The container is visible");
- is(TrackingProtection.content.getAttribute("state"), "loaded-tracking-content",
- 'content: state="loaded-tracking-content"');
- is(TrackingProtection.icon.getAttribute("state"), "loaded-tracking-content",
- 'icon: state="loaded-tracking-content"');
-
- ok(!hidden("#tracking-protection-icon"), "icon is visible");
- ok(!hidden("#tracking-action-block"), "blockButton is visible");
- ok(hidden("#tracking-action-unblock"), "unblockButton is hidden");
-
- // Make sure that the blocked tracking elements message appears
- ok(hidden("#tracking-not-detected"), "labelNoTracking is hidden");
- ok(!hidden("#tracking-loaded"), "labelTrackingLoaded is visible");
- ok(hidden("#tracking-blocked"), "labelTrackingBlocked is hidden");
-}
-
-add_task(function* testExceptionAddition() {
- yield UrlClassifierTestUtils.addTestTrackers();
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- browser = privateWin.gBrowser;
- let tab = browser.selectedTab = browser.addTab();
-
- TrackingProtection = browser.ownerGlobal.TrackingProtection;
- yield pushPrefs([PB_PREF, true]);
-
- ok(TrackingProtection.enabled, "TP is enabled after setting the pref");
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
-
- testTrackingPage(tab.ownerGlobal);
-
- info("Disable TP for the page (which reloads the page)");
- let tabReloadPromise = promiseTabLoadEvent(tab);
- clickButton("#tracking-action-unblock");
- is(identityPopupState(), "closed", "foobar");
-
- yield tabReloadPromise;
- testTrackingPageUnblocked();
-
- info("Test that the exception is remembered across tabs in the same private window");
- tab = browser.selectedTab = browser.addTab();
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- testTrackingPageUnblocked();
-
- yield promiseWindowClosed(privateWin);
-});
-
-add_task(function* testExceptionPersistence() {
- info("Open another private browsing window");
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- browser = privateWin.gBrowser;
- let tab = browser.selectedTab = browser.addTab();
-
- TrackingProtection = browser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection.enabled, "TP is still enabled");
-
- info("Load a test page containing tracking elements");
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
-
- testTrackingPage(tab.ownerGlobal);
-
- info("Disable TP for the page (which reloads the page)");
- let tabReloadPromise = promiseTabLoadEvent(tab);
- clickButton("#tracking-action-unblock");
- is(identityPopupState(), "closed", "foobar");
-
- yield tabReloadPromise;
- testTrackingPageUnblocked();
-
- privateWin.close();
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_6.js b/browser/base/content/test/general/browser_trackingUI_6.js
deleted file mode 100644
index be91bc4a0..000000000
--- a/browser/base/content/test/general/browser_trackingUI_6.js
+++ /dev/null
@@ -1,46 +0,0 @@
-const URL = "http://mochi.test:8888/browser/browser/base/content/test/general/file_trackingUI_6.html";
-
-function waitForSecurityChange(numChanges = 1) {
- return new Promise(resolve => {
- let n = 0;
- let listener = {
- onSecurityChange: function() {
- n = n + 1;
- info ("Received onSecurityChange event " + n + " of " + numChanges);
- if (n >= numChanges) {
- gBrowser.removeProgressListener(listener);
- resolve();
- }
- }
- };
- gBrowser.addProgressListener(listener);
- });
-}
-
-add_task(function* test_fetch() {
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({ set: [['privacy.trackingprotection.enabled', true]] },
- resolve);
- });
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: URL }, function* (newTabBrowser) {
- let securityChange = waitForSecurityChange();
- yield ContentTask.spawn(newTabBrowser, null, function* () {
- yield content.wrappedJSObject.test_fetch()
- .then(response => Assert.ok(false, "should have denied the request"))
- .catch(e => Assert.ok(true, `Caught exception: ${e}`));
- });
- yield securityChange;
-
- var TrackingProtection = newTabBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "got TP object");
- ok(TrackingProtection.enabled, "TP is enabled");
-
- is(TrackingProtection.content.getAttribute("state"), "blocked-tracking-content",
- 'content: state="blocked-tracking-content"');
- is(TrackingProtection.icon.getAttribute("state"), "blocked-tracking-content",
- 'icon: state="blocked-tracking-content"');
- is(TrackingProtection.icon.getAttribute("tooltiptext"),
- gNavigatorBundle.getString("trackingProtection.icon.activeTooltip"), "correct tooltip");
- });
-});
diff --git a/browser/base/content/test/general/browser_trackingUI_telemetry.js b/browser/base/content/test/general/browser_trackingUI_telemetry.js
deleted file mode 100644
index d9fce18d4..000000000
--- a/browser/base/content/test/general/browser_trackingUI_telemetry.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Test telemetry for Tracking Protection
- */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PREF = "privacy.trackingprotection.enabled";
-const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-const {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-/**
- * Enable local telemetry recording for the duration of the tests.
- */
-var oldCanRecord = Services.telemetry.canRecordExtended;
-Services.telemetry.canRecordExtended = true;
-Services.prefs.setBoolPref(PREF, false);
-Services.telemetry.getHistogramById("TRACKING_PROTECTION_ENABLED").clear();
-registerCleanupFunction(function () {
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.telemetry.canRecordExtended = oldCanRecord;
- Services.prefs.clearUserPref(PREF);
-});
-
-function getShieldHistogram() {
- return Services.telemetry.getHistogramById("TRACKING_PROTECTION_SHIELD");
-}
-
-function getEnabledHistogram() {
- return Services.telemetry.getHistogramById("TRACKING_PROTECTION_ENABLED");
-}
-
-function getEventsHistogram() {
- return Services.telemetry.getHistogramById("TRACKING_PROTECTION_EVENTS");
-}
-
-function getShieldCounts() {
- return getShieldHistogram().snapshot().counts;
-}
-
-function getEnabledCounts() {
- return getEnabledHistogram().snapshot().counts;
-}
-
-function getEventCounts() {
- return getEventsHistogram().snapshot().counts;
-}
-
-add_task(function* setup() {
- yield UrlClassifierTestUtils.addTestTrackers();
-
- let TrackingProtection = gBrowser.ownerGlobal.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
- ok(!TrackingProtection.enabled, "TP is not enabled");
-
- // Open a window with TP disabled to make sure 'enabled' is logged correctly.
- let newWin = yield promiseOpenAndLoadWindow({}, true);
- yield promiseWindowClosed(newWin);
-
- is(getEnabledCounts()[0], 1, "TP was disabled once on start up");
- is(getEnabledCounts()[1], 0, "TP was not enabled on start up");
-
- // Enable TP so the next browser to open will log 'enabled'
- Services.prefs.setBoolPref(PREF, true);
-});
-
-
-add_task(function* testNewWindow() {
- let newWin = yield promiseOpenAndLoadWindow({}, true);
- let tab = newWin.gBrowser.selectedTab = newWin.gBrowser.addTab();
- let TrackingProtection = newWin.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
-
- is(getEnabledCounts()[0], 1, "TP was disabled once on start up");
- is(getEnabledCounts()[1], 1, "TP was enabled once on start up");
-
- // Reset these to make counting easier
- getEventsHistogram().clear();
- getShieldHistogram().clear();
-
- yield promiseTabLoadEvent(tab, BENIGN_PAGE);
- is(getEventCounts()[0], 1, "Total page loads");
- is(getEventCounts()[1], 0, "Disable actions");
- is(getEventCounts()[2], 0, "Enable actions");
- is(getShieldCounts()[0], 1, "Page loads without tracking");
-
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- // Note that right now the events and shield histogram is not measuring what
- // you might think. Since onSecurityChange fires twice for a tracking page,
- // the total page loads count is double counting, and the shield count
- // (which is meant to measure times when the shield wasn't shown) fires even
- // when tracking elements exist on the page.
- todo_is(getEventCounts()[0], 2, "FIXME: TOTAL PAGE LOADS IS DOUBLE COUNTING");
- is(getEventCounts()[1], 0, "Disable actions");
- is(getEventCounts()[2], 0, "Enable actions");
- todo_is(getShieldCounts()[0], 1, "FIXME: TOTAL PAGE LOADS WITHOUT TRACKING IS DOUBLE COUNTING");
-
- info("Disable TP for the page (which reloads the page)");
- let tabReloadPromise = promiseTabLoadEvent(tab);
- newWin.document.querySelector("#tracking-action-unblock").doCommand();
- yield tabReloadPromise;
- todo_is(getEventCounts()[0], 3, "FIXME: TOTAL PAGE LOADS IS DOUBLE COUNTING");
- is(getEventCounts()[1], 1, "Disable actions");
- is(getEventCounts()[2], 0, "Enable actions");
- todo_is(getShieldCounts()[0], 1, "FIXME: TOTAL PAGE LOADS WITHOUT TRACKING IS DOUBLE COUNTING");
-
- info("Re-enable TP for the page (which reloads the page)");
- tabReloadPromise = promiseTabLoadEvent(tab);
- newWin.document.querySelector("#tracking-action-block").doCommand();
- yield tabReloadPromise;
- todo_is(getEventCounts()[0], 4, "FIXME: TOTAL PAGE LOADS IS DOUBLE COUNTING");
- is(getEventCounts()[1], 1, "Disable actions");
- is(getEventCounts()[2], 1, "Enable actions");
- todo_is(getShieldCounts()[0], 1, "FIXME: TOTAL PAGE LOADS WITHOUT TRACKING IS DOUBLE COUNTING");
-
- yield promiseWindowClosed(newWin);
-
- // Reset these to make counting easier for the next test
- getEventsHistogram().clear();
- getShieldHistogram().clear();
- getEnabledHistogram().clear();
-});
-
-add_task(function* testPrivateBrowsing() {
- let privateWin = yield promiseOpenAndLoadWindow({private: true}, true);
- let tab = privateWin.gBrowser.selectedTab = privateWin.gBrowser.addTab();
- let TrackingProtection = privateWin.TrackingProtection;
- ok(TrackingProtection, "TP is attached to the browser window");
-
- // Do a bunch of actions and make sure that no telemetry data is gathered
- yield promiseTabLoadEvent(tab, BENIGN_PAGE);
- yield promiseTabLoadEvent(tab, TRACKING_PAGE);
- let tabReloadPromise = promiseTabLoadEvent(tab);
- privateWin.document.querySelector("#tracking-action-unblock").doCommand();
- yield tabReloadPromise;
- tabReloadPromise = promiseTabLoadEvent(tab);
- privateWin.document.querySelector("#tracking-action-block").doCommand();
- yield tabReloadPromise;
-
- // Sum up all the counts to make sure that nothing got logged
- is(getEnabledCounts().reduce((p, c) => p+c), 0, "Telemetry logging off in PB mode");
- is(getEventCounts().reduce((p, c) => p+c), 0, "Telemetry logging off in PB mode");
- is(getShieldCounts().reduce((p, c) => p+c), 0, "Telemetry logging off in PB mode");
-
- yield promiseWindowClosed(privateWin);
-});
diff --git a/browser/base/content/test/general/browser_typeAheadFind.js b/browser/base/content/test/general/browser_typeAheadFind.js
deleted file mode 100644
index 1d550944a..000000000
--- a/browser/base/content/test/general/browser_typeAheadFind.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* 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/. */
-
-add_task(function *() {
- let testWindow = yield BrowserTestUtils.openNewBrowserWindow();
-
- testWindow.gBrowser.loadURI("data:text/html,<h1>A Page</h1>");
- yield BrowserTestUtils.browserLoaded(testWindow.gBrowser.selectedBrowser);
-
- yield SimpleTest.promiseFocus(testWindow.gBrowser.selectedBrowser);
-
- ok(!testWindow.gFindBarInitialized, "find bar is not initialized");
-
- let findBarOpenPromise = promiseWaitForEvent(testWindow.gBrowser, "findbaropen");
- EventUtils.synthesizeKey("/", {}, testWindow);
- yield findBarOpenPromise;
-
- ok(testWindow.gFindBarInitialized, "find bar is now initialized");
-
- yield BrowserTestUtils.closeWindow(testWindow);
-});
diff --git a/browser/base/content/test/general/browser_unknownContentType_title.js b/browser/base/content/test/general/browser_unknownContentType_title.js
deleted file mode 100644
index 269406bdb..000000000
--- a/browser/base/content/test/general/browser_unknownContentType_title.js
+++ /dev/null
@@ -1,33 +0,0 @@
-const url = "data:text/html;charset=utf-8,%3C%21DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3Ctitle%3ETest%20Page%3C%2Ftitle%3E%3C%2Fhead%3E%3C%2Fhtml%3E";
-const unknown_url = "http://example.com/browser/browser/base/content/test/general/unknownContentType_file.pif";
-
-function waitForNewWindow() {
- return new Promise(resolve => {
- let listener = (win) => {
- Services.obs.removeObserver(listener, "toplevel-window-ready");
- win.addEventListener("load", () => {
- resolve(win);
- });
- };
-
- Services.obs.addObserver(listener, "toplevel-window-ready", false)
- });
-}
-
-add_task(function*() {
- let tab = gBrowser.selectedTab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- yield promiseTabLoaded(gBrowser.selectedTab);
-
- is(gBrowser.contentTitle, "Test Page", "Should have the right title.")
-
- browser.loadURI(unknown_url);
- let win = yield waitForNewWindow();
- is(win.location, "chrome://mozapps/content/downloads/unknownContentType.xul",
- "Should have seen the unknown content dialog.");
- is(gBrowser.contentTitle, "Test Page", "Should still have the right title.")
-
- win.close();
- yield promiseWaitForFocus(window);
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/general/browser_unloaddialogs.js b/browser/base/content/test/general/browser_unloaddialogs.js
deleted file mode 100644
index bf3790b95..000000000
--- a/browser/base/content/test/general/browser_unloaddialogs.js
+++ /dev/null
@@ -1,41 +0,0 @@
-var testUrls =
- [
- "data:text/html,<script>" +
- "function handle(evt) {" +
- "evt.target.removeEventListener(evt.type, handle, true);" +
- "try { alert('This should NOT appear'); } catch(e) { }" +
- "}" +
- "window.addEventListener('pagehide', handle, true);" +
- "window.addEventListener('beforeunload', handle, true);" +
- "window.addEventListener('unload', handle, true);" +
- "</script><body>Testing alert during pagehide/beforeunload/unload</body>",
- "data:text/html,<script>" +
- "function handle(evt) {" +
- "evt.target.removeEventListener(evt.type, handle, true);" +
- "try { prompt('This should NOT appear'); } catch(e) { }" +
- "}" +
- "window.addEventListener('pagehide', handle, true);" +
- "window.addEventListener('beforeunload', handle, true);" +
- "window.addEventListener('unload', handle, true);" +
- "</script><body>Testing prompt during pagehide/beforeunload/unload</body>",
- "data:text/html,<script>" +
- "function handle(evt) {" +
- "evt.target.removeEventListener(evt.type, handle, true);" +
- "try { confirm('This should NOT appear'); } catch(e) { }" +
- "}" +
- "window.addEventListener('pagehide', handle, true);" +
- "window.addEventListener('beforeunload', handle, true);" +
- "window.addEventListener('unload', handle, true);" +
- "</script><body>Testing confirm during pagehide/beforeunload/unload</body>",
- ];
-
-add_task(function*() {
- for (let url of testUrls) {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
- ok(true, "Loaded page " + url);
- // Wait one turn of the event loop before closing, so everything settles.
- yield new Promise(resolve => setTimeout(resolve, 0));
- yield BrowserTestUtils.removeTab(tab);
- ok(true, "Closed page " + url + " without timeout");
- }
-});
diff --git a/browser/base/content/test/general/browser_utilityOverlay.js b/browser/base/content/test/general/browser_utilityOverlay.js
deleted file mode 100644
index 34adc00d9..000000000
--- a/browser/base/content/test/general/browser_utilityOverlay.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* 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/. */
-
-const gTests = [
- test_eventMatchesKey,
- test_getTopWin,
- test_getBoolPref,
- test_openNewTabWith,
- test_openUILink
-];
-
-function test () {
- waitForExplicitFinish();
- executeSoon(runNextTest);
-}
-
-function runNextTest() {
- if (gTests.length) {
- let testFun = gTests.shift();
- info("Running " + testFun.name);
- testFun()
- }
- else {
- finish();
- }
-}
-
-function test_eventMatchesKey() {
- let eventMatchResult;
- let key;
- let checkEvent = function(e) {
- e.stopPropagation();
- e.preventDefault();
- eventMatchResult = eventMatchesKey(e, key);
- }
- document.addEventListener("keypress", checkEvent);
-
- try {
- key = document.createElement("key");
- let keyset = document.getElementById("mainKeyset");
- key.setAttribute("key", "t");
- key.setAttribute("modifiers", "accel");
- keyset.appendChild(key);
- EventUtils.synthesizeKey("t", {accelKey: true});
- is(eventMatchResult, true, "eventMatchesKey: one modifier");
- keyset.removeChild(key);
-
- key = document.createElement("key");
- key.setAttribute("key", "g");
- key.setAttribute("modifiers", "accel,shift");
- keyset.appendChild(key);
- EventUtils.synthesizeKey("g", {accelKey: true, shiftKey: true});
- is(eventMatchResult, true, "eventMatchesKey: combination modifiers");
- keyset.removeChild(key);
-
- key = document.createElement("key");
- key.setAttribute("key", "w");
- key.setAttribute("modifiers", "accel");
- keyset.appendChild(key);
- EventUtils.synthesizeKey("f", {accelKey: true});
- is(eventMatchResult, false, "eventMatchesKey: mismatch keys");
- keyset.removeChild(key);
-
- key = document.createElement("key");
- key.setAttribute("keycode", "VK_DELETE");
- keyset.appendChild(key);
- EventUtils.synthesizeKey("VK_DELETE", {accelKey: true});
- is(eventMatchResult, false, "eventMatchesKey: mismatch modifiers");
- keyset.removeChild(key);
- } finally {
- // Make sure to remove the event listener so future tests don't
- // fail when they simulate key presses.
- document.removeEventListener("keypress", checkEvent);
- }
-
- runNextTest();
-}
-
-function test_getTopWin() {
- is(getTopWin(), window, "got top window");
- runNextTest();
-}
-
-
-function test_getBoolPref() {
- is(getBoolPref("browser.search.openintab", false), false, "getBoolPref");
- is(getBoolPref("this.pref.doesnt.exist", true), true, "getBoolPref fallback");
- is(getBoolPref("this.pref.doesnt.exist", false), false, "getBoolPref fallback #2");
- runNextTest();
-}
-
-function test_openNewTabWith() {
- openNewTabWith("http://example.com/");
- let tab = gBrowser.selectedTab = gBrowser.tabs[1];
- BrowserTestUtils.browserLoaded(tab.linkedBrowser).then(() => {
- is(tab.linkedBrowser.currentURI.spec, "http://example.com/", "example.com loaded");
- gBrowser.removeCurrentTab();
- runNextTest();
- });
-}
-
-function test_openUILink() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- BrowserTestUtils.browserLoaded(tab.linkedBrowser).then(() => {
- is(tab.linkedBrowser.currentURI.spec, "http://example.org/", "example.org loaded");
- gBrowser.removeCurrentTab();
- runNextTest();
- });
-
- openUILink("http://example.org/"); // defaults to "current"
-}
diff --git a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js
deleted file mode 100644
index c8f3cdc96..000000000
--- a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js
+++ /dev/null
@@ -1,55 +0,0 @@
-function wait_while_tab_is_busy() {
- return new Promise(resolve => {
- let progressListener = {
- onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
- if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
- gBrowser.removeProgressListener(this);
- setTimeout(resolve, 0);
- }
- }
- };
- gBrowser.addProgressListener(progressListener);
- });
-}
-
-// This function waits for the tab to stop being busy instead of waiting for it
-// to load, since the canViewSource change happens at that time.
-var with_new_tab_opened = Task.async(function* (options, taskFn) {
- let busyPromise = wait_while_tab_is_busy();
- let tab = yield BrowserTestUtils.openNewForegroundTab(options.gBrowser, options.url, false);
- yield busyPromise;
- yield taskFn(tab.linkedBrowser);
- gBrowser.removeTab(tab);
-});
-
-add_task(function*() {
- yield new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": [
- ["view_source.tab", true],
- ]}, resolve);
- });
-});
-
-add_task(function* test_regular_page() {
- function* test_expect_view_source_enabled(browser) {
- ok(!XULBrowserWindow.canViewSource.hasAttribute("disabled"),
- "View Source should be enabled");
- }
-
- yield with_new_tab_opened({
- gBrowser,
- url: "http://example.com",
- }, test_expect_view_source_enabled);
-});
-
-add_task(function* test_view_source_page() {
- function* test_expect_view_source_disabled(browser) {
- ok(XULBrowserWindow.canViewSource.hasAttribute("disabled"),
- "View Source should be disabled");
- }
-
- yield with_new_tab_opened({
- gBrowser,
- url: "view-source:http://example.com",
- }, test_expect_view_source_disabled);
-});
diff --git a/browser/base/content/test/general/browser_visibleFindSelection.js b/browser/base/content/test/general/browser_visibleFindSelection.js
deleted file mode 100644
index 630490644..000000000
--- a/browser/base/content/test/general/browser_visibleFindSelection.js
+++ /dev/null
@@ -1,52 +0,0 @@
-add_task(function*() {
- const childContent = "<div style='position: absolute; left: 2200px; background: green; width: 200px; height: 200px;'>" +
- "div</div><div style='position: absolute; left: 0px; background: red; width: 200px; height: 200px;'>" +
- "<span id='s'>div</span></div>";
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- yield promiseTabLoadEvent(tab, "data:text/html," + escape(childContent));
- yield SimpleTest.promiseFocus(gBrowser.selectedBrowser.contentWindowAsCPOW);
-
- let findBarOpenPromise = promiseWaitForEvent(gBrowser, "findbaropen");
- EventUtils.synthesizeKey("f", { accelKey: true });
- yield findBarOpenPromise;
-
- ok(gFindBarInitialized, "find bar is now initialized");
-
- // Finds the div in the green box.
- let scrollPromise = promiseWaitForEvent(gBrowser, "scroll");
- EventUtils.synthesizeKey("d", {});
- EventUtils.synthesizeKey("i", {});
- EventUtils.synthesizeKey("v", {});
- yield scrollPromise;
-
- // Wait for one paint to ensure we've processed the previous key events and scrolling.
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- return new Promise(
- resolve => {
- content.requestAnimationFrame(() => {
- setTimeout(resolve, 0);
- });
- }
- );
- });
-
- // Finds the div in the red box.
- scrollPromise = promiseWaitForEvent(gBrowser, "scroll");
- EventUtils.synthesizeKey("g", { accelKey: true });
- yield scrollPromise;
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- Assert.ok(content.document.getElementById("s").getBoundingClientRect().left >= 0,
- "scroll should include find result");
- });
-
- // clear the find bar
- EventUtils.synthesizeKey("a", { accelKey: true });
- EventUtils.synthesizeKey("VK_DELETE", { });
-
- gFindBar.close();
- gBrowser.removeCurrentTab();
-});
-
diff --git a/browser/base/content/test/general/browser_visibleTabs.js b/browser/base/content/test/general/browser_visibleTabs.js
deleted file mode 100644
index e9130bc18..000000000
--- a/browser/base/content/test/general/browser_visibleTabs.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function* () {
- // There should be one tab when we start the test
- let [origTab] = gBrowser.visibleTabs;
-
- // Add a tab that will get pinned
- let pinned = gBrowser.addTab();
- gBrowser.pinTab(pinned);
-
- let testTab = gBrowser.addTab();
-
- let visible = gBrowser.visibleTabs;
- is(visible.length, 3, "3 tabs should be open");
- is(visible[0], pinned, "the pinned tab is first");
- is(visible[1], origTab, "original tab is next");
- is(visible[2], testTab, "last created tab is last");
-
- // Only show the test tab (but also get pinned and selected)
- is(gBrowser.selectedTab, origTab, "sanity check that we're on the original tab");
- gBrowser.showOnlyTheseTabs([testTab]);
- is(gBrowser.visibleTabs.length, 3, "all 3 tabs are still visible");
-
- // Select the test tab and only show that (and pinned)
- gBrowser.selectedTab = testTab;
- gBrowser.showOnlyTheseTabs([testTab]);
-
- visible = gBrowser.visibleTabs;
- is(visible.length, 2, "2 tabs should be visible including the pinned");
- is(visible[0], pinned, "first is pinned");
- is(visible[1], testTab, "next is the test tab");
- is(gBrowser.tabs.length, 3, "3 tabs should still be open");
-
- gBrowser.selectTabAtIndex(1);
- is(gBrowser.selectedTab, testTab, "second tab is the test tab");
- gBrowser.selectTabAtIndex(0);
- is(gBrowser.selectedTab, pinned, "first tab is pinned");
- gBrowser.selectTabAtIndex(2);
- is(gBrowser.selectedTab, testTab, "no third tab, so no change");
- gBrowser.selectTabAtIndex(0);
- is(gBrowser.selectedTab, pinned, "switch back to the pinned");
- gBrowser.selectTabAtIndex(2);
- is(gBrowser.selectedTab, testTab, "no third tab, so select last tab");
- gBrowser.selectTabAtIndex(-2);
- is(gBrowser.selectedTab, pinned, "pinned tab is second from left (when orig tab is hidden)");
- gBrowser.selectTabAtIndex(-1);
- is(gBrowser.selectedTab, testTab, "last tab is the test tab");
-
- gBrowser.tabContainer.advanceSelectedTab(1, true);
- is(gBrowser.selectedTab, pinned, "wrapped around the end to pinned");
- gBrowser.tabContainer.advanceSelectedTab(1, true);
- is(gBrowser.selectedTab, testTab, "next to test tab");
- gBrowser.tabContainer.advanceSelectedTab(1, true);
- is(gBrowser.selectedTab, pinned, "next to pinned again");
-
- gBrowser.tabContainer.advanceSelectedTab(-1, true);
- is(gBrowser.selectedTab, testTab, "going backwards to last tab");
- gBrowser.tabContainer.advanceSelectedTab(-1, true);
- is(gBrowser.selectedTab, pinned, "next to pinned");
- gBrowser.tabContainer.advanceSelectedTab(-1, true);
- is(gBrowser.selectedTab, testTab, "next to test tab again");
-
- // Try showing all tabs
- gBrowser.showOnlyTheseTabs(Array.slice(gBrowser.tabs));
- is(gBrowser.visibleTabs.length, 3, "all 3 tabs are visible again");
-
- // Select the pinned tab and show the testTab to make sure selection updates
- gBrowser.selectedTab = pinned;
- gBrowser.showOnlyTheseTabs([testTab]);
- is(gBrowser.tabs[1], origTab, "make sure origTab is in the middle");
- is(origTab.hidden, true, "make sure it's hidden");
- gBrowser.removeTab(pinned);
- is(gBrowser.selectedTab, testTab, "making sure origTab was skipped");
- is(gBrowser.visibleTabs.length, 1, "only testTab is there");
-
- // Only show one of the non-pinned tabs (but testTab is selected)
- gBrowser.showOnlyTheseTabs([origTab]);
- is(gBrowser.visibleTabs.length, 2, "got 2 tabs");
-
- // Now really only show one of the tabs
- gBrowser.showOnlyTheseTabs([testTab]);
- visible = gBrowser.visibleTabs;
- is(visible.length, 1, "only the original tab is visible");
- is(visible[0], testTab, "it's the original tab");
- is(gBrowser.tabs.length, 2, "still have 2 open tabs");
-
- // Close the last visible tab and make sure we still get a visible tab
- gBrowser.removeTab(testTab);
- is(gBrowser.visibleTabs.length, 1, "only orig is left and visible");
- is(gBrowser.tabs.length, 1, "sanity check that it matches");
- is(gBrowser.selectedTab, origTab, "got the orig tab");
- is(origTab.hidden, false, "and it's not hidden -- visible!");
-});
diff --git a/browser/base/content/test/general/browser_visibleTabs_bookmarkAllPages.js b/browser/base/content/test/general/browser_visibleTabs_bookmarkAllPages.js
deleted file mode 100644
index 827f86c05..000000000
--- a/browser/base/content/test/general/browser_visibleTabs_bookmarkAllPages.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- let tabOne = gBrowser.addTab("about:blank");
- let tabTwo = gBrowser.addTab("http://mochi.test:8888/");
- gBrowser.selectedTab = tabTwo;
-
- let browser = gBrowser.getBrowserForTab(tabTwo);
- let onLoad = function() {
- browser.removeEventListener("load", onLoad, true);
-
- gBrowser.showOnlyTheseTabs([tabTwo]);
-
- is(gBrowser.visibleTabs.length, 1, "Only one tab is visible");
-
- let uris = PlacesCommandHook.uniqueCurrentPages;
- is(uris.length, 1, "Only one uri is returned");
-
- is(uris[0].uri.spec, tabTwo.linkedBrowser.currentURI.spec, "It's the correct URI");
-
- gBrowser.removeTab(tabOne);
- gBrowser.removeTab(tabTwo);
- Array.forEach(gBrowser.tabs, function(tab) {
- gBrowser.showTab(tab);
- });
-
- finish();
- }
- browser.addEventListener("load", onLoad, true);
-}
diff --git a/browser/base/content/test/general/browser_visibleTabs_bookmarkAllTabs.js b/browser/base/content/test/general/browser_visibleTabs_bookmarkAllTabs.js
deleted file mode 100644
index 0a0ea87bd..000000000
--- a/browser/base/content/test/general/browser_visibleTabs_bookmarkAllTabs.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- // There should be one tab when we start the test
- let [origTab] = gBrowser.visibleTabs;
- is(gBrowser.visibleTabs.length, 1, "1 tab should be open");
- is(Disabled(), true, "Bookmark All Tabs should be disabled");
-
- // Add a tab
- let testTab1 = gBrowser.addTab();
- is(gBrowser.visibleTabs.length, 2, "2 tabs should be open");
- is(Disabled(), true, "Bookmark All Tabs should be disabled since there are two tabs with the same address");
-
- let testTab2 = gBrowser.addTab("about:mozilla");
- is(gBrowser.visibleTabs.length, 3, "3 tabs should be open");
- // Wait for tab load, the code checks for currentURI.
- testTab2.linkedBrowser.addEventListener("load", function () {
- testTab2.linkedBrowser.removeEventListener("load", arguments.callee, true);
- is(Disabled(), false, "Bookmark All Tabs should be enabled since there are two tabs with different addresses");
-
- // Hide the original tab
- gBrowser.selectedTab = testTab2;
- gBrowser.showOnlyTheseTabs([testTab2]);
- is(gBrowser.visibleTabs.length, 1, "1 tab should be visible");
- is(Disabled(), true, "Bookmark All Tabs should be disabled as there is only one visible tab");
-
- // Add a tab that will get pinned
- let pinned = gBrowser.addTab();
- is(gBrowser.visibleTabs.length, 2, "2 tabs should be visible now");
- is(Disabled(), false, "Bookmark All Tabs should be available as there are two visible tabs");
- gBrowser.pinTab(pinned);
- is(Hidden(), false, "Bookmark All Tabs should be visible on a normal tab");
- is(Disabled(), true, "Bookmark All Tabs should not be available since one tab is pinned");
- gBrowser.selectedTab = pinned;
- is(Hidden(), true, "Bookmark All Tabs should be hidden on a pinned tab");
-
- // Show all tabs
- let allTabs = Array.from(gBrowser.tabs);
- gBrowser.showOnlyTheseTabs(allTabs);
-
- // reset the environment
- gBrowser.removeTab(testTab2);
- gBrowser.removeTab(testTab1);
- gBrowser.removeTab(pinned);
- is(gBrowser.visibleTabs.length, 1, "only orig is left and visible");
- is(gBrowser.tabs.length, 1, "sanity check that it matches");
- is(Disabled(), true, "Bookmark All Tabs should be hidden");
- is(gBrowser.selectedTab, origTab, "got the orig tab");
- is(origTab.hidden, false, "and it's not hidden -- visible!");
- finish();
- }, true);
-}
-
-function Disabled() {
- updateTabContextMenu();
- return document.getElementById("Browser:BookmarkAllTabs").getAttribute("disabled") == "true";
-}
-
-function Hidden() {
- updateTabContextMenu();
- return document.getElementById("context_bookmarkAllTabs").hidden;
-}
diff --git a/browser/base/content/test/general/browser_visibleTabs_contextMenu.js b/browser/base/content/test/general/browser_visibleTabs_contextMenu.js
deleted file mode 100644
index 4fdab3d8a..000000000
--- a/browser/base/content/test/general/browser_visibleTabs_contextMenu.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* 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/. */
-
-const remoteClientsFixture = [ { id: 1, name: "Foo"}, { id: 2, name: "Bar"} ];
-
-add_task(function* test() {
- // There should be one tab when we start the test
- let [origTab] = gBrowser.visibleTabs;
- is(gBrowser.visibleTabs.length, 1, "there is one visible tab");
- let testTab = gBrowser.addTab();
- is(gBrowser.visibleTabs.length, 2, "there are now two visible tabs");
-
- // Check the context menu with two tabs
- updateTabContextMenu(origTab);
- is(document.getElementById("context_closeTab").disabled, false, "Close Tab is enabled");
- is(document.getElementById("context_reloadAllTabs").disabled, false, "Reload All Tabs is enabled");
-
-
- if (gFxAccounts.sendTabToDeviceEnabled) {
- // Check the send tab to device menu item
- const oldGetter = setupRemoteClientsFixture(remoteClientsFixture);
- yield updateTabContextMenu(origTab, function* () {
- yield openMenuItemSubmenu("context_sendTabToDevice");
- });
- is(document.getElementById("context_sendTabToDevice").hidden, false, "Send tab to device is shown");
- let targets = document.getElementById("context_sendTabToDevicePopupMenu").childNodes;
- is(targets[0].getAttribute("label"), "Foo", "Foo target is present");
- is(targets[1].getAttribute("label"), "Bar", "Bar target is present");
- is(targets[3].getAttribute("label"), "All Devices", "All Devices target is present");
- restoreRemoteClients(oldGetter);
- }
-
- // Hide the original tab.
- gBrowser.selectedTab = testTab;
- gBrowser.showOnlyTheseTabs([testTab]);
- is(gBrowser.visibleTabs.length, 1, "now there is only one visible tab");
-
- // Check the context menu with one tab.
- updateTabContextMenu(testTab);
- is(document.getElementById("context_closeTab").disabled, false, "Close Tab is enabled when more than one tab exists");
- is(document.getElementById("context_reloadAllTabs").disabled, true, "Reload All Tabs is disabled");
-
- // Add a tab that will get pinned
- // So now there's one pinned tab, one visible unpinned tab, and one hidden tab
- let pinned = gBrowser.addTab();
- gBrowser.pinTab(pinned);
- is(gBrowser.visibleTabs.length, 2, "now there are two visible tabs");
-
- // Check the context menu on the unpinned visible tab
- updateTabContextMenu(testTab);
- is(document.getElementById("context_closeOtherTabs").disabled, true, "Close Other Tabs is disabled");
- is(document.getElementById("context_closeTabsToTheEnd").disabled, true, "Close Tabs To The End is disabled");
-
- // Show all tabs
- let allTabs = Array.from(gBrowser.tabs);
- gBrowser.showOnlyTheseTabs(allTabs);
-
- // Check the context menu now
- updateTabContextMenu(testTab);
- is(document.getElementById("context_closeOtherTabs").disabled, false, "Close Other Tabs is enabled");
- is(document.getElementById("context_closeTabsToTheEnd").disabled, true, "Close Tabs To The End is disabled");
-
- // Check the context menu of the original tab
- // Close Tabs To The End should now be enabled
- updateTabContextMenu(origTab);
- is(document.getElementById("context_closeTabsToTheEnd").disabled, false, "Close Tabs To The End is enabled");
-
- gBrowser.removeTab(testTab);
- gBrowser.removeTab(pinned);
-});
-
diff --git a/browser/base/content/test/general/browser_visibleTabs_tabPreview.js b/browser/base/content/test/general/browser_visibleTabs_tabPreview.js
deleted file mode 100644
index 7ce4b143f..000000000
--- a/browser/base/content/test/general/browser_visibleTabs_tabPreview.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* 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/. */
-
-add_task(function* test() {
- gPrefService.setBoolPref("browser.ctrlTab.previews", true);
-
- let [origTab] = gBrowser.visibleTabs;
- let tabOne = gBrowser.addTab();
- let tabTwo = gBrowser.addTab();
-
- // test the ctrlTab.tabList
- pressCtrlTab();
- ok(ctrlTab.tabList.length, 3, "Show 3 tabs in tab preview");
- releaseCtrl();
-
- gBrowser.showOnlyTheseTabs([origTab]);
- pressCtrlTab();
- ok(ctrlTab.tabList.length, 1, "Show 1 tab in tab preview");
- ok(!ctrlTab.isOpen, "With 1 tab open, Ctrl+Tab doesn't open the preview panel");
-
- gBrowser.showOnlyTheseTabs([origTab, tabOne, tabTwo]);
- pressCtrlTab();
- ok(ctrlTab.isOpen, "With 3 tabs open, Ctrl+Tab does open the preview panel");
- releaseCtrl();
-
- // cleanup
- gBrowser.removeTab(tabOne);
- gBrowser.removeTab(tabTwo);
-
- if (gPrefService.prefHasUserValue("browser.ctrlTab.previews"))
- gPrefService.clearUserPref("browser.ctrlTab.previews");
-});
-
-function pressCtrlTab(aShiftKey) {
- EventUtils.synthesizeKey("VK_TAB", { ctrlKey: true, shiftKey: !!aShiftKey });
-}
-
-function releaseCtrl() {
- EventUtils.synthesizeKey("VK_CONTROL", { type: "keyup" });
-}
diff --git a/browser/base/content/test/general/browser_web_channel.html b/browser/base/content/test/general/browser_web_channel.html
deleted file mode 100644
index f117ccca2..000000000
--- a/browser/base/content/test/general/browser_web_channel.html
+++ /dev/null
@@ -1,189 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>web_channel_test</title>
-</head>
-<body>
-<script>
- var IFRAME_SRC_ROOT = "http://mochi.test:8888/browser/browser/base/content/test/general/browser_web_channel_iframe.html";
-
- window.onload = function() {
- var testName = window.location.search.replace(/^\?/, "");
-
- switch (testName) {
- case "generic":
- test_generic();
- break;
- case "twoway":
- test_twoWay();
- break;
- case "multichannel":
- test_multichannel();
- break;
- case "iframe":
- test_iframe();
- break;
- case "iframe_pre_redirect":
- test_iframe_pre_redirect();
- break;
- case "unsolicited":
- test_unsolicited();
- break;
- case "bubbles":
- test_bubbles();
- break;
- case "object":
- test_object();
- break;
- default:
- throw new Error(`INVALID TEST NAME ${testName}`);
- }
- };
-
- function test_generic() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "generic",
- message: {
- something: {
- nested: "hello",
- },
- }
- })
- });
-
- window.dispatchEvent(event);
- }
-
- function test_twoWay() {
- var firstMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "twoway",
- message: {
- command: "one",
- },
- })
- });
-
- window.addEventListener("WebChannelMessageToContent", function(e) {
- var secondMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "twoway",
- message: {
- command: "two",
- detail: e.detail.message,
- },
- }),
- });
-
- if (!e.detail.message.error) {
- window.dispatchEvent(secondMessage);
- }
- }, true);
-
- window.dispatchEvent(firstMessage);
- }
-
- function test_multichannel() {
- var event1 = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "wrongchannel",
- message: {},
- })
- });
-
- var event2 = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "multichannel",
- message: {},
- })
- });
-
- window.dispatchEvent(event1);
- window.dispatchEvent(event2);
- }
-
- function test_iframe() {
- // Note that this message is the response to the message sent
- // by the iframe! This is bad, as this page is *not* trusted.
- window.addEventListener("WebChannelMessageToContent", function(e) {
- // the test parent will fail if the echo message is received.
- echoEventToChannel(e, "echo");
- });
-
- // only attach the iframe for the iframe test to avoid
- // interfering with other tests.
- var iframe = document.createElement("iframe");
- iframe.setAttribute("src", IFRAME_SRC_ROOT + "?iframe");
- document.body.appendChild(iframe);
- }
-
- function test_iframe_pre_redirect() {
- var iframe = document.createElement("iframe");
- iframe.setAttribute("src", IFRAME_SRC_ROOT + "?iframe_pre_redirect");
- document.body.appendChild(iframe);
- }
-
- function test_unsolicited() {
- // echo any unsolicted events back to chrome.
- window.addEventListener("WebChannelMessageToContent", function(e) {
- echoEventToChannel(e, "echo");
- }, true);
- }
-
- function test_bubbles() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "not_a_window",
- message: {
- command: "start"
- }
- })
- });
-
- var nonWindowTarget = document.getElementById("not_a_window");
-
- nonWindowTarget.addEventListener("WebChannelMessageToContent", function(e) {
- echoEventToChannel(e, "not_a_window");
- }, true);
-
-
- nonWindowTarget.dispatchEvent(event);
- }
-
- function test_object() {
- let objectMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "objects",
- message: { type: "object" }
- }
- });
-
- let stringMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "objects",
- message: { type: "string" }
- })
- });
- // Test fails if objectMessage is received, we send stringMessage to know
- // when we should stop listening for objectMessage
- window.dispatchEvent(objectMessage);
- window.dispatchEvent(stringMessage);
- }
-
- function echoEventToChannel(e, channelId) {
- var echoedEvent = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: channelId,
- message: e.detail.message,
- })
- });
-
- e.target.dispatchEvent(echoedEvent);
- }
-</script>
-
-<div id="not_a_window"></div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/browser_web_channel.js b/browser/base/content/test/general/browser_web_channel.js
deleted file mode 100644
index abc1c6fef..000000000
--- a/browser/base/content/test/general/browser_web_channel.js
+++ /dev/null
@@ -1,436 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "WebChannel",
- "resource://gre/modules/WebChannel.jsm");
-
-const HTTP_PATH = "http://example.com";
-const HTTP_ENDPOINT = "/browser/browser/base/content/test/general/browser_web_channel.html";
-const HTTP_MISMATCH_PATH = "http://example.org";
-const HTTP_IFRAME_PATH = "http://mochi.test:8888";
-const HTTP_REDIRECTED_IFRAME_PATH = "http://example.org";
-
-requestLongerTimeout(2); // timeouts in debug builds.
-
-// Keep this synced with /mobile/android/tests/browser/robocop/testWebChannel.js
-// as much as possible. (We only have that since we can't run browser chrome
-// tests on Android. Yet?)
-var gTests = [
- {
- desc: "WebChannel generic message",
- run: function* () {
- return new Promise(function(resolve, reject) {
- let tab;
- let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null));
- channel.listen(function (id, message, target) {
- is(id, "generic");
- is(message.something.nested, "hello");
- channel.stopListening();
- gBrowser.removeTab(tab);
- resolve();
- });
-
- tab = gBrowser.addTab(HTTP_PATH + HTTP_ENDPOINT + "?generic");
- });
- }
- },
- {
- desc: "WebChannel generic message in a private window.",
- run: function* () {
- let promiseTestDone = new Promise(function(resolve, reject) {
- let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null));
- channel.listen(function(id, message, target) {
- is(id, "generic");
- is(message.something.nested, "hello");
- channel.stopListening();
- resolve();
- });
- });
-
- const url = HTTP_PATH + HTTP_ENDPOINT + "?generic";
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield BrowserTestUtils.openNewForegroundTab(privateWindow.gBrowser, url);
- yield promiseTestDone;
- yield BrowserTestUtils.closeWindow(privateWindow);
- }
- },
- {
- desc: "WebChannel two way communication",
- run: function* () {
- return new Promise(function(resolve, reject) {
- let tab;
- let channel = new WebChannel("twoway", Services.io.newURI(HTTP_PATH, null, null));
-
- channel.listen(function (id, message, sender) {
- is(id, "twoway", "bad id");
- ok(message.command, "command not ok");
-
- if (message.command === "one") {
- channel.send({ data: { nested: true } }, sender);
- }
-
- if (message.command === "two") {
- is(message.detail.data.nested, true);
- channel.stopListening();
- gBrowser.removeTab(tab);
- resolve();
- }
- });
-
- tab = gBrowser.addTab(HTTP_PATH + HTTP_ENDPOINT + "?twoway");
- });
- }
- },
- {
- desc: "WebChannel two way communication in an iframe",
- run: function* () {
- let parentChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null));
- let iframeChannel = new WebChannel("twoway", Services.io.newURI(HTTP_IFRAME_PATH, null, null));
- let promiseTestDone = new Promise(function (resolve, reject) {
- parentChannel.listen(function (id, message, sender) {
- reject(new Error("WebChannel message incorrectly sent to parent"));
- });
-
- iframeChannel.listen(function (id, message, sender) {
- is(id, "twoway", "bad id (2)");
- ok(message.command, "command not ok (2)");
-
- if (message.command === "one") {
- iframeChannel.send({ data: { nested: true } }, sender);
- }
-
- if (message.command === "two") {
- is(message.detail.data.nested, true);
- resolve();
- }
- });
- });
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?iframe"
- }, function* () {
- yield promiseTestDone;
- parentChannel.stopListening();
- iframeChannel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel response to a redirected iframe",
- run: function* () {
- /**
- * This test checks that WebChannel responses are only sent
- * to an iframe if the iframe has not redirected to another origin.
- * Test flow:
- * 1. create a page, embed an iframe on origin A.
- * 2. the iframe sends a message `redirecting`, then redirects to
- * origin B.
- * 3. the iframe at origin B is set up to echo any messages back to the
- * test parent.
- * 4. the test parent receives the `redirecting` message from origin A.
- * the test parent creates a new channel with origin B.
- * 5. when origin B is ready, it sends a `loaded` message to the test
- * parent, letting the test parent know origin B is ready to echo
- * messages.
- * 5. the test parent tries to send a response to origin A. If the
- * WebChannel does not perform a valid origin check, the response
- * will be received by origin B. If the WebChannel does perform
- * a valid origin check, the response will not be sent.
- * 6. the test parent sends a `done` message to origin B, which origin
- * B echoes back. If the response to origin A is not echoed but
- * the message to origin B is, then hooray, the test passes.
- */
-
- let preRedirectChannel = new WebChannel("pre_redirect", Services.io.newURI(HTTP_IFRAME_PATH, null, null));
- let postRedirectChannel = new WebChannel("post_redirect", Services.io.newURI(HTTP_REDIRECTED_IFRAME_PATH, null, null));
-
- let promiseTestDone = new Promise(function (resolve, reject) {
- preRedirectChannel.listen(function (id, message, preRedirectSender) {
- if (message.command === "redirecting") {
-
- postRedirectChannel.listen(function (aId, aMessage, aPostRedirectSender) {
- is(aId, "post_redirect");
- isnot(aMessage.command, "no_response_expected");
-
- if (aMessage.command === "loaded") {
- // The message should not be received on the preRedirectChannel
- // because the target window has redirected.
- preRedirectChannel.send({ command: "no_response_expected" }, preRedirectSender);
- postRedirectChannel.send({ command: "done" }, aPostRedirectSender);
- } else if (aMessage.command === "done") {
- resolve();
- } else {
- reject(new Error(`Unexpected command ${aMessage.command}`));
- }
- });
- } else {
- reject(new Error(`Unexpected command ${message.command}`));
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?iframe_pre_redirect"
- }, function* () {
- yield promiseTestDone;
- preRedirectChannel.stopListening();
- postRedirectChannel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel multichannel",
- run: function* () {
- return new Promise(function(resolve, reject) {
- let tab;
- let channel = new WebChannel("multichannel", Services.io.newURI(HTTP_PATH, null, null));
-
- channel.listen(function (id, message, sender) {
- is(id, "multichannel");
- gBrowser.removeTab(tab);
- resolve();
- });
-
- tab = gBrowser.addTab(HTTP_PATH + HTTP_ENDPOINT + "?multichannel");
- });
- }
- },
- {
- desc: "WebChannel unsolicited send, using system principal",
- run: function* () {
- let channel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null));
-
- // an unsolicted message is sent from Chrome->Content which is then
- // echoed back. If the echo is received here, then the content
- // received the message.
- let messagePromise = new Promise(function (resolve, reject) {
- channel.listen(function (id, message, sender) {
- is(id, "echo");
- is(message.command, "unsolicited");
-
- resolve()
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited"
- }, function* (targetBrowser) {
- channel.send({ command: "unsolicited" }, {
- browser: targetBrowser,
- principal: Services.scriptSecurityManager.getSystemPrincipal()
- });
- yield messagePromise;
- channel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel unsolicited send, using target origin's principal",
- run: function* () {
- let targetURI = Services.io.newURI(HTTP_PATH, null, null);
- let channel = new WebChannel("echo", targetURI);
-
- // an unsolicted message is sent from Chrome->Content which is then
- // echoed back. If the echo is received here, then the content
- // received the message.
- let messagePromise = new Promise(function (resolve, reject) {
- channel.listen(function (id, message, sender) {
- is(id, "echo");
- is(message.command, "unsolicited");
-
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited"
- }, function* (targetBrowser) {
-
- channel.send({ command: "unsolicited" }, {
- browser: targetBrowser,
- principal: Services.scriptSecurityManager.getNoAppCodebasePrincipal(targetURI)
- });
-
- yield messagePromise;
- channel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel unsolicited send with principal mismatch",
- run: function* () {
- let targetURI = Services.io.newURI(HTTP_PATH, null, null);
- let channel = new WebChannel("echo", targetURI);
-
- // two unsolicited messages are sent from Chrome->Content. The first,
- // `unsolicited_no_response_expected` is sent to the wrong principal
- // and should not be echoed back. The second, `done`, is sent to the
- // correct principal and should be echoed back.
- let messagePromise = new Promise(function (resolve, reject) {
- channel.listen(function (id, message, sender) {
- is(id, "echo");
-
- if (message.command === "done") {
- resolve();
- } else {
- reject(new Error(`Unexpected command ${message.command}`));
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited"
- }, function* (targetBrowser) {
-
- let mismatchURI = Services.io.newURI(HTTP_MISMATCH_PATH, null, null);
- let mismatchPrincipal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(mismatchURI);
-
- // send a message to the wrong principal. It should not be delivered
- // to content, and should not be echoed back.
- channel.send({ command: "unsolicited_no_response_expected" }, {
- browser: targetBrowser,
- principal: mismatchPrincipal
- });
-
- let targetPrincipal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(targetURI);
-
- // send the `done` message to the correct principal. It
- // should be echoed back.
- channel.send({ command: "done" }, {
- browser: targetBrowser,
- principal: targetPrincipal
- });
-
- yield messagePromise;
- channel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel non-window target",
- run: function* () {
- /**
- * This test ensures messages can be received from and responses
- * sent to non-window elements.
- *
- * First wait for the non-window element to send a "start" message.
- * Then send the non-window element a "done" message.
- * The non-window element will echo the "done" message back, if it
- * receives the message.
- * Listen for the response. If received, good to go!
- */
- let channel = new WebChannel("not_a_window", Services.io.newURI(HTTP_PATH, null, null));
-
- let testDonePromise = new Promise(function (resolve, reject) {
- channel.listen(function (id, message, sender) {
- if (message.command === "start") {
- channel.send({ command: "done" }, sender);
- } else if (message.command === "done") {
- resolve();
- } else {
- reject(new Error(`Unexpected command ${message.command}`));
- }
- });
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?bubbles"
- }, function* () {
- yield testDonePromise;
- channel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel disallows non-string message from non-whitelisted origin",
- run: function* () {
- /**
- * This test ensures that non-string messages can't be sent via WebChannels.
- * We create a page (on a non-whitelisted origin) which should send us two
- * messages immediately. The first message has an object for it's detail,
- * and the second has a string. We check that we only get the second
- * message.
- */
- let channel = new WebChannel("objects", Services.io.newURI(HTTP_PATH, null, null));
- let testDonePromise = new Promise((resolve, reject) => {
- channel.listen((id, message, sender) => {
- is(id, "objects");
- is(message.type, "string");
- resolve();
- });
- });
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?object"
- }, function* () {
- yield testDonePromise;
- channel.stopListening();
- });
- }
- },
- {
- desc: "WebChannel allows both string and non-string message from whitelisted origin",
- run: function* () {
- /**
- * Same process as above, but we whitelist the origin before loading the page,
- * and expect to get *both* messages back (each exactly once).
- */
- let channel = new WebChannel("objects", Services.io.newURI(HTTP_PATH, null, null));
-
- let testDonePromise = new Promise((resolve, reject) => {
- let sawObject = false;
- let sawString = false;
- channel.listen((id, message, sender) => {
- is(id, "objects");
- if (message.type === "object") {
- ok(!sawObject);
- sawObject = true;
- } else if (message.type === "string") {
- ok(!sawString);
- sawString = true;
- } else {
- reject(new Error(`Unknown message type: ${message.type}`))
- }
- if (sawObject && sawString) {
- resolve();
- }
- });
- });
- const webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist";
- let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref);
- let newWhitelist = origWhitelist + " " + HTTP_PATH;
- Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: HTTP_PATH + HTTP_ENDPOINT + "?object"
- }, function* () {
- yield testDonePromise;
- Services.prefs.setCharPref(webchannelWhitelistPref, origWhitelist);
- channel.stopListening();
- });
- }
- }
-]; // gTests
-
-function test() {
- waitForExplicitFinish();
-
- Task.spawn(function* () {
- for (let testCase of gTests) {
- info("Running: " + testCase.desc);
- yield testCase.run();
- }
- }).then(finish, ex => {
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
-}
diff --git a/browser/base/content/test/general/browser_web_channel_iframe.html b/browser/base/content/test/general/browser_web_channel_iframe.html
deleted file mode 100644
index 7900e7530..000000000
--- a/browser/base/content/test/general/browser_web_channel_iframe.html
+++ /dev/null
@@ -1,96 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>web_channel_test (iframe)</title>
-</head>
-<body>
-<script>
- var REDIRECTED_IFRAME_SRC_ROOT = "http://example.org/browser/browser/base/content/test/general/browser_web_channel_iframe.html";
-
- window.onload = function() {
- var testName = window.location.search.replace(/^\?/, "");
- switch (testName) {
- case "iframe":
- test_iframe();
- break;
- case "iframe_pre_redirect":
- test_iframe_pre_redirect();
- break;
- case "iframe_post_redirect":
- test_iframe_post_redirect();
- break;
- default:
- throw new Error(`INVALID TEST NAME ${testName}`);
- }
- };
-
- function test_iframe() {
- var firstMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "twoway",
- message: {
- command: "one",
- },
- })
- });
-
- window.addEventListener("WebChannelMessageToContent", function(e) {
- var secondMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "twoway",
- message: {
- command: "two",
- detail: e.detail.message,
- },
- }),
- });
-
- if (!e.detail.message.error) {
- window.dispatchEvent(secondMessage);
- }
- }, true);
-
- window.dispatchEvent(firstMessage);
- }
-
-
- function test_iframe_pre_redirect() {
- var firstMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "pre_redirect",
- message: {
- command: "redirecting",
- },
- }),
- });
- window.dispatchEvent(firstMessage);
- document.location = REDIRECTED_IFRAME_SRC_ROOT + "?iframe_post_redirect";
- }
-
- function test_iframe_post_redirect() {
- window.addEventListener("WebChannelMessageToContent", function(e) {
- var echoMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "post_redirect",
- message: e.detail.message,
- }),
- });
-
- window.dispatchEvent(echoMessage);
- }, true);
-
- // Let the test parent know the page has loaded and is ready to echo events
- var loadedMessage = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "post_redirect",
- message: {
- command: "loaded",
- },
- }),
- });
- window.dispatchEvent(loadedMessage);
- }
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/browser_windowactivation.js b/browser/base/content/test/general/browser_windowactivation.js
deleted file mode 100644
index ae4ba75dc..000000000
--- a/browser/base/content/test/general/browser_windowactivation.js
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * This test checks that window activation state is set properly with multiple tabs.
- */
-
-var testPage = "data:text/html,<body><style>:-moz-window-inactive { background-color: red; }</style><div id='area'></div></body>";
-
-var colorChangeNotifications = 0;
-var otherWindow;
-
-var browser1, browser2;
-
-function test() {
- waitForExplicitFinish();
- waitForFocus(reallyRunTests);
-}
-
-function reallyRunTests() {
-
- let tab1 = gBrowser.addTab();
- let tab2 = gBrowser.addTab();
- browser1 = gBrowser.getBrowserForTab(tab1);
- browser2 = gBrowser.getBrowserForTab(tab2);
-
- gURLBar.focus();
-
- var loadCount = 0;
- function check()
- {
- // wait for both tabs to load
- if (++loadCount != 2) {
- return;
- }
-
- browser1.removeEventListener("load", check, true);
- browser2.removeEventListener("load", check, true);
-
- sendGetBackgroundRequest(true);
- }
-
- // The test performs four checks, using -moz-window-inactive on two child tabs.
- // First, the initial state should be transparent. The second check is done
- // while another window is focused. The third check is done after that window
- // is closed and the main window focused again. The fourth check is done after
- // switching to the second tab.
- window.messageManager.addMessageListener("Test:BackgroundColorChanged", function(message) {
- colorChangeNotifications++;
-
- switch (colorChangeNotifications) {
- case 1:
- is(message.data.color, "transparent", "first window initial");
- break;
- case 2:
- is(message.data.color, "transparent", "second window initial");
- runOtherWindowTests();
- break;
- case 3:
- is(message.data.color, "rgb(255, 0, 0)", "first window lowered");
- break;
- case 4:
- is(message.data.color, "rgb(255, 0, 0)", "second window lowered");
- sendGetBackgroundRequest(true);
- otherWindow.close();
- break;
- case 5:
- is(message.data.color, "transparent", "first window raised");
- break;
- case 6:
- is(message.data.color, "transparent", "second window raised");
- gBrowser.selectedTab = tab2;
- break;
- case 7:
- is(message.data.color, "transparent", "first window after tab switch");
- break;
- case 8:
- is(message.data.color, "transparent", "second window after tab switch");
- finishTest();
- break;
- case 9:
- ok(false, "too many color change notifications");
- break;
- }
- });
-
- window.messageManager.addMessageListener("Test:FocusReceived", function(message) {
- // No color change should occur after a tab switch.
- if (colorChangeNotifications == 6) {
- sendGetBackgroundRequest(false);
- }
- });
-
- window.messageManager.addMessageListener("Test:ActivateEvent", function(message) {
- ok(message.data.ok, "Test:ActivateEvent");
- });
-
- window.messageManager.addMessageListener("Test:DeactivateEvent", function(message) {
- ok(message.data.ok, "Test:DeactivateEvent");
- });
-
- browser1.addEventListener("load", check, true);
- browser2.addEventListener("load", check, true);
- browser1.contentWindow.location = testPage;
- browser2.contentWindow.location = testPage;
-
- browser1.messageManager.loadFrameScript("data:,(" + childFunction.toString() + ")();", true);
- browser2.messageManager.loadFrameScript("data:,(" + childFunction.toString() + ")();", true);
-
- gBrowser.selectedTab = tab1;
-}
-
-function sendGetBackgroundRequest(ifChanged)
-{
- browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged });
- browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged });
-}
-
-function runOtherWindowTests() {
- otherWindow = window.open("data:text/html,<body>Hi</body>", "", "chrome");
- waitForFocus(function () {
- sendGetBackgroundRequest(true);
- }, otherWindow);
-}
-
-function finishTest()
-{
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
- otherWindow = null;
- finish();
-}
-
-function childFunction()
-{
- let oldColor = null;
-
- let expectingResponse = false;
- let ifChanged = true;
-
- addMessageListener("Test:GetBackgroundColor", function(message) {
- expectingResponse = true;
- ifChanged = message.data.ifChanged;
- });
-
- content.addEventListener("focus", function () {
- sendAsyncMessage("Test:FocusReceived", { });
- }, false);
-
- var windowGotActivate = false;
- var windowGotDeactivate = false;
- addEventListener("activate", function() {
- sendAsyncMessage("Test:ActivateEvent", { ok: !windowGotActivate });
- windowGotActivate = false;
- });
-
- addEventListener("deactivate", function() {
- sendAsyncMessage("Test:DeactivateEvent", { ok: !windowGotDeactivate });
- windowGotDeactivate = false;
- });
- content.addEventListener("activate", function() {
- windowGotActivate = true;
- });
-
- content.addEventListener("deactivate", function() {
- windowGotDeactivate = true;
- });
-
- content.setInterval(function () {
- if (!expectingResponse) {
- return;
- }
-
- let area = content.document.getElementById("area");
- if (!area) {
- return; /* hasn't loaded yet */
- }
-
- let color = content.getComputedStyle(area, "").backgroundColor;
- if (oldColor != color || !ifChanged) {
- expectingResponse = false;
- oldColor = color;
- sendAsyncMessage("Test:BackgroundColorChanged", { color: color });
- }
- }, 20);
-}
diff --git a/browser/base/content/test/general/browser_windowopen_reflows.js b/browser/base/content/test/general/browser_windowopen_reflows.js
deleted file mode 100644
index 7dac8aad6..000000000
--- a/browser/base/content/test/general/browser_windowopen_reflows.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const EXPECTED_REFLOWS = [
- // handleEvent flushes layout to get the tabstrip width after a resize.
- "handleEvent@chrome://browser/content/tabbrowser.xml|",
-
- // Loading a tab causes a reflow.
- "loadTabs@chrome://browser/content/tabbrowser.xml|" +
- "loadOneOrMoreURIs@chrome://browser/content/browser.js|" +
- "gBrowserInit._delayedStartup@chrome://browser/content/browser.js|",
-
- // Selecting the address bar causes a reflow.
- "select@chrome://global/content/bindings/textbox.xml|" +
- "focusAndSelectUrlBar@chrome://browser/content/browser.js|" +
- "gBrowserInit._delayedStartup@chrome://browser/content/browser.js|",
-
- // Focusing the content area causes a reflow.
- "gBrowserInit._delayedStartup@chrome://browser/content/browser.js|",
-
- // Sometimes sessionstore collects data during this test, which causes a sync reflow
- // (https://bugzilla.mozilla.org/show_bug.cgi?id=892154 will fix this)
- "ssi_getWindowDimension@resource:///modules/sessionstore/SessionStore.jsm",
-];
-
-if (Services.appinfo.OS == "WINNT" || Services.appinfo.OS == "Darwin") {
- // TabsInTitlebar._update causes a reflow on OS X and Windows trying to do calculations
- // since layout info is already dirty. This doesn't seem to happen before
- // MozAfterPaint on Linux.
- EXPECTED_REFLOWS.push("TabsInTitlebar._update/rect@chrome://browser/content/browser-tabsintitlebar.js|" +
- "TabsInTitlebar._update@chrome://browser/content/browser-tabsintitlebar.js|" +
- "updateAppearance@chrome://browser/content/browser-tabsintitlebar.js|" +
- "handleEvent@chrome://browser/content/tabbrowser.xml|");
-}
-
-if (Services.appinfo.OS == "Darwin") {
- // _onOverflow causes a reflow getting widths.
- EXPECTED_REFLOWS.push("OverflowableToolbar.prototype._onOverflow@resource:///modules/CustomizableUI.jsm|" +
- "OverflowableToolbar.prototype.init@resource:///modules/CustomizableUI.jsm|" +
- "OverflowableToolbar.prototype.observe@resource:///modules/CustomizableUI.jsm|" +
- "gBrowserInit._delayedStartup@chrome://browser/content/browser.js|");
- // Same as above since in packaged builds there are no function names and the resource URI includes "app"
- EXPECTED_REFLOWS.push("@resource://app/modules/CustomizableUI.jsm|" +
- "@resource://app/modules/CustomizableUI.jsm|" +
- "@resource://app/modules/CustomizableUI.jsm|" +
- "gBrowserInit._delayedStartup@chrome://browser/content/browser.js|");
-}
-
-/*
- * This test ensures that there are no unexpected
- * uninterruptible reflows when opening new windows.
- */
-function test() {
- waitForExplicitFinish();
-
- // Add a reflow observer and open a new window
- let win = OpenBrowserWindow();
- let docShell = win.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShell);
- docShell.addWeakReflowObserver(observer);
-
- // Wait until the mozafterpaint event occurs.
- waitForMozAfterPaint(win, function paintListener() {
- // Remove reflow observer and clean up.
- docShell.removeWeakReflowObserver(observer);
- win.close();
-
- finish();
- });
-}
-
-var observer = {
- reflow: function (start, end) {
- // Gather information about the current code path.
- let stack = new Error().stack;
- let path = stack.split("\n").slice(1).map(line => {
- return line.replace(/:\d+:\d+$/, "");
- }).join("|");
- let pathWithLineNumbers = (new Error().stack).split("\n").slice(1).join("|");
-
- // Stack trace is empty. Reflow was triggered by native code.
- if (path === "") {
- return;
- }
-
- // Check if this is an expected reflow.
- for (let expectedStack of EXPECTED_REFLOWS) {
- if (path.startsWith(expectedStack) ||
- // Accept an empty function name for gBrowserInit._delayedStartup or TabsInTitlebar._update to workaround bug 906578.
- path.startsWith(expectedStack.replace(/(^|\|)(gBrowserInit\._delayedStartup|TabsInTitlebar\._update)@/, "$1@"))) {
- ok(true, "expected uninterruptible reflow '" + expectedStack + "'");
- return;
- }
- }
-
- ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'");
- },
-
- reflowInterruptible: function (start, end) {
- // We're not interested in interruptible reflows.
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIReflowObserver,
- Ci.nsISupportsWeakReference])
-};
-
-function waitForMozAfterPaint(win, callback) {
- win.addEventListener("MozAfterPaint", function onEnd(event) {
- if (event.target != win)
- return;
- win.removeEventListener("MozAfterPaint", onEnd);
- executeSoon(callback);
- });
-}
diff --git a/browser/base/content/test/general/browser_zbug569342.js b/browser/base/content/test/general/browser_zbug569342.js
deleted file mode 100644
index 2dac5acde..000000000
--- a/browser/base/content/test/general/browser_zbug569342.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var gTab = null;
-
-function load(url, cb) {
- gTab = gBrowser.addTab(url);
- gBrowser.addEventListener("load", function (event) {
- if (event.target.location != url)
- return;
-
- gBrowser.removeEventListener("load", arguments.callee, true);
- // Trigger onLocationChange by switching tabs.
- gBrowser.selectedTab = gTab;
- cb();
- }, true);
-}
-
-function test() {
- waitForExplicitFinish();
-
- ok(gFindBar.hidden, "Find bar should not be visible by default");
-
- // Open the Find bar before we navigate to pages that shouldn't have it.
- EventUtils.synthesizeKey("f", { accelKey: true });
- ok(!gFindBar.hidden, "Find bar should be visible");
-
- nextTest();
-}
-
-var urls = [
- "about:config",
- "about:addons",
-];
-
-function nextTest() {
- let url = urls.shift();
- if (url) {
- testFindDisabled(url, nextTest);
- } else {
- // Make sure the find bar is re-enabled after disabled page is closed.
- testFindEnabled("about:blank", function () {
- EventUtils.synthesizeKey("VK_ESCAPE", { });
- ok(gFindBar.hidden, "Find bar should now be hidden");
- finish();
- });
- }
-}
-
-function testFindDisabled(url, cb) {
- load(url, function() {
- ok(gFindBar.hidden, "Find bar should not be visible");
- EventUtils.synthesizeKey("/", {}, gTab.linkedBrowser.contentWindow);
- ok(gFindBar.hidden, "Find bar should not be visible");
- EventUtils.synthesizeKey("f", { accelKey: true });
- ok(gFindBar.hidden, "Find bar should not be visible");
- ok(document.getElementById("cmd_find").getAttribute("disabled"),
- "Find command should be disabled");
-
- gBrowser.removeTab(gTab);
- cb();
- });
-}
-
-function testFindEnabled(url, cb) {
- load(url, function() {
- ok(!document.getElementById("cmd_find").getAttribute("disabled"),
- "Find command should not be disabled");
-
- // Open Find bar and then close it.
- EventUtils.synthesizeKey("f", { accelKey: true });
- ok(!gFindBar.hidden, "Find bar should be visible again");
- EventUtils.synthesizeKey("VK_ESCAPE", { });
- ok(gFindBar.hidden, "Find bar should now be hidden");
-
- gBrowser.removeTab(gTab);
- cb();
- });
-}
diff --git a/browser/base/content/test/general/bug1262648_string_with_newlines.dtd b/browser/base/content/test/general/bug1262648_string_with_newlines.dtd
deleted file mode 100644
index 308072c4e..000000000
--- a/browser/base/content/test/general/bug1262648_string_with_newlines.dtd
+++ /dev/null
@@ -1,3 +0,0 @@
-<!ENTITY foo.bar "This string
-contains
-newlines!"> \ No newline at end of file
diff --git a/browser/base/content/test/general/bug364677-data.xml b/browser/base/content/test/general/bug364677-data.xml
deleted file mode 100644
index b48915c05..000000000
--- a/browser/base/content/test/general/bug364677-data.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<rss version="2.0">
- <channel>
- <title>t</title>
- </channel>
-</rss>
diff --git a/browser/base/content/test/general/bug364677-data.xml^headers^ b/browser/base/content/test/general/bug364677-data.xml^headers^
deleted file mode 100644
index f203c6368..000000000
--- a/browser/base/content/test/general/bug364677-data.xml^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: text/xml
diff --git a/browser/base/content/test/general/bug395533-data.txt b/browser/base/content/test/general/bug395533-data.txt
deleted file mode 100644
index e0ed39850..000000000
--- a/browser/base/content/test/general/bug395533-data.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-<rss version="2.0">
- <channel>
- <link>http://example.org/</link>
- <title>t</title>
- </channel>
-</rss>
diff --git a/browser/base/content/test/general/bug592338.html b/browser/base/content/test/general/bug592338.html
deleted file mode 100644
index 159b21a76..000000000
--- a/browser/base/content/test/general/bug592338.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<html>
-<head>
-<script type="text/javascript">
-var theme = {
- id: "test",
- name: "Test Background",
- headerURL: "http://example.com/firefox/personas/01/header.jpg",
- footerURL: "http://example.com/firefox/personas/01/footer.jpg",
- textcolor: "#fff",
- accentcolor: "#6b6b6b"
-};
-
-function setTheme(node) {
- node.setAttribute("data-browsertheme", JSON.stringify(theme));
- var event = document.createEvent("Events");
- event.initEvent("InstallBrowserTheme", true, false);
- node.dispatchEvent(event);
-}
-</script>
-</head>
-<body>
-<a id="theme-install" href="#" onclick="setTheme(this)">Install</a>
-</body>
-</html>
diff --git a/browser/base/content/test/general/bug792517-2.html b/browser/base/content/test/general/bug792517-2.html
deleted file mode 100644
index bfc24d817..000000000
--- a/browser/base/content/test/general/bug792517-2.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
-<body>
-<a href="bug792517.sjs" id="fff">this is a link</a>
-</body>
-</html>
diff --git a/browser/base/content/test/general/bug792517.html b/browser/base/content/test/general/bug792517.html
deleted file mode 100644
index e7c040bf1..000000000
--- a/browser/base/content/test/general/bug792517.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
-<body>
-<img src="moz.png" id="img">
-</body>
-</html>
diff --git a/browser/base/content/test/general/bug792517.sjs b/browser/base/content/test/general/bug792517.sjs
deleted file mode 100644
index 91e5aa23f..000000000
--- a/browser/base/content/test/general/bug792517.sjs
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function handleRequest(aRequest, aResponse) {
- aResponse.setStatusLine(aRequest.httpVersion, 200);
- if (aRequest.hasHeader('Cookie')) {
- aResponse.write("cookie-present");
- } else {
- aResponse.setHeader("Set-Cookie", "foopy=1");
- aResponse.write("cookie-not-present");
- }
-}
diff --git a/browser/base/content/test/general/bug839103.css b/browser/base/content/test/general/bug839103.css
deleted file mode 100644
index 611907d3d..000000000
--- a/browser/base/content/test/general/bug839103.css
+++ /dev/null
@@ -1 +0,0 @@
-* {}
diff --git a/browser/base/content/test/general/clipboard_pastefile.html b/browser/base/content/test/general/clipboard_pastefile.html
deleted file mode 100644
index fcbf60ed2..000000000
--- a/browser/base/content/test/general/clipboard_pastefile.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<html><body>
-<script>
-function checkPaste(event)
-{
- let output = document.getElementById("output");
- output.textContent = checkPasteHelper(event);
-}
-
-function checkPasteHelper(event)
-{
- let dt = event.clipboardData;
- if (dt.types.length != 2)
- return "Wrong number of types; got " + dt.types.length;
-
- for (let type of dt.types) {
- if (type != "Files" && type != "application/x-moz-file")
- return "Invalid type for types; got" + type;
- }
-
- for (let type of dt.mozTypesAt(0)) {
- if (type != "Files" && type != "application/x-moz-file")
- return "Invalid type for mozTypesAt; got" + type;
- }
-
- if (dt.getData("text/plain"))
- return "text/plain found with getData";
- if (dt.mozGetDataAt("text/plain", 0))
- return "text/plain found with mozGetDataAt";
-
- return "Passed";
-}
-</script>
-
-<input id="input" onpaste="checkPaste(event)">
-<div id="output"></div>
-
-</body></html>
diff --git a/browser/base/content/test/general/close_beforeunload.html b/browser/base/content/test/general/close_beforeunload.html
deleted file mode 100644
index 4b62002cc..000000000
--- a/browser/base/content/test/general/close_beforeunload.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<body>
- <p>I will close myself if you close me.</p>
- <script>
- window.onbeforeunload = function() {
- window.close();
- };
- </script>
-</body>
diff --git a/browser/base/content/test/general/close_beforeunload_opens_second_tab.html b/browser/base/content/test/general/close_beforeunload_opens_second_tab.html
deleted file mode 100644
index 243307a0e..000000000
--- a/browser/base/content/test/general/close_beforeunload_opens_second_tab.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<body>
- <a href="#" onclick="window.open('close_beforeunload.html', '_blank')">Open second tab</a>
-</body>
diff --git a/browser/base/content/test/general/contentSearchUI.html b/browser/base/content/test/general/contentSearchUI.html
deleted file mode 100644
index 3750ac2b0..000000000
--- a/browser/base/content/test/general/contentSearchUI.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!DOCTYPE html>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<html>
-<head>
-<meta charset="utf-8">
-<script type="application/javascript;version=1.8"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js">
-</script>
-<script type="application/javascript;version=1.8"
- src="chrome://browser/content/contentSearchUI.js">
-</script>
-<link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css"/>
-</head>
-<body>
-
-<div id="container" style="position: relative;"><input type="text" value=""/></div>
-
-</body>
-</html>
diff --git a/browser/base/content/test/general/contentSearchUI.js b/browser/base/content/test/general/contentSearchUI.js
deleted file mode 100644
index 0e46230a2..000000000
--- a/browser/base/content/test/general/contentSearchUI.js
+++ /dev/null
@@ -1,209 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-(function () {
-
-const TEST_MSG = "ContentSearchUIControllerTest";
-const ENGINE_NAME = "browser_searchSuggestionEngine searchSuggestionEngine.xml";
-var gController;
-
-addMessageListener(TEST_MSG, msg => {
- messageHandlers[msg.data.type](msg.data.data);
-});
-
-var messageHandlers = {
-
- init: function() {
- Services.search.currentEngine = Services.search.getEngineByName(ENGINE_NAME);
- let input = content.document.querySelector("input");
- gController =
- new content.ContentSearchUIController(input, input.parentNode, "test", "test");
- content.addEventListener("ContentSearchService", function listener(aEvent) {
- if (aEvent.detail.type == "State" &&
- gController.defaultEngine.name == ENGINE_NAME) {
- content.removeEventListener("ContentSearchService", listener);
- ack("init");
- }
- });
- gController.remoteTimeout = 5000;
- },
-
- key: function (arg) {
- let keyName = typeof(arg) == "string" ? arg : arg.key;
- content.synthesizeKey(keyName, arg.modifiers || {});
- let wait = arg.waitForSuggestions ? waitForSuggestions : cb => cb();
- wait(ack.bind(null, "key"));
- },
-
- startComposition: function (arg) {
- content.synthesizeComposition({ type: "compositionstart", data: "" });
- ack("startComposition");
- },
-
- changeComposition: function (arg) {
- let data = typeof(arg) == "string" ? arg : arg.data;
- content.synthesizeCompositionChange({
- composition: {
- string: data,
- clauses: [
- { length: data.length, attr: content.COMPOSITION_ATTR_RAW_CLAUSE }
- ]
- },
- caret: { start: data.length, length: 0 }
- });
- let wait = arg.waitForSuggestions ? waitForSuggestions : cb => cb();
- wait(ack.bind(null, "changeComposition"));
- },
-
- commitComposition: function () {
- content.synthesizeComposition({ type: "compositioncommitasis" });
- ack("commitComposition");
- },
-
- focus: function () {
- gController.input.focus();
- ack("focus");
- },
-
- blur: function () {
- gController.input.blur();
- ack("blur");
- },
-
- waitForSearch: function () {
- waitForContentSearchEvent("Search", aData => ack("waitForSearch", aData));
- },
-
- waitForSearchSettings: function () {
- waitForContentSearchEvent("ManageEngines",
- aData => ack("waitForSearchSettings", aData));
- },
-
- mousemove: function (itemIndex) {
- let row;
- if (itemIndex == -1) {
- row = gController._table.firstChild;
- }
- else {
- let allElts = [...gController._suggestionsList.children,
- ...gController._oneOffButtons,
- content.document.getElementById("contentSearchSettingsButton")];
- row = allElts[itemIndex];
- }
- let event = {
- type: "mousemove",
- clickcount: 0,
- }
- row.addEventListener("mousemove", function handler() {
- row.removeEventListener("mousemove", handler);
- ack("mousemove");
- });
- content.synthesizeMouseAtCenter(row, event);
- },
-
- click: function (arg) {
- let eltIdx = typeof(arg) == "object" ? arg.eltIdx : arg;
- let row;
- if (eltIdx == -1) {
- row = gController._table.firstChild;
- }
- else {
- let allElts = [...gController._suggestionsList.children,
- ...gController._oneOffButtons,
- content.document.getElementById("contentSearchSettingsButton")];
- row = allElts[eltIdx];
- }
- let event = arg.modifiers || {};
- // synthesizeMouseAtCenter defaults to sending a mousedown followed by a
- // mouseup if the event type is not specified.
- content.synthesizeMouseAtCenter(row, event);
- ack("click");
- },
-
- addInputValueToFormHistory: function () {
- gController.addInputValueToFormHistory();
- ack("addInputValueToFormHistory");
- },
-
- addDuplicateOneOff: function () {
- let btn = gController._oneOffButtons[gController._oneOffButtons.length - 1];
- let newBtn = btn.cloneNode(true);
- btn.parentNode.appendChild(newBtn);
- gController._oneOffButtons.push(newBtn);
- ack("addDuplicateOneOff");
- },
-
- removeLastOneOff: function () {
- gController._oneOffButtons.pop().remove();
- ack("removeLastOneOff");
- },
-
- reset: function () {
- // Reset both the input and suggestions by select all + delete. If there was
- // no text entered, this won't have any effect, so also escape to ensure the
- // suggestions table is closed.
- gController.input.focus();
- content.synthesizeKey("a", { accelKey: true });
- content.synthesizeKey("VK_DELETE", {});
- content.synthesizeKey("VK_ESCAPE", {});
- ack("reset");
- },
-};
-
-function ack(aType, aData) {
- sendAsyncMessage(TEST_MSG, { type: aType, data: aData || currentState() });
-}
-
-function waitForSuggestions(cb) {
- let observer = new content.MutationObserver(() => {
- if (gController.input.getAttribute("aria-expanded") == "true") {
- observer.disconnect();
- cb();
- }
- });
- observer.observe(gController.input, {
- attributes: true,
- attributeFilter: ["aria-expanded"],
- });
-}
-
-function waitForContentSearchEvent(messageType, cb) {
- let mm = content.SpecialPowers.Cc["@mozilla.org/globalmessagemanager;1"].
- getService(content.SpecialPowers.Ci.nsIMessageListenerManager);
- mm.addMessageListener("ContentSearch", function listener(aMsg) {
- if (aMsg.data.type != messageType) {
- return;
- }
- mm.removeMessageListener("ContentSearch", listener);
- cb(aMsg.data.data);
- });
-}
-
-function currentState() {
- let state = {
- selectedIndex: gController.selectedIndex,
- selectedButtonIndex: gController.selectedButtonIndex,
- numSuggestions: gController._table.hidden ? 0 : gController.numSuggestions,
- suggestionAtIndex: [],
- isFormHistorySuggestionAtIndex: [],
-
- tableHidden: gController._table.hidden,
-
- inputValue: gController.input.value,
- ariaExpanded: gController.input.getAttribute("aria-expanded"),
- };
-
- if (state.numSuggestions) {
- for (let i = 0; i < gController.numSuggestions; i++) {
- state.suggestionAtIndex.push(gController.suggestionAtIndex(i));
- state.isFormHistorySuggestionAtIndex.push(
- gController.isFormHistorySuggestionAtIndex(i));
- }
- }
-
- return state;
-}
-
-})();
diff --git a/browser/base/content/test/general/content_aboutAccounts.js b/browser/base/content/test/general/content_aboutAccounts.js
deleted file mode 100644
index 12ac04934..000000000
--- a/browser/base/content/test/general/content_aboutAccounts.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* 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/. */
-
-// This file is loaded as a "content script" for browser_aboutAccounts tests
-"use strict";
-
-var {interfaces: Ci, utils: Cu} = Components;
-
-addEventListener("load", function load(event) {
- if (event.target != content.document) {
- return;
- }
-// content.document.removeEventListener("load", load, true);
- sendAsyncMessage("test:document:load");
- // Opening Sync prefs in tests is a pain as leaks are reported due to the
- // in-flight promises. For now we just mock the openPrefs() function and have
- // it send a message back to the test so we know it was called.
- content.openPrefs = function() {
- sendAsyncMessage("test:openPrefsCalled");
- }
-}, true);
-
-addEventListener("DOMContentLoaded", function domContentLoaded(event) {
- removeEventListener("DOMContentLoaded", domContentLoaded, true);
- let iframe = content.document.getElementById("remote");
- if (!iframe) {
- // at least one test initially loads about:blank - in that case, we are done.
- return;
- }
- // We use DOMContentLoaded here as that fires for our iframe even when we've
- // arranged for the URL in the iframe to cause an error.
- addEventListener("DOMContentLoaded", function iframeLoaded(dclEvent) {
- if (iframe.contentWindow.location.href == "about:blank" ||
- dclEvent.target != iframe.contentDocument) {
- return;
- }
- removeEventListener("DOMContentLoaded", iframeLoaded, true);
- sendAsyncMessage("test:iframe:load", {url: iframe.contentDocument.location.href});
- // And an event listener for the test responses, which we send to the test
- // via a message.
- iframe.contentWindow.addEventListener("FirefoxAccountsTestResponse", function (fxAccountsEvent) {
- sendAsyncMessage("test:response", {data: fxAccountsEvent.detail.data});
- }, true);
- }, true);
-}, true);
-
-// Return the visibility state of a list of ids.
-addMessageListener("test:check-visibilities", function (message) {
- let result = {};
- for (let id of message.data.ids) {
- let elt = content.document.getElementById(id);
- if (elt) {
- let displayStyle = content.window.getComputedStyle(elt).display;
- if (displayStyle == 'none') {
- result[id] = false;
- } else if (displayStyle == 'block') {
- result[id] = true;
- } else {
- result[id] = "strange: " + displayStyle; // tests should fail!
- }
- } else {
- result[id] = "doesn't exist: " + id;
- }
- }
- sendAsyncMessage("test:check-visibilities-response", result);
-});
-
-addMessageListener("test:load-with-mocked-profile-path", function (message) {
- addEventListener("DOMContentLoaded", function domContentLoaded(event) {
- removeEventListener("DOMContentLoaded", domContentLoaded, true);
- content.getDefaultProfilePath = () => message.data.profilePath;
- // now wait for the iframe to load.
- let iframe = content.document.getElementById("remote");
- iframe.addEventListener("load", function iframeLoaded(loadEvent) {
- if (iframe.contentWindow.location.href == "about:blank" ||
- loadEvent.target != iframe) {
- return;
- }
- iframe.removeEventListener("load", iframeLoaded, true);
- sendAsyncMessage("test:load-with-mocked-profile-path-response",
- {url: iframe.contentDocument.location.href});
- }, true);
- });
- let webNav = docShell.QueryInterface(Ci.nsIWebNavigation);
- webNav.loadURI(message.data.url, webNav.LOAD_FLAGS_NONE, null, null, null);
-}, true);
diff --git a/browser/base/content/test/general/contextmenu_common.js b/browser/base/content/test/general/contextmenu_common.js
deleted file mode 100644
index 1a0fa931a..000000000
--- a/browser/base/content/test/general/contextmenu_common.js
+++ /dev/null
@@ -1,324 +0,0 @@
-var lastElement;
-
-function openContextMenuFor(element, shiftkey, waitForSpellCheck) {
- // Context menu should be closed before we open it again.
- is(SpecialPowers.wrap(contextMenu).state, "closed", "checking if popup is closed");
-
- if (lastElement)
- lastElement.blur();
- element.focus();
-
- // Some elements need time to focus and spellcheck before any tests are
- // run on them.
- function actuallyOpenContextMenuFor() {
- lastElement = element;
- var eventDetails = { type : "contextmenu", button : 2, shiftKey : shiftkey };
- synthesizeMouse(element, 2, 2, eventDetails, element.ownerGlobal);
- }
-
- if (waitForSpellCheck) {
- var { onSpellCheck } = SpecialPowers.Cu.import("resource://gre/modules/AsyncSpellCheckTestHelper.jsm", {});
- onSpellCheck(element, actuallyOpenContextMenuFor);
- }
- else {
- actuallyOpenContextMenuFor();
- }
-}
-
-function closeContextMenu() {
- contextMenu.hidePopup();
-}
-
-function getVisibleMenuItems(aMenu, aData) {
- var items = [];
- var accessKeys = {};
- for (var i = 0; i < aMenu.childNodes.length; i++) {
- var item = aMenu.childNodes[i];
- if (item.hidden)
- continue;
-
- var key = item.accessKey;
- if (key)
- key = key.toLowerCase();
-
- var isPageMenuItem = item.hasAttribute("generateditemid");
-
- if (item.nodeName == "menuitem") {
- var isGenerated = item.className == "spell-suggestion"
- || item.className == "sendtab-target";
- if (isGenerated) {
- is(item.id, "", "child menuitem #" + i + " is generated");
- } else if (isPageMenuItem) {
- is(item.id, "", "child menuitem #" + i + " is a generated page menu item");
- } else {
- ok(item.id, "child menuitem #" + i + " has an ID");
- }
- var label = item.getAttribute("label");
- ok(label.length, "menuitem " + item.id + " has a label");
- if (isGenerated) {
- is(key, "", "Generated items shouldn't have an access key");
- items.push("*" + label);
- } else if (isPageMenuItem) {
- items.push("+" + label);
- } else if (item.id.indexOf("spell-check-dictionary-") != 0 &&
- item.id != "spell-no-suggestions" &&
- item.id != "spell-add-dictionaries-main" &&
- item.id != "context-savelinktopocket" &&
- item.id != "fill-login-saved-passwords" &&
- item.id != "fill-login-no-logins") {
- ok(key, "menuitem " + item.id + " has an access key");
- if (accessKeys[key])
- ok(false, "menuitem " + item.id + " has same accesskey as " + accessKeys[key]);
- else
- accessKeys[key] = item.id;
- }
- if (!isGenerated && !isPageMenuItem) {
- items.push(item.id);
- }
- if (isPageMenuItem) {
- var p = {};
- p.type = item.getAttribute("type");
- p.icon = item.getAttribute("image");
- p.checked = item.hasAttribute("checked");
- p.disabled = item.hasAttribute("disabled");
- items.push(p);
- } else {
- items.push(!item.disabled);
- }
- } else if (item.nodeName == "menuseparator") {
- ok(true, "--- seperator id is " + item.id);
- items.push("---");
- items.push(null);
- } else if (item.nodeName == "menu") {
- if (isPageMenuItem) {
- item.id = "generated-submenu-" + aData.generatedSubmenuId++;
- }
- ok(item.id, "child menu #" + i + " has an ID");
- if (!isPageMenuItem) {
- ok(key, "menu has an access key");
- if (accessKeys[key])
- ok(false, "menu " + item.id + " has same accesskey as " + accessKeys[key]);
- else
- accessKeys[key] = item.id;
- }
- items.push(item.id);
- items.push(!item.disabled);
- // Add a dummy item so that the indexes in checkMenu are the same
- // for expectedItems and actualItems.
- items.push([]);
- items.push(null);
- } else if (item.nodeName == "menugroup") {
- ok(item.id, "child menugroup #" + i + " has an ID");
- items.push(item.id);
- items.push(!item.disabled);
- var menugroupChildren = [];
- for (var child of item.children) {
- if (child.hidden)
- continue;
-
- menugroupChildren.push([child.id, !child.disabled]);
- }
- items.push(menugroupChildren);
- items.push(null);
- } else {
- ok(false, "child #" + i + " of menu ID " + aMenu.id +
- " has an unknown type (" + item.nodeName + ")");
- }
- }
- return items;
-}
-
-function checkContextMenu(expectedItems) {
- is(contextMenu.state, "open", "checking if popup is open");
- var data = { generatedSubmenuId: 1 };
- checkMenu(contextMenu, expectedItems, data);
-}
-
-function checkMenuItem(actualItem, actualEnabled, expectedItem, expectedEnabled, index) {
- is(actualItem, expectedItem,
- "checking item #" + index/2 + " (" + expectedItem + ") name");
-
- if (typeof expectedEnabled == "object" && expectedEnabled != null ||
- typeof actualEnabled == "object" && actualEnabled != null) {
-
- ok(!(actualEnabled == null), "actualEnabled is not null");
- ok(!(expectedEnabled == null), "expectedEnabled is not null");
- is(typeof actualEnabled, typeof expectedEnabled, "checking types");
-
- if (typeof actualEnabled != typeof expectedEnabled ||
- actualEnabled == null || expectedEnabled == null)
- return;
-
- is(actualEnabled.type, expectedEnabled.type,
- "checking item #" + index/2 + " (" + expectedItem + ") type attr value");
- var icon = actualEnabled.icon;
- if (icon) {
- var tmp = "";
- var j = icon.length - 1;
- while (j && icon[j] != "/") {
- tmp = icon[j--] + tmp;
- }
- icon = tmp;
- }
- is(icon, expectedEnabled.icon,
- "checking item #" + index/2 + " (" + expectedItem + ") icon attr value");
- is(actualEnabled.checked, expectedEnabled.checked,
- "checking item #" + index/2 + " (" + expectedItem + ") has checked attr");
- is(actualEnabled.disabled, expectedEnabled.disabled,
- "checking item #" + index/2 + " (" + expectedItem + ") has disabled attr");
- } else if (expectedEnabled != null)
- is(actualEnabled, expectedEnabled,
- "checking item #" + index/2 + " (" + expectedItem + ") enabled state");
-}
-
-/*
- * checkMenu - checks to see if the specified <menupopup> contains the
- * expected items and state.
- * expectedItems is a array of (1) item IDs and (2) a boolean specifying if
- * the item is enabled or not (or null to ignore it). Submenus can be checked
- * by providing a nested array entry after the expected <menu> ID.
- * For example: ["blah", true, // item enabled
- * "submenu", null, // submenu
- * ["sub1", true, // submenu contents
- * "sub2", false], null, // submenu contents
- * "lol", false] // item disabled
- *
- */
-function checkMenu(menu, expectedItems, data) {
- var actualItems = getVisibleMenuItems(menu, data);
- // ok(false, "Items are: " + actualItems);
- for (var i = 0; i < expectedItems.length; i+=2) {
- var actualItem = actualItems[i];
- var actualEnabled = actualItems[i + 1];
- var expectedItem = expectedItems[i];
- var expectedEnabled = expectedItems[i + 1];
- if (expectedItem instanceof Array) {
- ok(true, "Checking submenu/menugroup...");
- var previousId = expectedItems[i - 2]; // The last item was the menu ID.
- var previousItem = menu.getElementsByAttribute("id", previousId)[0];
- ok(previousItem, (previousItem ? previousItem.nodeName : "item") + " with previous id (" + previousId + ") found");
- if (previousItem && previousItem.nodeName == "menu") {
- ok(previousItem, "got a submenu element of id='" + previousId + "'");
- is(previousItem.nodeName, "menu", "submenu element of id='" + previousId +
- "' has expected nodeName");
- checkMenu(previousItem.menupopup, expectedItem, data, i);
- } else if (previousItem && previousItem.nodeName == "menugroup") {
- ok(expectedItem.length, "menugroup must not be empty");
- for (var j = 0; j < expectedItem.length / 2; j++) {
- checkMenuItem(actualItems[i][j][0], actualItems[i][j][1], expectedItem[j*2], expectedItem[j*2+1], i+j*2);
- }
- i += j;
- } else {
- ok(false, "previous item is not a menu or menugroup");
- }
- } else {
- checkMenuItem(actualItem, actualEnabled, expectedItem, expectedEnabled, i);
- }
- }
- // Could find unexpected extra items at the end...
- is(actualItems.length, expectedItems.length, "checking expected number of menu entries");
-}
-
-let lastElementSelector = null;
-/**
- * Right-clicks on the element that matches `selector` and checks the
- * context menu that appears against the `menuItems` array.
- *
- * @param {String} selector
- * A selector passed to querySelector to find
- * the element that will be referenced.
- * @param {Array} menuItems
- * An array of menuitem ids and their associated enabled state. A state
- * of null means that it will be ignored. Ids of '---' are used for
- * menuseparators.
- * @param {Object} options, optional
- * skipFocusChange: don't move focus to the element before test, useful
- * if you want to delay spell-check initialization
- * offsetX: horizontal mouse offset from the top-left corner of
- * the element, optional
- * offsetY: vertical mouse offset from the top-left corner of the
- * element, optional
- * centered: if true, mouse position is centered in element, defaults
- * to true if offsetX and offsetY are not provided
- * waitForSpellCheck: wait until spellcheck is initialized before
- * starting test
- * preCheckContextMenuFn: callback to run before opening menu
- * onContextMenuShown: callback to run when the context menu is shown
- * postCheckContextMenuFn: callback to run after opening menu
- * @return {Promise} resolved after the test finishes
- */
-function* test_contextmenu(selector, menuItems, options={}) {
- contextMenu = document.getElementById("contentAreaContextMenu");
- is(contextMenu.state, "closed", "checking if popup is closed");
-
- // Default to centered if no positioning is defined.
- if (!options.offsetX && !options.offsetY) {
- options.centered = true;
- }
-
- if (!options.skipFocusChange) {
- yield ContentTask.spawn(gBrowser.selectedBrowser,
- [lastElementSelector, selector],
- function*([contentLastElementSelector, contentSelector]) {
- if (contentLastElementSelector) {
- let contentLastElement = content.document.querySelector(contentLastElementSelector);
- contentLastElement.blur();
- }
- let element = content.document.querySelector(contentSelector);
- element.focus();
- });
- lastElementSelector = selector;
- info(`Moved focus to ${selector}`);
- }
-
- if (options.preCheckContextMenuFn) {
- yield options.preCheckContextMenuFn();
- info("Completed preCheckContextMenuFn");
- }
-
- if (options.waitForSpellCheck) {
- info("Waiting for spell check");
- yield ContentTask.spawn(gBrowser.selectedBrowser, selector, function*(contentSelector) {
- let {onSpellCheck} = Cu.import("resource://gre/modules/AsyncSpellCheckTestHelper.jsm", {});
- let element = content.document.querySelector(contentSelector);
- yield new Promise(resolve => onSpellCheck(element, resolve));
- info("Spell check running");
- });
- }
-
- let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouse(selector, options.offsetX || 0, options.offsetY || 0, {
- type: "contextmenu",
- button: 2,
- shiftkey: options.shiftkey,
- centered: options.centered
- },
- gBrowser.selectedBrowser);
- yield awaitPopupShown;
- info("Popup Shown");
-
- if (options.onContextMenuShown) {
- yield options.onContextMenuShown();
- info("Completed onContextMenuShown");
- }
-
- if (menuItems) {
- if (Services.prefs.getBoolPref("devtools.inspector.enabled")) {
- let inspectItems = ["---", null,
- "context-inspect", true];
- menuItems = menuItems.concat(inspectItems);
- }
-
- checkContextMenu(menuItems);
- }
-
- let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
-
- if (options.postCheckContextMenuFn) {
- yield options.postCheckContextMenuFn();
- info("Completed postCheckContextMenuFn");
- }
-
- contextMenu.hidePopup();
- yield awaitPopupHidden;
-}
diff --git a/browser/base/content/test/general/ctxmenu-image.png b/browser/base/content/test/general/ctxmenu-image.png
deleted file mode 100644
index 4c3be5084..000000000
--- a/browser/base/content/test/general/ctxmenu-image.png
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/discovery.html b/browser/base/content/test/general/discovery.html
deleted file mode 100644
index 1679e6545..000000000
--- a/browser/base/content/test/general/discovery.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head id="linkparent">
- <title>Autodiscovery Test</title>
- </head>
- <body>
- </body>
-</html>
diff --git a/browser/base/content/test/general/download_page.html b/browser/base/content/test/general/download_page.html
deleted file mode 100644
index 4f9154033..000000000
--- a/browser/base/content/test/general/download_page.html
+++ /dev/null
@@ -1,47 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=676619
--->
- <head>
- <title>Test for the download attribute</title>
-
- </head>
- <body>
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=676619">Bug 676619</a>
- <br/>
- <ul>
- <li><a href="data:text/plain,Hey What are you looking for?"
- download="test.txt" id="link1">Download "test.txt"</a></li>
- <li><a href="video.ogg"
- download id="link2">Download "video.ogg"</a></li>
- <li><a href="video.ogg"
- download="just some video" id="link3">Download "just some video"</a></li>
- <li><a href="data:text/plain,test"
- download="with-target.txt" id="link4">Download "with-target.txt"</a></li>
- <li><a href="javascript:(1+2)+''"
- download="javascript.txt" id="link5">Download "javascript.txt"</a></li>
- </ul>
- <script>
- var li = document.createElement('li');
- var a = document.createElement('a');
-
- a.href = window.URL.createObjectURL(new Blob(["just text"])) ;
- a.download = "test.blob";
- a.id = "link6";
- a.textContent = 'Download "test.blob"';
-
- li.appendChild(a);
- document.getElementsByTagName('ul')[0].appendChild(li);
-
- window.addEventListener("beforeunload", function (evt) {
- document.getElementById("unload-flag").textContent = "Fail";
- });
- </script>
- <ul>
- <li><a href="http://example.com/"
- download="example.com" id="link7" target="_blank">Download "example.com"</a></li>
- <ul>
- <div id="unload-flag">Okay</div>
- </body>
-</html>
diff --git a/browser/base/content/test/general/dummy_page.html b/browser/base/content/test/general/dummy_page.html
deleted file mode 100644
index 1a87e2840..000000000
--- a/browser/base/content/test/general/dummy_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Dummy test page</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Dummy test page</p>
-</body>
-</html>
diff --git a/browser/base/content/test/general/feed_discovery.html b/browser/base/content/test/general/feed_discovery.html
deleted file mode 100644
index baecba19b..000000000
--- a/browser/base/content/test/general/feed_discovery.html
+++ /dev/null
@@ -1,73 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=377611
--->
- <head>
- <title>Test for feed discovery</title>
- <meta charset="utf-8">
-
- <!-- Straight up standard -->
- <link rel="alternate" type="application/atom+xml" title="1" href="/1.atom" />
- <link rel="alternate" type="application/rss+xml" title="2" href="/2.rss" />
- <link rel="feed" title="3" href="/3.xml" />
-
- <!-- rel is a space-separated list -->
- <link rel=" alternate " type="application/atom+xml" title="4" href="/4.atom" />
- <link rel="foo alternate" type="application/atom+xml" title="5" href="/5.atom" />
- <link rel="alternate foo" type="application/atom+xml" title="6" href="/6.atom" />
- <link rel="foo alternate foo" type="application/atom+xml" title="7" href="/7.atom" />
- <link rel="meat feed cake" title="8" href="/8.atom" />
-
- <!-- rel is case-insensitive -->
- <link rel="ALTERNate" type="application/atom+xml" title="9" href="/9.atom" />
- <link rel="fEEd" title="10" href="/10.atom" />
-
- <!-- type can have leading and trailing whitespace -->
- <link rel="alternate" type=" application/atom+xml " title="11" href="/11.atom" />
-
- <!-- type is case-insensitive -->
- <link rel="alternate" type="aPPliCAtion/ATom+xML" title="12" href="/12.atom" />
-
- <!-- "feed stylesheet" is a feed, though "alternate stylesheet" isn't -->
- <link rel="feed stylesheet" title="13" href="/13.atom" />
-
- <!-- hyphens or letters around rel not allowed -->
- <link rel="disabled-alternate" type="application/atom+xml" title="Bogus1" href="/Bogus1" />
- <link rel="alternates" type="application/atom+xml" title="Bogus2" href="/Bogus2" />
- <link rel=" alternate-like" type="application/atom+xml" title="Bogus3" href="/Bogus3" />
-
- <!-- don't tolerate text/xml if title includes 'rss' not as a word -->
- <link rel="alternate" type="text/xml" title="Bogus4 scissorsshaped" href="/Bogus4" />
-
- <!-- don't tolerate application/xml if title includes 'rss' not as a word -->
- <link rel="alternate" type="application/xml" title="Bogus5 scissorsshaped" href="/Bogus5" />
-
- <!-- don't tolerate application/rdf+xml if title includes 'rss' not as a word -->
- <link rel="alternate" type="application/rdf+xml" title="Bogus6 scissorsshaped" href="/Bogus6" />
-
- <!-- don't tolerate random types -->
- <link rel="alternate" type="text/plain" title="Bogus7 rss" href="/Bogus7" />
-
- <!-- don't find Atom by title -->
- <link rel="foopy" type="application/atom+xml" title="Bogus8 Atom and RSS" href="/Bogus8" />
-
- <!-- don't find application/rss+xml by title -->
- <link rel="goats" type="application/rss+xml" title="Bogus9 RSS and Atom" href="/Bogus9" />
-
- <!-- don't find application/rdf+xml by title -->
- <link rel="alternate" type="application/rdf+xml" title="Bogus10 RSS and Atom" href="/Bogus10" />
-
- <!-- don't find application/xml by title -->
- <link rel="alternate" type="application/xml" title="Bogus11 RSS and Atom" href="/Bogus11" />
-
- <!-- don't find text/xml by title -->
- <link rel="alternate" type="text/xml" title="Bogus12 RSS and Atom" href="/Bogus12" />
-
- <!-- alternate and stylesheet isn't a feed -->
- <link rel="alternate stylesheet" type="application/rss+xml" title="Bogus13 RSS" href="/Bogus13" />
- </head>
- <body>
- </body>
-</html>
-
diff --git a/browser/base/content/test/general/feed_tab.html b/browser/base/content/test/general/feed_tab.html
deleted file mode 100644
index 50903f48b..000000000
--- a/browser/base/content/test/general/feed_tab.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=458579
--->
- <head>
- <title>Test for page info feeds tab</title>
-
- <!-- Straight up standard -->
- <link rel="alternate" type="application/atom+xml" title="1" href="/1.atom" />
- <link rel="alternate" type="application/rss+xml" title="2" href="/2.rss" />
- <link rel="feed" title="3" href="/3.xml" />
-
- </head>
- <body>
- </body>
-</html>
diff --git a/browser/base/content/test/general/file_bug1045809_1.html b/browser/base/content/test/general/file_bug1045809_1.html
deleted file mode 100644
index 9baf2d45d..000000000
--- a/browser/base/content/test/general/file_bug1045809_1.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
- <head>
- </head>
- <body>
- <iframe src="http://test1.example.com/browser/browser/base/content/test/general/file_bug1045809_2.html"></iframe>
- </body>
-</html>
diff --git a/browser/base/content/test/general/file_bug1045809_2.html b/browser/base/content/test/general/file_bug1045809_2.html
deleted file mode 100644
index 67a297dbc..000000000
--- a/browser/base/content/test/general/file_bug1045809_2.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
- <head>
- </head>
- <body>
- <div id="mixedContentContainer">Mixed Content is here</div>
- </body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_1.html b/browser/base/content/test/general/file_bug822367_1.html
deleted file mode 100644
index 62f42d226..000000000
--- a/browser/base/content/test/general/file_bug822367_1.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 1 for Mixed Content Blocker User Override - Mixed Script
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 1 for Bug 822367</title>
-</head>
-<body>
- <div id="testContent">
- <p id="p1"></p>
- </div>
- <script src="http://example.com/browser/browser/base/content/test/general/file_bug822367_1.js">
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_1.js b/browser/base/content/test/general/file_bug822367_1.js
deleted file mode 100644
index 175de363b..000000000
--- a/browser/base/content/test/general/file_bug822367_1.js
+++ /dev/null
@@ -1 +0,0 @@
-document.getElementById('p1').innerHTML="hello";
diff --git a/browser/base/content/test/general/file_bug822367_2.html b/browser/base/content/test/general/file_bug822367_2.html
deleted file mode 100644
index fe56ee213..000000000
--- a/browser/base/content/test/general/file_bug822367_2.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 2 for Mixed Content Blocker User Override - Mixed Display
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 2 for Bug 822367 - Mixed Display</title>
-</head>
-<body>
- <div id="testContent">
- <img src="http://example.com/tests/image/test/mochitest/blue.png">
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_3.html b/browser/base/content/test/general/file_bug822367_3.html
deleted file mode 100644
index c1ff2c000..000000000
--- a/browser/base/content/test/general/file_bug822367_3.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 3 for Mixed Content Blocker User Override - Mixed Script and Display
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 3 for Bug 822367</title>
- <script>
- function foo() {
- var x = document.createElement('p');
- x.setAttribute("id", "p2");
- x.innerHTML = "bye";
- document.getElementById("testContent").appendChild(x);
- }
- </script>
-</head>
-<body>
- <div id="testContent">
- <p id="p1"></p>
- <img src="http://example.com/tests/image/test/mochitest/blue.png" onload="foo()">
- </div>
- <script src="http://example.com/browser/browser/base/content/test/general/file_bug822367_1.js">
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_4.html b/browser/base/content/test/general/file_bug822367_4.html
deleted file mode 100644
index 9a073143f..000000000
--- a/browser/base/content/test/general/file_bug822367_4.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 4 for Mixed Content Blocker User Override - Mixed Script and Display
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 4 for Bug 822367</title>
-</head>
-<body>
- <div id="testContent">
- <p id="p1"></p>
- </div>
- <script src="http://example.com/browser/browser/base/content/test/general/file_bug822367_4.js">
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_4.js b/browser/base/content/test/general/file_bug822367_4.js
deleted file mode 100644
index 301db89c7..000000000
--- a/browser/base/content/test/general/file_bug822367_4.js
+++ /dev/null
@@ -1 +0,0 @@
-document.location = "https://example.com/browser/browser/base/content/test/general/file_bug822367_4B.html";
diff --git a/browser/base/content/test/general/file_bug822367_4B.html b/browser/base/content/test/general/file_bug822367_4B.html
deleted file mode 100644
index 76ea2b623..000000000
--- a/browser/base/content/test/general/file_bug822367_4B.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 4B for Mixed Content Blocker User Override - Location Changed
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 4B Location Change for Bug 822367</title>
-</head>
-<body>
- <div id="testContent">
- <p id="p1"></p>
- </div>
- <script src="http://example.com/browser/browser/base/content/test/general/file_bug822367_1.js">
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_5.html b/browser/base/content/test/general/file_bug822367_5.html
deleted file mode 100644
index 3c9a9317e..000000000
--- a/browser/base/content/test/general/file_bug822367_5.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 5 for Mixed Content Blocker User Override - Mixed Script in document.open()
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 5 for Bug 822367</title>
- <script>
- function createDoc()
- {
- var doc=document.open("text/html", "replace");
- doc.write('<!DOCTYPE html><html><body><p id="p1">This is some content</p><script src="http://example.com/browser/browser/base/content/test/general/file_bug822367_1.js">\<\/script\>\<\/body>\<\/html>');
- doc.close();
- }
- </script>
-</head>
-<body>
- <div id="testContent">
- <img src="https://example.com/tests/image/test/mochitest/blue.png" onload="createDoc()">
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug822367_6.html b/browser/base/content/test/general/file_bug822367_6.html
deleted file mode 100644
index baa5674c2..000000000
--- a/browser/base/content/test/general/file_bug822367_6.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 6 for Mixed Content Blocker User Override - Mixed Script in document.open() within an iframe
-https://bugzilla.mozilla.org/show_bug.cgi?id=822367
--->
-<head>
- <meta charset="utf-8">
- <title>Test 6 for Bug 822367</title>
-</head>
-<body>
- <div id="testContent">
- <iframe name="f1" id="f1" src="https://example.com/browser/browser/base/content/test/general/file_bug822367_5.html"></iframe>
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug902156.js b/browser/base/content/test/general/file_bug902156.js
deleted file mode 100644
index f943dd628..000000000
--- a/browser/base/content/test/general/file_bug902156.js
+++ /dev/null
@@ -1,5 +0,0 @@
-/*
- * Once the mixed content blocker is disabled for the page, this scripts loads
- * and updates the text inside the div container.
- */
-document.getElementById("mctestdiv").innerHTML = "Mixed Content Blocker disabled";
diff --git a/browser/base/content/test/general/file_bug902156_1.html b/browser/base/content/test/general/file_bug902156_1.html
deleted file mode 100644
index e3625de99..000000000
--- a/browser/base/content/test/general/file_bug902156_1.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 1 for Bug 902156 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=902156
--->
-<head>
- <meta charset="utf-8">
- <title>Test 1 for Bug 902156</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <script src="http://test1.example.com/browser/browser/base/content/test/general/file_bug902156.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug902156_2.html b/browser/base/content/test/general/file_bug902156_2.html
deleted file mode 100644
index 25aff3349..000000000
--- a/browser/base/content/test/general/file_bug902156_2.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 2 for Bug 902156 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=902156
--->
-<head>
- <meta charset="utf-8">
- <title>Test 2 for Bug 902156</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <a href="https://test2.example.com/browser/browser/base/content/test/general/file_bug902156_1.html"
- id="mctestlink" target="_top">Go to http site</a>
- <script src="http://test2.example.com/browser/browser/base/content/test/general/file_bug902156.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug902156_3.html b/browser/base/content/test/general/file_bug902156_3.html
deleted file mode 100644
index 65805adff..000000000
--- a/browser/base/content/test/general/file_bug902156_3.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 3 for Bug 902156 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=902156
--->
-<head>
- <meta charset="utf-8">
- <title>Test 3 for Bug 902156</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <script src="http://test1.example.com/browser/browser/base/content/test/general/file_bug902156.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug906190.js b/browser/base/content/test/general/file_bug906190.js
deleted file mode 100644
index f943dd628..000000000
--- a/browser/base/content/test/general/file_bug906190.js
+++ /dev/null
@@ -1,5 +0,0 @@
-/*
- * Once the mixed content blocker is disabled for the page, this scripts loads
- * and updates the text inside the div container.
- */
-document.getElementById("mctestdiv").innerHTML = "Mixed Content Blocker disabled";
diff --git a/browser/base/content/test/general/file_bug906190.sjs b/browser/base/content/test/general/file_bug906190.sjs
deleted file mode 100644
index bff126874..000000000
--- a/browser/base/content/test/general/file_bug906190.sjs
+++ /dev/null
@@ -1,17 +0,0 @@
-function handleRequest(request, response) {
- var page = "<!DOCTYPE html><html><body>bug 906190</body></html>";
- var path = "https://test1.example.com/browser/browser/base/content/test/general/";
- var url;
-
- if (request.queryString.includes('bad-redirection=1')) {
- url = path + "this_page_does_not_exist.html";
- } else {
- url = path + "file_bug906190_redirected.html";
- }
-
- response.setHeader("Cache-Control", "no-cache", false);
- response.setHeader("Content-Type", "text/html", false);
- response.setStatusLine(request.httpVersion, "302", "Found");
- response.setHeader("Location", url, false);
- response.write(page);
-}
diff --git a/browser/base/content/test/general/file_bug906190_1.html b/browser/base/content/test/general/file_bug906190_1.html
deleted file mode 100644
index cbb3cac26..000000000
--- a/browser/base/content/test/general/file_bug906190_1.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 1 for Bug 906190 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=906190
--->
-<head>
- <meta charset="utf-8">
- <title>Test 1 for Bug 906190</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <script src="http://test1.example.com/browser/browser/base/content/test/general/file_bug906190.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug906190_2.html b/browser/base/content/test/general/file_bug906190_2.html
deleted file mode 100644
index 70c7c61cf..000000000
--- a/browser/base/content/test/general/file_bug906190_2.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 2 for Bug 906190 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=906190
--->
-<head>
- <meta charset="utf-8">
- <title>Test 2 for Bug 906190</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <script src="http://test2.example.com/browser/browser/base/content/test/general/file_bug906190.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug906190_3_4.html b/browser/base/content/test/general/file_bug906190_3_4.html
deleted file mode 100644
index aea6648a9..000000000
--- a/browser/base/content/test/general/file_bug906190_3_4.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 3 and 4 for Bug 906190 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=906190
--->
-<head>
- <meta charset="utf-8">
- <meta http-equiv="refresh" content="0; url=https://test1.example.com/browser/browser/base/content/test/general/file_bug906190_redirected.html">
- <title>Test 3 and 4 for Bug 906190</title>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug906190_redirected.html b/browser/base/content/test/general/file_bug906190_redirected.html
deleted file mode 100644
index cc324bd25..000000000
--- a/browser/base/content/test/general/file_bug906190_redirected.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Redirected Page of Test 3 to 6 for Bug 906190 - See file browser_bug902156.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=906190
--->
-<head>
- <meta charset="utf-8">
- <title>Redirected Page for Bug 906190</title>
-</head>
-<body>
- <div id="mctestdiv">Mixed Content Blocker enabled</div>
- <script src="http://test1.example.com/browser/browser/base/content/test/general/file_bug906190.js" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug970276_favicon1.ico b/browser/base/content/test/general/file_bug970276_favicon1.ico
deleted file mode 100644
index d44438903..000000000
--- a/browser/base/content/test/general/file_bug970276_favicon1.ico
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/file_bug970276_favicon2.ico b/browser/base/content/test/general/file_bug970276_favicon2.ico
deleted file mode 100644
index d44438903..000000000
--- a/browser/base/content/test/general/file_bug970276_favicon2.ico
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/file_bug970276_popup1.html b/browser/base/content/test/general/file_bug970276_popup1.html
deleted file mode 100644
index 5ce7dab87..000000000
--- a/browser/base/content/test/general/file_bug970276_popup1.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test file for bug 970276.</title>
-
- <!--Set a favicon; that's the whole point of this file.-->
- <link rel="icon" href="file_bug970276_favicon1.ico">
-</head>
-<body>
- Test file for bug 970276.
-
- <iframe src="file_bug970276_popup2.html">
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_bug970276_popup2.html b/browser/base/content/test/general/file_bug970276_popup2.html
deleted file mode 100644
index 0b9e5294e..000000000
--- a/browser/base/content/test/general/file_bug970276_popup2.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test file for bug 970276.</title>
-
- <!--Set a favicon; that's the whole point of this file.-->
- <link rel="icon" href="file_bug970276_favicon2.ico">
-</head>
-<body>
- Test inner file for bug 970276.
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_csp_block_all_mixedcontent.html b/browser/base/content/test/general/file_csp_block_all_mixedcontent.html
deleted file mode 100644
index 93a7f13d9..000000000
--- a/browser/base/content/test/general/file_csp_block_all_mixedcontent.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html><head><meta charset="utf-8">
-<title>Bug 1122236 - CSP: Implement block-all-mixed-content</title>
-</head>
-<meta http-equiv="Content-Security-Policy" content="block-all-mixed-content">
-<body>
-<script src="http://example.com/browser/browser/base/content/test/general/file_csp_block_all_mixedcontent.js"/>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_csp_block_all_mixedcontent.js b/browser/base/content/test/general/file_csp_block_all_mixedcontent.js
deleted file mode 100644
index dc6d6a64e..000000000
--- a/browser/base/content/test/general/file_csp_block_all_mixedcontent.js
+++ /dev/null
@@ -1,3 +0,0 @@
-// empty script file just used for testing Bug 1122236.
-// Making sure the UI is not degraded when blocking
-// mixed content using the CSP directive: block-all-mixed-content.
diff --git a/browser/base/content/test/general/file_documentnavigation_frameset.html b/browser/base/content/test/general/file_documentnavigation_frameset.html
deleted file mode 100644
index beb01addf..000000000
--- a/browser/base/content/test/general/file_documentnavigation_frameset.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<html id="outer">
-
-<frameset rows="30%, 70%">
- <frame src="data:text/html,&lt;html id='htmlframe1' &gt;&lt;body id='framebody1'&gt;&lt;input id='i1'&gt;&lt;body&gt;&lt;/html&gt;">
- <frameset cols="30%, 33%, 34%">
- <frame src="data:text/html,&lt;html id='htmlframe2'&gt;&lt;body id='framebody2'&gt;&lt;input id='i2'&gt;&lt;body&gt;&lt;/html&gt;">
- <frame src="data:text/html,&lt;html id='htmlframe3'&gt;&lt;body id='framebody3'&gt;&lt;input id='i3'&gt;&lt;body&gt;&lt;/html&gt;">
- <frame src="data:text/html,&lt;html id='htmlframe4'&gt;&lt;body id='framebody4'&gt;&lt;input id='i4'&gt;&lt;body&gt;&lt;/html&gt;">
- </frameset>
-</frameset>
-
-</html>
diff --git a/browser/base/content/test/general/file_double_close_tab.html b/browser/base/content/test/general/file_double_close_tab.html
deleted file mode 100644
index 0bead5efc..000000000
--- a/browser/base/content/test/general/file_double_close_tab.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- <title>Test page that blocks beforeunload. Used in tests for bug 1050638 and bug 305085</title>
- </head>
- <body>
- This page will block beforeunload. It should still be user-closable at all times.
- <script>
- window.onbeforeunload = function() {
- return "stop";
- };
- </script>
- </body>
-</html>
diff --git a/browser/base/content/test/general/file_favicon_change.html b/browser/base/content/test/general/file_favicon_change.html
deleted file mode 100644
index 18ac6526b..000000000
--- a/browser/base/content/test/general/file_favicon_change.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE html>
-<html><head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <link rel="icon" href="http://example.org/one-icon" type="image/ico" id="i">
-</head>
-<body>
- <script>
- window.addEventListener("PleaseChangeFavicon", function() {
- var ico = document.getElementById("i");
- ico.setAttribute("href", "http://example.org/other-icon");
- });
- </script>
-</body></html>
diff --git a/browser/base/content/test/general/file_favicon_change_not_in_document.html b/browser/base/content/test/general/file_favicon_change_not_in_document.html
deleted file mode 100644
index deebb07dc..000000000
--- a/browser/base/content/test/general/file_favicon_change_not_in_document.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!DOCTYPE html>
-<html><head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <link rel="icon" href="http://example.org/one-icon" type="image/ico" id="i">
-</head>
-<body onload="onload()">
- <script>
- function onload() {
- var ico = document.createElement("link");
- ico.setAttribute("rel", "icon");
- ico.setAttribute("type", "image/ico");
- ico.setAttribute("href", "http://example.org/other-icon");
- setTimeout(function() {
- ico.setAttribute("href", "http://example.org/yet-another-icon");
- document.getElementById("i").remove();
- document.head.appendChild(ico);
- }, 1000);
- }
- </script>
-</body></html>
-
diff --git a/browser/base/content/test/general/file_fullscreen-window-open.html b/browser/base/content/test/general/file_fullscreen-window-open.html
deleted file mode 100644
index 1584f4c98..000000000
--- a/browser/base/content/test/general/file_fullscreen-window-open.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Test for window.open() when browser is in fullscreen</title>
- </head>
- <body>
- <script>
- window.addEventListener("load", function onLoad() {
- window.removeEventListener("load", onLoad, true);
-
- document.getElementById("test").addEventListener("click", onClick, true);
- }, true);
-
- function onClick(aEvent) {
- aEvent.preventDefault();
-
- var dataStr = aEvent.target.getAttribute("data-test-param");
- var data = JSON.parse(dataStr);
- window.open(data.uri, data.title, data.option);
- }
- </script>
- <a id="test" href="" data-test-param="">Test</a>
- </body>
-</html>
diff --git a/browser/base/content/test/general/file_generic_favicon.ico b/browser/base/content/test/general/file_generic_favicon.ico
deleted file mode 100644
index d44438903..000000000
--- a/browser/base/content/test/general/file_generic_favicon.ico
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/file_mediaPlayback.html b/browser/base/content/test/general/file_mediaPlayback.html
deleted file mode 100644
index a6979287e..000000000
--- a/browser/base/content/test/general/file_mediaPlayback.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<!DOCTYPE html>
-<audio src="audio.ogg" controls loop>
diff --git a/browser/base/content/test/general/file_mixedContentFramesOnHttp.html b/browser/base/content/test/general/file_mixedContentFramesOnHttp.html
deleted file mode 100644
index 3bd16aea5..000000000
--- a/browser/base/content/test/general/file_mixedContentFramesOnHttp.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test for https://bugzilla.mozilla.org/show_bug.cgi?id=1182551
--->
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 1182551</title>
-</head>
-<body>
- <p>Test for Bug 1182551. This is an HTTP top level page. We include an HTTPS iframe that loads mixed passive content.</p>
- <iframe src="https://example.org/browser/browser/base/content/test/general/file_mixedPassiveContent.html"></iframe>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_mixedContentFromOnunload.html b/browser/base/content/test/general/file_mixedContentFromOnunload.html
deleted file mode 100644
index fb28a2889..000000000
--- a/browser/base/content/test/general/file_mixedContentFromOnunload.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test for https://bugzilla.mozilla.org/show_bug.cgi?id=947079
--->
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 947079</title>
-</head>
-<body>
- <p>Test for Bug 947079</p>
- <script>
- window.addEventListener('unload', function() {
- new Image().src = 'http://mochi.test:8888/tests/image/test/mochitest/blue.png';
- });
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_mixedContentFromOnunload_test1.html b/browser/base/content/test/general/file_mixedContentFromOnunload_test1.html
deleted file mode 100644
index 1d027b036..000000000
--- a/browser/base/content/test/general/file_mixedContentFromOnunload_test1.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 1 for https://bugzilla.mozilla.org/show_bug.cgi?id=947079
-Page with no insecure subresources
--->
-<head>
- <meta charset="utf-8">
- <title>Test 1 for Bug 947079</title>
-</head>
-<body>
- <p>There are no insecure resource loads on this page</p>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_mixedContentFromOnunload_test2.html b/browser/base/content/test/general/file_mixedContentFromOnunload_test2.html
deleted file mode 100644
index 4813337cc..000000000
--- a/browser/base/content/test/general/file_mixedContentFromOnunload_test2.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test 2 for https://bugzilla.mozilla.org/show_bug.cgi?id=947079
-Page with an insecure image load
--->
-<head>
- <meta charset="utf-8">
- <title>Test 2 for Bug 947079</title>
-</head>
-<body>
- <p>Page with http image load</p>
- <img src="http://test2.example.com/tests/image/test/mochitest/blue.png">
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_mixedPassiveContent.html b/browser/base/content/test/general/file_mixedPassiveContent.html
deleted file mode 100644
index a60ac94e8..000000000
--- a/browser/base/content/test/general/file_mixedPassiveContent.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-Test for https://bugzilla.mozilla.org/show_bug.cgi?id=1182551
--->
-<head>
- <meta charset="utf-8">
- <title>HTTPS page with HTTP image</title>
-</head>
-<body>
- <img src="http://mochi.test:8888/tests/image/test/mochitest/blue.png">
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_trackingUI_6.html b/browser/base/content/test/general/file_trackingUI_6.html
deleted file mode 100644
index 52e1ae63f..000000000
--- a/browser/base/content/test/general/file_trackingUI_6.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="UTF-8">
- <title>Testing the shield from fetch and XHR</title>
-</head>
-<body>
- <p>Hello there!</p>
- <script type="application/javascript; version=1.8">
- function test_fetch() {
- let url = "http://trackertest.org/browser/browser/base/content/test/general/file_trackingUI_6.js";
- return fetch(url);
- }
- </script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/file_trackingUI_6.js b/browser/base/content/test/general/file_trackingUI_6.js
deleted file mode 100644
index f7ac687cf..000000000
--- a/browser/base/content/test/general/file_trackingUI_6.js
+++ /dev/null
@@ -1,2 +0,0 @@
-/* Some code goes here! */
-void 0;
diff --git a/browser/base/content/test/general/file_trackingUI_6.js^headers^ b/browser/base/content/test/general/file_trackingUI_6.js^headers^
deleted file mode 100644
index cb762eff8..000000000
--- a/browser/base/content/test/general/file_trackingUI_6.js^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Access-Control-Allow-Origin: *
diff --git a/browser/base/content/test/general/file_with_favicon.html b/browser/base/content/test/general/file_with_favicon.html
deleted file mode 100644
index 0702b4aab..000000000
--- a/browser/base/content/test/general/file_with_favicon.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test file for bugs with favicons</title>
-
- <!--Set a favicon; that's the whole point of this file.-->
- <link rel="icon" href="file_generic_favicon.ico">
-</head>
-<body>
- Test file for bugs with favicons
-</body>
-</html>
diff --git a/browser/base/content/test/general/fxa_profile_handler.sjs b/browser/base/content/test/general/fxa_profile_handler.sjs
deleted file mode 100644
index 7160b76d0..000000000
--- a/browser/base/content/test/general/fxa_profile_handler.sjs
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This is basically an echo server!
-// We just grab responseStatus and responseBody query params!
-
-function reallyHandleRequest(request, response) {
- var query = "?" + request.queryString;
-
- var responseStatus = 200;
- var match = /responseStatus=([^&]*)/.exec(query);
- if (match) {
- responseStatus = parseInt(match[1]);
- }
-
- var responseBody = "";
- match = /responseBody=([^&]*)/.exec(query);
- if (match) {
- responseBody = decodeURIComponent(match[1]);
- }
-
- response.setStatusLine("1.0", responseStatus, "OK");
- response.write(responseBody);
-}
-
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 500, "NotOK");
- response.write("Error handling request: " + e);
- }
-}
diff --git a/browser/base/content/test/general/gZipOfflineChild.cacheManifest b/browser/base/content/test/general/gZipOfflineChild.cacheManifest
deleted file mode 100644
index ae0545d12..000000000
--- a/browser/base/content/test/general/gZipOfflineChild.cacheManifest
+++ /dev/null
@@ -1,2 +0,0 @@
-CACHE MANIFEST
-gZipOfflineChild.html
diff --git a/browser/base/content/test/general/gZipOfflineChild.cacheManifest^headers^ b/browser/base/content/test/general/gZipOfflineChild.cacheManifest^headers^
deleted file mode 100644
index 257f2eb60..000000000
--- a/browser/base/content/test/general/gZipOfflineChild.cacheManifest^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: text/cache-manifest
diff --git a/browser/base/content/test/general/gZipOfflineChild.html b/browser/base/content/test/general/gZipOfflineChild.html
deleted file mode 100644
index ea2caa125..000000000
--- a/browser/base/content/test/general/gZipOfflineChild.html
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/gZipOfflineChild.html^headers^ b/browser/base/content/test/general/gZipOfflineChild.html^headers^
deleted file mode 100644
index 4204d8601..000000000
--- a/browser/base/content/test/general/gZipOfflineChild.html^headers^
+++ /dev/null
@@ -1,2 +0,0 @@
-Content-Type: text/html
-Content-Encoding: gzip
diff --git a/browser/base/content/test/general/gZipOfflineChild_uncompressed.html b/browser/base/content/test/general/gZipOfflineChild_uncompressed.html
deleted file mode 100644
index 4ab8f8d5e..000000000
--- a/browser/base/content/test/general/gZipOfflineChild_uncompressed.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<html manifest="gZipOfflineChild.cacheManifest">
-<head>
- <!-- This file is gzipped to create gZipOfflineChild.html -->
-<title></title>
-<script type="text/javascript">
-
-function finish(success) {
- window.parent.postMessage(success, "*");
-}
-
-applicationCache.oncached = function() { finish("oncache"); }
-applicationCache.onnoupdate = function() { finish("onupdate"); }
-applicationCache.onerror = function() { finish("onerror"); }
-
-</script>
-</head>
-
-<body>
-<h1>Child</h1>
-</body>
-</html>
diff --git a/browser/base/content/test/general/head.js b/browser/base/content/test/general/head.js
deleted file mode 100644
index 6c28615fe..000000000
--- a/browser/base/content/test/general/head.js
+++ /dev/null
@@ -1,1069 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "TabCrashHandler",
- "resource:///modules/ContentCrashHandlers.jsm");
-
-/**
- * Wait for a <notification> to be closed then call the specified callback.
- */
-function waitForNotificationClose(notification, cb) {
- let parent = notification.parentNode;
-
- let observer = new MutationObserver(function onMutatations(mutations) {
- for (let mutation of mutations) {
- for (let i = 0; i < mutation.removedNodes.length; i++) {
- let node = mutation.removedNodes.item(i);
- if (node != notification) {
- continue;
- }
- observer.disconnect();
- cb();
- }
- }
- });
- observer.observe(parent, {childList: true});
-}
-
-function closeAllNotifications () {
- let notificationBox = document.getElementById("global-notificationbox");
-
- if (!notificationBox || !notificationBox.currentNotification) {
- return Promise.resolve();
- }
-
- let deferred = Promise.defer();
- for (let notification of notificationBox.allNotifications) {
- waitForNotificationClose(notification, function () {
- if (notificationBox.allNotifications.length === 0) {
- deferred.resolve();
- }
- });
- notification.close();
- }
-
- return deferred.promise;
-}
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- executeSoon(aCallback);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function updateTabContextMenu(tab, onOpened) {
- let menu = document.getElementById("tabContextMenu");
- if (!tab)
- tab = gBrowser.selectedTab;
- var evt = new Event("");
- tab.dispatchEvent(evt);
- menu.openPopup(tab, "end_after", 0, 0, true, false, evt);
- is(TabContextMenu.contextTab, tab, "TabContextMenu context is the expected tab");
- const onFinished = () => menu.hidePopup();
- if (onOpened) {
- return Task.spawn(function*() {
- yield onOpened();
- onFinished();
- });
- }
- onFinished();
- return Promise.resolve();
-}
-
-function openToolbarCustomizationUI(aCallback, aBrowserWin) {
- if (!aBrowserWin)
- aBrowserWin = window;
-
- aBrowserWin.gCustomizeMode.enter();
-
- aBrowserWin.gNavToolbox.addEventListener("customizationready", function UI_loaded() {
- aBrowserWin.gNavToolbox.removeEventListener("customizationready", UI_loaded);
- executeSoon(function() {
- aCallback(aBrowserWin)
- });
- });
-}
-
-function closeToolbarCustomizationUI(aCallback, aBrowserWin) {
- aBrowserWin.gNavToolbox.addEventListener("aftercustomization", function unloaded() {
- aBrowserWin.gNavToolbox.removeEventListener("aftercustomization", unloaded);
- executeSoon(aCallback);
- });
-
- aBrowserWin.gCustomizeMode.exit();
-}
-
-function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
- var tries = 0;
- var interval = setInterval(function() {
- if (tries >= retryTimes) {
- ok(false, errorMsg);
- moveOn();
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, 100);
- var moveOn = function() { clearInterval(interval); nextTest(); };
-}
-
-function promiseWaitForCondition(aConditionFn) {
- let deferred = Promise.defer();
- waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
- return deferred.promise;
-}
-
-function promiseWaitForEvent(object, eventName, capturing = false, chrome = false) {
- return new Promise((resolve) => {
- function listener(event) {
- info("Saw " + eventName);
- object.removeEventListener(eventName, listener, capturing, chrome);
- resolve(event);
- }
-
- info("Waiting for " + eventName);
- object.addEventListener(eventName, listener, capturing, chrome);
- });
-}
-
-/**
- * Allows setting focus on a window, and waiting for that window to achieve
- * focus.
- *
- * @param aWindow
- * The window to focus and wait for.
- *
- * @return {Promise}
- * @resolves When the window is focused.
- * @rejects Never.
- */
-function promiseWaitForFocus(aWindow) {
- return new Promise((resolve) => {
- waitForFocus(resolve, aWindow);
- });
-}
-
-function getTestPlugin(aName) {
- var pluginName = aName || "Test Plug-in";
- var ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
- var tags = ph.getPluginTags();
-
- // Find the test plugin
- for (var i = 0; i < tags.length; i++) {
- if (tags[i].name == pluginName)
- return tags[i];
- }
- ok(false, "Unable to find plugin");
- return null;
-}
-
-// call this to set the test plugin(s) initially expected enabled state.
-// it will automatically be reset to it's previous value after the test
-// ends
-function setTestPluginEnabledState(newEnabledState, pluginName) {
- var plugin = getTestPlugin(pluginName);
- var oldEnabledState = plugin.enabledState;
- plugin.enabledState = newEnabledState;
- SimpleTest.registerCleanupFunction(function() {
- getTestPlugin(pluginName).enabledState = oldEnabledState;
- });
-}
-
-function pushPrefs(...aPrefs) {
- let deferred = Promise.defer();
- SpecialPowers.pushPrefEnv({"set": aPrefs}, deferred.resolve);
- return deferred.promise;
-}
-
-function updateBlocklist(aCallback) {
- var blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
- .getService(Ci.nsITimerCallback);
- var observer = function() {
- Services.obs.removeObserver(observer, "blocklist-updated");
- SimpleTest.executeSoon(aCallback);
- };
- Services.obs.addObserver(observer, "blocklist-updated", false);
- blocklistNotifier.notify(null);
-}
-
-var _originalTestBlocklistURL = null;
-function setAndUpdateBlocklist(aURL, aCallback) {
- if (!_originalTestBlocklistURL)
- _originalTestBlocklistURL = Services.prefs.getCharPref("extensions.blocklist.url");
- Services.prefs.setCharPref("extensions.blocklist.url", aURL);
- updateBlocklist(aCallback);
-}
-
-function resetBlocklist() {
- Services.prefs.setCharPref("extensions.blocklist.url", _originalTestBlocklistURL);
-}
-
-function whenNewWindowLoaded(aOptions, aCallback) {
- let win = OpenBrowserWindow(aOptions);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- aCallback(win);
- }, false);
-}
-
-function promiseWindowWillBeClosed(win) {
- return new Promise((resolve, reject) => {
- Services.obs.addObserver(function observe(subject, topic) {
- if (subject == win) {
- Services.obs.removeObserver(observe, topic);
- resolve();
- }
- }, "domwindowclosed", false);
- });
-}
-
-function promiseWindowClosed(win) {
- let promise = promiseWindowWillBeClosed(win);
- win.close();
- return promise;
-}
-
-function promiseOpenAndLoadWindow(aOptions, aWaitForDelayedStartup=false) {
- let deferred = Promise.defer();
- let win = OpenBrowserWindow(aOptions);
- if (aWaitForDelayedStartup) {
- Services.obs.addObserver(function onDS(aSubject, aTopic, aData) {
- if (aSubject != win) {
- return;
- }
- Services.obs.removeObserver(onDS, "browser-delayed-startup-finished");
- deferred.resolve(win);
- }, "browser-delayed-startup-finished", false);
-
- } else {
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- deferred.resolve(win);
- });
- }
- return deferred.promise;
-}
-
-/**
- * Waits for all pending async statements on the default connection, before
- * proceeding with aCallback.
- *
- * @param aCallback
- * Function to be called when done.
- * @param aScope
- * Scope for the callback.
- * @param aArguments
- * Arguments array for the callback.
- *
- * @note The result is achieved by asynchronously executing a query requiring
- * a write lock. Since all statements on the same connection are
- * serialized, the end of this write operation means that all writes are
- * complete. Note that WAL makes so that writers don't block readers, but
- * this is a problem only across different connections.
- */
-function waitForAsyncUpdates(aCallback, aScope, aArguments) {
- let scope = aScope || this;
- let args = aArguments || [];
- let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
- let begin = db.createAsyncStatement("BEGIN EXCLUSIVE");
- begin.executeAsync();
- begin.finalize();
-
- let commit = db.createAsyncStatement("COMMIT");
- commit.executeAsync({
- handleResult: function() {},
- handleError: function() {},
- handleCompletion: function(aReason) {
- aCallback.apply(scope, args);
- }
- });
- commit.finalize();
-}
-
-/**
- * Asynchronously check a url is visited.
-
- * @param aURI The URI.
- * @param aExpectedValue The expected value.
- * @return {Promise}
- * @resolves When the check has been added successfully.
- * @rejects JavaScript exception.
- */
-function promiseIsURIVisited(aURI, aExpectedValue) {
- let deferred = Promise.defer();
- PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
- deferred.resolve(aIsVisited);
- });
-
- return deferred.promise;
-}
-
-function whenNewTabLoaded(aWindow, aCallback) {
- aWindow.BrowserOpenTab();
-
- let browser = aWindow.gBrowser.selectedBrowser;
- if (browser.contentDocument.readyState === "complete") {
- aCallback();
- return;
- }
-
- whenTabLoaded(aWindow.gBrowser.selectedTab, aCallback);
-}
-
-function whenTabLoaded(aTab, aCallback) {
- promiseTabLoadEvent(aTab).then(aCallback);
-}
-
-function promiseTabLoaded(aTab) {
- let deferred = Promise.defer();
- whenTabLoaded(aTab, deferred.resolve);
- return deferred.promise;
-}
-
-/**
- * Ensures that the specified URIs are either cleared or not.
- *
- * @param aURIs
- * Array of page URIs
- * @param aShouldBeCleared
- * True if each visit to the URI should be cleared, false otherwise
- */
-function promiseHistoryClearedState(aURIs, aShouldBeCleared) {
- let deferred = Promise.defer();
- let callbackCount = 0;
- let niceStr = aShouldBeCleared ? "no longer" : "still";
- function callbackDone() {
- if (++callbackCount == aURIs.length)
- deferred.resolve();
- }
- aURIs.forEach(function (aURI) {
- PlacesUtils.asyncHistory.isURIVisited(aURI, function(uri, isVisited) {
- is(isVisited, !aShouldBeCleared,
- "history visit " + uri.spec + " should " + niceStr + " exist");
- callbackDone();
- });
- });
-
- return deferred.promise;
-}
-
-/**
- * Waits for the next top-level document load in the current browser. The URI
- * of the document is compared against aExpectedURL. The load is then stopped
- * before it actually starts.
- *
- * @param aExpectedURL
- * The URL of the document that is expected to load.
- * @param aStopFromProgressListener
- * Whether to cancel the load directly from the progress listener. Defaults to true.
- * If you're using this method to avoid hitting the network, you want the default (true).
- * However, the browser UI will behave differently for loads stopped directly from
- * the progress listener (effectively in the middle of a call to loadURI) and so there
- * are cases where you may want to avoid stopping the load directly from within the
- * progress listener callback.
- * @return promise
- */
-function waitForDocLoadAndStopIt(aExpectedURL, aBrowser=gBrowser.selectedBrowser, aStopFromProgressListener=true) {
- function content_script(contentStopFromProgressListener) {
- let { interfaces: Ci, utils: Cu } = Components;
- Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
- let wp = docShell.QueryInterface(Ci.nsIWebProgress);
-
- function stopContent(now, uri) {
- if (now) {
- /* Hammer time. */
- content.stop();
-
- /* Let the parent know we're done. */
- sendAsyncMessage("Test:WaitForDocLoadAndStopIt", { uri });
- } else {
- setTimeout(stopContent.bind(null, true, uri), 0);
- }
- }
-
- let progressListener = {
- onStateChange: function (webProgress, req, flags, status) {
- dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n");
-
- if (webProgress.isTopLevel &&
- flags & Ci.nsIWebProgressListener.STATE_START) {
- wp.removeProgressListener(progressListener);
-
- let chan = req.QueryInterface(Ci.nsIChannel);
- dump(`waitForDocLoadAndStopIt: Document start: ${chan.URI.spec}\n`);
-
- stopContent(contentStopFromProgressListener, chan.originalURI.spec);
- }
- },
- QueryInterface: XPCOMUtils.generateQI(["nsISupportsWeakReference"])
- };
- wp.addProgressListener(progressListener, wp.NOTIFY_STATE_WINDOW);
-
- /**
- * As |this| is undefined and we can't extend |docShell|, adding an unload
- * event handler is the easiest way to ensure the weakly referenced
- * progress listener is kept alive as long as necessary.
- */
- addEventListener("unload", function () {
- try {
- wp.removeProgressListener(progressListener);
- } catch (e) { /* Will most likely fail. */ }
- });
- }
-
- return new Promise((resolve, reject) => {
- function complete({ data }) {
- is(data.uri, aExpectedURL, "waitForDocLoadAndStopIt: The expected URL was loaded");
- mm.removeMessageListener("Test:WaitForDocLoadAndStopIt", complete);
- resolve();
- }
-
- let mm = aBrowser.messageManager;
- mm.loadFrameScript("data:,(" + content_script.toString() + ")(" + aStopFromProgressListener + ");", true);
- mm.addMessageListener("Test:WaitForDocLoadAndStopIt", complete);
- info("waitForDocLoadAndStopIt: Waiting for URL: " + aExpectedURL);
- });
-}
-
-/**
- * Waits for the next load to complete in any browser or the given browser.
- * If a <tabbrowser> is given it waits for a load in any of its browsers.
- *
- * @return promise
- */
-function waitForDocLoadComplete(aBrowser=gBrowser) {
- return new Promise(resolve => {
- let listener = {
- onStateChange: function (webProgress, req, flags, status) {
- let docStop = Ci.nsIWebProgressListener.STATE_IS_NETWORK |
- Ci.nsIWebProgressListener.STATE_STOP;
- info("Saw state " + flags.toString(16) + " and status " + status.toString(16));
-
- // When a load needs to be retargetted to a new process it is cancelled
- // with NS_BINDING_ABORTED so ignore that case
- if ((flags & docStop) == docStop && status != Cr.NS_BINDING_ABORTED) {
- aBrowser.removeProgressListener(this);
- waitForDocLoadComplete.listeners.delete(this);
-
- let chan = req.QueryInterface(Ci.nsIChannel);
- info("Browser loaded " + chan.originalURI.spec);
- resolve();
- }
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
- Ci.nsISupportsWeakReference])
- };
- aBrowser.addProgressListener(listener);
- waitForDocLoadComplete.listeners.add(listener);
- info("Waiting for browser load");
- });
-}
-
-// Keep a set of progress listeners for waitForDocLoadComplete() to make sure
-// they're not GC'ed before we saw the page load.
-waitForDocLoadComplete.listeners = new Set();
-registerCleanupFunction(() => waitForDocLoadComplete.listeners.clear());
-
-var FullZoomHelper = {
-
- selectTabAndWaitForLocationChange: function selectTabAndWaitForLocationChange(tab) {
- if (!tab)
- throw new Error("tab must be given.");
- if (gBrowser.selectedTab == tab)
- return Promise.resolve();
-
- return Promise.all([BrowserTestUtils.switchTab(gBrowser, tab),
- this.waitForLocationChange()]);
- },
-
- removeTabAndWaitForLocationChange: function removeTabAndWaitForLocationChange(tab) {
- tab = tab || gBrowser.selectedTab;
- let selected = gBrowser.selectedTab == tab;
- gBrowser.removeTab(tab);
- if (selected)
- return this.waitForLocationChange();
- return Promise.resolve();
- },
-
- waitForLocationChange: function waitForLocationChange() {
- return new Promise(resolve => {
- Services.obs.addObserver(function obs(subj, topic, data) {
- Services.obs.removeObserver(obs, topic);
- resolve();
- }, "browser-fullZoom:location-change", false);
- });
- },
-
- load: function load(tab, url) {
- return new Promise(resolve => {
- let didLoad = false;
- let didZoom = false;
-
- promiseTabLoadEvent(tab).then(event => {
- didLoad = true;
- if (didZoom)
- resolve();
- }, true);
-
- this.waitForLocationChange().then(function () {
- didZoom = true;
- if (didLoad)
- resolve();
- });
-
- tab.linkedBrowser.loadURI(url);
- });
- },
-
- zoomTest: function zoomTest(tab, val, msg) {
- is(ZoomManager.getZoomForBrowser(tab.linkedBrowser), val, msg);
- },
-
- enlarge: function enlarge() {
- return new Promise(resolve => FullZoom.enlarge(resolve));
- },
-
- reduce: function reduce() {
- return new Promise(resolve => FullZoom.reduce(resolve));
- },
-
- reset: function reset() {
- return FullZoom.reset();
- },
-
- BACK: 0,
- FORWARD: 1,
- navigate: function navigate(direction) {
- return new Promise(resolve => {
- let didPs = false;
- let didZoom = false;
-
- gBrowser.addEventListener("pageshow", function listener(event) {
- gBrowser.removeEventListener("pageshow", listener, true);
- didPs = true;
- if (didZoom)
- resolve();
- }, true);
-
- if (direction == this.BACK)
- gBrowser.goBack();
- else if (direction == this.FORWARD)
- gBrowser.goForward();
-
- this.waitForLocationChange().then(function () {
- didZoom = true;
- if (didPs)
- resolve();
- });
- });
- },
-
- failAndContinue: function failAndContinue(func) {
- return function (err) {
- ok(false, err);
- func();
- };
- },
-};
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url)
-{
- info("Wait tab event: load");
-
- function handle(loadedUrl) {
- if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
- info(`Skipping spurious load event for ${loadedUrl}`);
- return false;
- }
-
- info("Tab event received: load");
- return true;
- }
-
- let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
-
- if (url)
- BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
- return loaded;
-}
-
-/**
- * Returns a Promise that resolves once a new tab has been opened in
- * a xul:tabbrowser.
- *
- * @param aTabBrowser
- * The xul:tabbrowser to monitor for a new tab.
- * @return {Promise}
- * Resolved when the new tab has been opened.
- * @resolves to the TabOpen event that was fired.
- * @rejects Never.
- */
-function waitForNewTabEvent(aTabBrowser) {
- return promiseWaitForEvent(aTabBrowser.tabContainer, "TabOpen");
-}
-
-/**
- * Test the state of the identity box and control center to make
- * sure they are correctly showing the expected mixed content states.
- *
- * @note The checks are done synchronously, but new code should wait on the
- * returned Promise object to ensure the identity panel has closed.
- * Bug 1221114 is filed to fix the existing code.
- *
- * @param tabbrowser
- * @param Object states
- * MUST include the following properties:
- * {
- * activeLoaded: true|false,
- * activeBlocked: true|false,
- * passiveLoaded: true|false,
- * }
- *
- * @return {Promise}
- * @resolves When the operation has finished and the identity panel has closed.
- */
-function assertMixedContentBlockingState(tabbrowser, states = {}) {
- if (!tabbrowser || !("activeLoaded" in states) ||
- !("activeBlocked" in states) || !("passiveLoaded" in states)) {
- throw new Error("assertMixedContentBlockingState requires a browser and a states object");
- }
-
- let {passiveLoaded, activeLoaded, activeBlocked} = states;
- let {gIdentityHandler} = tabbrowser.ownerGlobal;
- let doc = tabbrowser.ownerDocument;
- let identityBox = gIdentityHandler._identityBox;
- let classList = identityBox.classList;
- let connectionIcon = doc.getElementById("connection-icon");
- let connectionIconImage = tabbrowser.ownerGlobal.getComputedStyle(connectionIcon).
- getPropertyValue("list-style-image");
-
- let stateSecure = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_SECURE;
- let stateBroken = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_BROKEN;
- let stateInsecure = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_IS_INSECURE;
- let stateActiveBlocked = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_ACTIVE_CONTENT;
- let stateActiveLoaded = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_LOADED_MIXED_ACTIVE_CONTENT;
- let statePassiveLoaded = gIdentityHandler._state & Ci.nsIWebProgressListener.STATE_LOADED_MIXED_DISPLAY_CONTENT;
-
- is(activeBlocked, !!stateActiveBlocked, "Expected state for activeBlocked matches UI state");
- is(activeLoaded, !!stateActiveLoaded, "Expected state for activeLoaded matches UI state");
- is(passiveLoaded, !!statePassiveLoaded, "Expected state for passiveLoaded matches UI state");
-
- if (stateInsecure) {
- // HTTP request, there should be no MCB classes for the identity box and the non secure icon
- // should always be visible regardless of MCB state.
- ok(classList.contains("unknownIdentity"), "unknownIdentity on HTTP page");
- is_element_hidden(connectionIcon);
-
- ok(!classList.contains("mixedActiveContent"), "No MCB icon on HTTP page");
- ok(!classList.contains("mixedActiveBlocked"), "No MCB icon on HTTP page");
- ok(!classList.contains("mixedDisplayContent"), "No MCB icon on HTTP page");
- ok(!classList.contains("mixedDisplayContentLoadedActiveBlocked"), "No MCB icon on HTTP page");
- } else {
- // Make sure the identity box UI has the correct mixedcontent states and icons
- is(classList.contains("mixedActiveContent"), activeLoaded,
- "identityBox has expected class for activeLoaded");
- is(classList.contains("mixedActiveBlocked"), activeBlocked && !passiveLoaded,
- "identityBox has expected class for activeBlocked && !passiveLoaded");
- is(classList.contains("mixedDisplayContent"), passiveLoaded && !(activeLoaded || activeBlocked),
- "identityBox has expected class for passiveLoaded && !(activeLoaded || activeBlocked)");
- is(classList.contains("mixedDisplayContentLoadedActiveBlocked"), passiveLoaded && activeBlocked,
- "identityBox has expected class for passiveLoaded && activeBlocked");
-
- is_element_visible(connectionIcon);
- if (activeLoaded) {
- is(connectionIconImage, "url(\"chrome://browser/skin/connection-mixed-active-loaded.svg#icon\")",
- "Using active loaded icon");
- }
- if (activeBlocked && !passiveLoaded) {
- is(connectionIconImage, "url(\"chrome://browser/skin/connection-secure.svg\")",
- "Using active blocked icon");
- }
- if (passiveLoaded && !(activeLoaded || activeBlocked)) {
- is(connectionIconImage, "url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
- "Using passive loaded icon");
- }
- if (passiveLoaded && activeBlocked) {
- is(connectionIconImage, "url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
- "Using active blocked and passive loaded icon");
- }
- }
-
- // Make sure the identity popup has the correct mixedcontent states
- gIdentityHandler._identityBox.click();
- let popupAttr = doc.getElementById("identity-popup").getAttribute("mixedcontent");
- let bodyAttr = doc.getElementById("identity-popup-securityView-body").getAttribute("mixedcontent");
-
- is(popupAttr.includes("active-loaded"), activeLoaded,
- "identity-popup has expected attr for activeLoaded");
- is(bodyAttr.includes("active-loaded"), activeLoaded,
- "securityView-body has expected attr for activeLoaded");
-
- is(popupAttr.includes("active-blocked"), activeBlocked,
- "identity-popup has expected attr for activeBlocked");
- is(bodyAttr.includes("active-blocked"), activeBlocked,
- "securityView-body has expected attr for activeBlocked");
-
- is(popupAttr.includes("passive-loaded"), passiveLoaded,
- "identity-popup has expected attr for passiveLoaded");
- is(bodyAttr.includes("passive-loaded"), passiveLoaded,
- "securityView-body has expected attr for passiveLoaded");
-
- // Make sure the correct icon is visible in the Control Center.
- // This logic is controlled with CSS, so this helps prevent regressions there.
- let securityView = doc.getElementById("identity-popup-securityView");
- let securityViewBG = tabbrowser.ownerGlobal.getComputedStyle(securityView).
- getPropertyValue("background-image");
- let securityContentBG = tabbrowser.ownerGlobal.getComputedStyle(securityView).
- getPropertyValue("background-image");
-
- if (stateInsecure) {
- is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/conn-not-secure.svg\")",
- "CC using 'not secure' icon");
- is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/conn-not-secure.svg\")",
- "CC using 'not secure' icon");
- }
-
- if (stateSecure) {
- is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-secure\")",
- "CC using secure icon");
- is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-secure\")",
- "CC using secure icon");
- }
-
- if (stateBroken) {
- if (activeLoaded) {
- is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/mcb-disabled.svg\")",
- "CC using active loaded icon");
- is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/mcb-disabled.svg\")",
- "CC using active loaded icon");
- } else if (activeBlocked || passiveLoaded) {
- is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-degraded\")",
- "CC using degraded icon");
- is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-degraded\")",
- "CC using degraded icon");
- } else {
- // There is a case here with weak ciphers, but no bc tests are handling this yet.
- is(securityViewBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-degraded\")",
- "CC using degraded icon");
- is(securityContentBG, "url(\"chrome://browser/skin/controlcenter/connection.svg#connection-degraded\")",
- "CC using degraded icon");
- }
- }
-
- if (activeLoaded || activeBlocked || passiveLoaded) {
- doc.getElementById("identity-popup-security-expander").click();
- is(Array.filter(doc.querySelectorAll("[observes=identity-popup-mcb-learn-more]"),
- element => !is_hidden(element)).length, 1,
- "The 'Learn more' link should be visible once.");
- }
-
- gIdentityHandler._identityPopup.hidden = true;
-
- // Wait for the panel to be closed before continuing. The promisePopupHidden
- // function cannot be used because it's unreliable unless promisePopupShown is
- // also called before closing the panel. This cannot be done until all callers
- // are made asynchronous (bug 1221114).
- return new Promise(resolve => executeSoon(resolve));
-}
-
-function is_hidden(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
- if (style.display == "-moz-popup")
- return ["hiding", "closed"].indexOf(element.state) != -1;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_hidden(element.parentNode);
-
- return false;
-}
-
-function is_visible(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return false;
- if (style.visibility != "visible")
- return false;
- if (style.display == "-moz-popup" && element.state != "open")
- return false;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_visible(element.parentNode);
-
- return true;
-}
-
-function is_element_visible(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_visible(element), msg || "Element should be visible");
-}
-
-function is_element_hidden(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_hidden(element), msg || "Element should be hidden");
-}
-
-function promisePopupEvent(popup, eventSuffix) {
- let endState = {shown: "open", hidden: "closed"}[eventSuffix];
-
- if (popup.state == endState)
- return Promise.resolve();
-
- let eventType = "popup" + eventSuffix;
- let deferred = Promise.defer();
- popup.addEventListener(eventType, function onPopupShown(event) {
- popup.removeEventListener(eventType, onPopupShown);
- deferred.resolve();
- });
-
- return deferred.promise;
-}
-
-function promisePopupShown(popup) {
- return promisePopupEvent(popup, "shown");
-}
-
-function promisePopupHidden(popup) {
- return promisePopupEvent(popup, "hidden");
-}
-
-function promiseNotificationShown(notification) {
- let win = notification.browser.ownerGlobal;
- if (win.PopupNotifications.panel.state == "open") {
- return Promise.resolve();
- }
- let panelPromise = promisePopupShown(win.PopupNotifications.panel);
- notification.reshow();
- return panelPromise;
-}
-
-/**
- * Allows waiting for an observer notification once.
- *
- * @param aTopic
- * Notification topic to observe.
- *
- * @return {Promise}
- * @resolves An object with subject and data properties from the observed
- * notification.
- * @rejects Never.
- */
-function promiseTopicObserved(aTopic)
-{
- return new Promise((resolve) => {
- Services.obs.addObserver(
- function PTO_observe(aSubject, aTopic2, aData) {
- Services.obs.removeObserver(PTO_observe, aTopic2);
- resolve({subject: aSubject, data: aData});
- }, aTopic, false);
- });
-}
-
-function promiseNewSearchEngine(basename) {
- return new Promise((resolve, reject) => {
- info("Waiting for engine to be added: " + basename);
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- registerCleanupFunction(() => Services.search.removeEngine(engine));
- resolve(engine);
- },
- onError: function (errCode) {
- Assert.ok(false, "addEngine failed with error code " + errCode);
- reject();
- },
- });
- });
-}
-
-// Compares the security state of the page with what is expected
-function isSecurityState(expectedState) {
- let ui = gTestBrowser.securityUI;
- if (!ui) {
- ok(false, "No security UI to get the security state");
- return;
- }
-
- const wpl = Components.interfaces.nsIWebProgressListener;
-
- // determine the security state
- let isSecure = ui.state & wpl.STATE_IS_SECURE;
- let isBroken = ui.state & wpl.STATE_IS_BROKEN;
- let isInsecure = ui.state & wpl.STATE_IS_INSECURE;
-
- let actualState;
- if (isSecure && !(isBroken || isInsecure)) {
- actualState = "secure";
- } else if (isBroken && !(isSecure || isInsecure)) {
- actualState = "broken";
- } else if (isInsecure && !(isSecure || isBroken)) {
- actualState = "insecure";
- } else {
- actualState = "unknown";
- }
-
- is(expectedState, actualState, "Expected state " + expectedState + " and the actual state is " + actualState + ".");
-}
-
-/**
- * Resolves when a bookmark with the given uri is added.
- */
-function promiseOnBookmarkItemAdded(aExpectedURI) {
- return new Promise((resolve, reject) => {
- let bookmarksObserver = {
- onItemAdded: function (aItemId, aFolderId, aIndex, aItemType, aURI) {
- info("Added a bookmark to " + aURI.spec);
- PlacesUtils.bookmarks.removeObserver(bookmarksObserver);
- if (aURI.equals(aExpectedURI)) {
- resolve();
- }
- else {
- reject(new Error("Added an unexpected bookmark"));
- }
- },
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemRemoved: function () {},
- onItemChanged: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- ])
- };
- info("Waiting for a bookmark to be added");
- PlacesUtils.bookmarks.addObserver(bookmarksObserver, false);
- });
-}
-
-function promiseErrorPageLoaded(browser) {
- return new Promise(resolve => {
- browser.addEventListener("DOMContentLoaded", function onLoad() {
- browser.removeEventListener("DOMContentLoaded", onLoad, false, true);
- resolve();
- }, false, true);
- });
-}
-
-function* loadBadCertPage(url) {
- const EXCEPTION_DIALOG_URI = "chrome://pippki/content/exceptionDialog.xul";
- let exceptionDialogResolved = new Promise(function(resolve) {
- // When the certificate exception dialog has opened, click the button to add
- // an exception.
- let certExceptionDialogObserver = {
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "cert-exception-ui-ready") {
- Services.obs.removeObserver(this, "cert-exception-ui-ready");
- let certExceptionDialog = getCertExceptionDialog(EXCEPTION_DIALOG_URI);
- ok(certExceptionDialog, "found exception dialog");
- executeSoon(function() {
- certExceptionDialog.documentElement.getButton("extra1").click();
- resolve();
- });
- }
- }
- };
-
- Services.obs.addObserver(certExceptionDialogObserver,
- "cert-exception-ui-ready", false);
- });
-
- let loaded = BrowserTestUtils.waitForErrorPage(gBrowser.selectedBrowser);
- yield BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url);
- yield loaded;
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
- content.document.getElementById("exceptionDialogButton").click();
- });
- yield exceptionDialogResolved;
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
-}
-
-// Utility function to get a handle on the certificate exception dialog.
-// Modified from toolkit/components/passwordmgr/test/prompt_common.js
-function getCertExceptionDialog(aLocation) {
- let enumerator = Services.wm.getXULWindowEnumerator(null);
-
- while (enumerator.hasMoreElements()) {
- let win = enumerator.getNext();
- let windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell;
-
- let containedDocShells = windowDocShell.getDocShellEnumerator(
- Ci.nsIDocShellTreeItem.typeChrome,
- Ci.nsIDocShell.ENUMERATE_FORWARDS);
- while (containedDocShells.hasMoreElements()) {
- // Get the corresponding document for this docshell
- let childDocShell = containedDocShells.getNext();
- let childDoc = childDocShell.QueryInterface(Ci.nsIDocShell)
- .contentViewer
- .DOMDocument;
-
- if (childDoc.location.href == aLocation) {
- return childDoc;
- }
- }
- }
- return undefined;
-}
-
-function setupRemoteClientsFixture(fixture) {
- let oldRemoteClientsGetter =
- Object.getOwnPropertyDescriptor(gFxAccounts, "remoteClients").get;
-
- Object.defineProperty(gFxAccounts, "remoteClients", {
- get: function() { return fixture; }
- });
- return oldRemoteClientsGetter;
-}
-
-function restoreRemoteClients(getter) {
- Object.defineProperty(gFxAccounts, "remoteClients", {
- get: getter
- });
-}
-
-function* openMenuItemSubmenu(id) {
- let menuPopup = document.getElementById(id).menupopup;
- let menuPopupPromise = BrowserTestUtils.waitForEvent(menuPopup, "popupshown");
- menuPopup.showPopup();
- yield menuPopupPromise;
-}
diff --git a/browser/base/content/test/general/head_plain.js b/browser/base/content/test/general/head_plain.js
deleted file mode 100644
index 3796c7d2b..000000000
--- a/browser/base/content/test/general/head_plain.js
+++ /dev/null
@@ -1,27 +0,0 @@
-
-function getTestPlugin(pluginName) {
- var ph = SpecialPowers.Cc["@mozilla.org/plugin/host;1"]
- .getService(SpecialPowers.Ci.nsIPluginHost);
- var tags = ph.getPluginTags();
- var name = pluginName || "Test Plug-in";
- for (var tag of tags) {
- if (tag.name == name) {
- return tag;
- }
- }
-
- ok(false, "Could not find plugin tag with plugin name '" + name + "'");
- return null;
-}
-
-// call this to set the test plugin(s) initially expected enabled state.
-// it will automatically be reset to it's previous value after the test
-// ends
-function setTestPluginEnabledState(newEnabledState, pluginName) {
- var plugin = getTestPlugin(pluginName);
- var oldEnabledState = plugin.enabledState;
- plugin.enabledState = newEnabledState;
- SimpleTest.registerCleanupFunction(function() {
- getTestPlugin(pluginName).enabledState = oldEnabledState;
- });
-}
diff --git a/browser/base/content/test/general/healthreport_pingData.js b/browser/base/content/test/general/healthreport_pingData.js
deleted file mode 100644
index 1737baba1..000000000
--- a/browser/base/content/test/general/healthreport_pingData.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var TEST_PINGS = [
- {
- type: "test-telemetryArchive-1",
- payload: { foo: "bar" },
- date: new Date(2010, 1, 1, 10, 0, 0),
- },
- {
- type: "test-telemetryArchive-2",
- payload: { x: { y: "z"} },
- date: new Date(2010, 1, 1, 11, 0, 0),
- },
- {
- type: "test-telemetryArchive-3",
- payload: { moo: "meh" },
- date: new Date(2010, 1, 1, 12, 0, 0),
- },
-];
diff --git a/browser/base/content/test/general/healthreport_testRemoteCommands.html b/browser/base/content/test/general/healthreport_testRemoteCommands.html
deleted file mode 100644
index 7978914f2..000000000
--- a/browser/base/content/test/general/healthreport_testRemoteCommands.html
+++ /dev/null
@@ -1,243 +0,0 @@
-<html>
- <head>
- <meta charset="utf-8">
-<script type="application/javascript;version=1.7"
- src="healthreport_pingData.js">
-</script>
-<script type="application/javascript;version=1.7">
-
-function init() {
- window.addEventListener("message", doTest, false);
- doTest();
-}
-
-function checkSubmissionValue(payload, expectedValue) {
- return payload.enabled == expectedValue;
-}
-
-function isArray(arg) {
- return Object.prototype.toString.call(arg) === '[object Array]';
-}
-
-function writeDiagnostic(text) {
- let node = document.createTextNode(text);
- let br = document.createElement("br");
- document.body.appendChild(node);
- document.body.appendChild(br);
-}
-
-function validateCurrentTelemetryEnvironment(data) {
- // Simple check for now: check that the received object has the expected
- // top-level properties.
- const expectedKeys = ["profile", "settings", "system", "build", "partner", "addons"];
- return expectedKeys.every(key => (key in data));
-}
-
-function validateCurrentTelemetryPingData(ping) {
- // Simple check for now: check that the received object has the expected
- // top-level properties and that the type and reason match.
- const expectedKeys = ["environment", "clientId", "payload", "application",
- "version", "type", "id"];
- return expectedKeys.every(key => (key in ping)) &&
- (ping.type == "main") &&
- ("info" in ping.payload) &&
- ("reason" in ping.payload.info) &&
- (ping.payload.info.reason == "gather-subsession-payload");
-}
-
-function validateTelemetryPingList(list) {
- if (!isArray(list)) {
- console.log("Telemetry ping list is not an array.");
- return false;
- }
-
- // Telemetry may generate other pings (e.g. "deletion" pings), so filter those
- // out.
- const TEST_TYPES_REGEX = /^test-telemetryArchive/;
- list = list.filter(p => TEST_TYPES_REGEX.test(p.type));
-
- if (list.length != TEST_PINGS.length) {
- console.log("Telemetry ping length is not correct.");
- return false;
- }
-
- let valid = true;
- for (let i=0; i<list.length; ++i) {
- let received = list[i];
- let expected = TEST_PINGS[i];
- if (received.type != expected.type ||
- received.timestampCreated != expected.date.getTime()) {
- writeDiagnostic("Telemetry ping " + i + " does not match.");
- writeDiagnostic("Expected: " + JSON.stringify(expected));
- writeDiagnostic("Received: " + JSON.stringify(received));
- valid = false;
- } else {
- writeDiagnostic("Telemetry ping " + i + " matches.");
- }
- }
-
- return true;
-}
-
-function validateTelemetryPingData(expected, received) {
- const receivedDate = new Date(received.creationDate);
- if (received.id != expected.id ||
- received.type != expected.type ||
- receivedDate.getTime() != expected.date.getTime()) {
- writeDiagnostic("Telemetry ping data for " + expected.id + " doesn't match.");
- writeDiagnostic("Expected: " + JSON.stringify(expected));
- writeDiagnostic("Received: " + JSON.stringify(received));
- return false;
- }
-
- writeDiagnostic("Telemetry ping data for " + expected.id + " matched.");
- return true;
-}
-
-var tests = [
-{
- info: "Checking initial value is enabled",
- event: "RequestCurrentPrefs",
- payloadType: "prefs",
- validateResponse: function(payload) {
- return checkSubmissionValue(payload, true);
- },
-},
-{
- info: "Verifying disabling works",
- event: "DisableDataSubmission",
- payloadType: "prefs",
- validateResponse: function(payload) {
- return checkSubmissionValue(payload, false);
- },
-},
-{
- info: "Verifying we're still disabled",
- event: "RequestCurrentPrefs",
- payloadType: "prefs",
- validateResponse: function(payload) {
- return checkSubmissionValue(payload, false);
- },
-},
-{
- info: "Verifying that we can get the current ping data while submission is disabled",
- event: "RequestCurrentPingData",
- payloadType: "telemetry-current-ping-data",
- validateResponse: function(payload) {
- return validateCurrentTelemetryPingData(payload);
- },
-},
-{
- info: "Verifying enabling works",
- event: "EnableDataSubmission",
- payloadType: "prefs",
- validateResponse: function(payload) {
- return checkSubmissionValue(payload, true);
- },
-},
-{
- info: "Verifying we're still re-enabled",
- event: "RequestCurrentPrefs",
- payloadType: "prefs",
- validateResponse: function(payload) {
- return checkSubmissionValue(payload, true);
- },
-},
-{
- info: "Verifying that we can get the current Telemetry environment data",
- event: "RequestCurrentEnvironment",
- payloadType: "telemetry-current-environment-data",
- validateResponse: function(payload) {
- return validateCurrentTelemetryEnvironment(payload);
- },
-},
-{
- info: "Verifying that we can get the current Telemetry ping data",
- event: "RequestCurrentPingData",
- payloadType: "telemetry-current-ping-data",
- validateResponse: function(payload) {
- return validateCurrentTelemetryPingData(payload);
- },
-},
-{
- info: "Verifying that we get the proper Telemetry ping list",
- event: "RequestTelemetryPingList",
- payloadType: "telemetry-ping-list",
- validateResponse: function(payload) {
- // Validate the ping list
- if (!validateTelemetryPingList(payload)) {
- return false;
- }
-
- // Now that we received the ping ids, set up additional test tasks
- // that check loading the individual pings.
- for (let i=0; i<TEST_PINGS.length; ++i) {
- TEST_PINGS[i].id = payload[i].id;
- tests.push({
- info: "Verifying that we can get the proper Telemetry ping data #" + (i + 1),
- event: "RequestTelemetryPingData",
- eventData: { id: TEST_PINGS[i].id },
- payloadType: "telemetry-ping-data",
- validateResponse: function(payload) {
- return validateTelemetryPingData(TEST_PINGS[i], payload.pingData);
- },
- });
- }
-
- return true;
- },
-},
-];
-
-var currentTest = -1;
-function doTest(evt) {
- if (evt) {
- if (currentTest < 0 || !evt.data.content)
- return; // not yet testing
-
- var test = tests[currentTest];
- if (evt.data.type != test.payloadType)
- return; // skip unrequested events
-
- var error = JSON.stringify(evt.data.content);
- var pass = false;
- try {
- pass = test.validateResponse(evt.data.content)
- } catch (e) {}
- reportResult(test.info, pass, error);
- }
- // start the next test if there are any left
- if (tests[++currentTest])
- sendToBrowser(tests[currentTest].event, tests[currentTest].eventData);
- else
- reportFinished();
-}
-
-function reportResult(info, pass, error) {
- var data = {type: "testResult", info: info, pass: pass, error: error};
- var event = new CustomEvent("FirefoxHealthReportTestResponse", {detail: {data: data}, bubbles: true});
- document.dispatchEvent(event);
-}
-
-function reportFinished(cmd) {
- var data = {type: "testsComplete", count: tests.length};
- var event = new CustomEvent("FirefoxHealthReportTestResponse", {detail: {data: data}, bubbles: true});
- document.dispatchEvent(event);
-}
-
-function sendToBrowser(type, eventData) {
- eventData = eventData || {};
- let detail = {command: type};
- for (let key of Object.keys(eventData)) {
- detail[key] = eventData[key];
- }
-
- var event = new CustomEvent("RemoteHealthReportCommand", {detail: detail, bubbles: true});
- document.dispatchEvent(event);
-}
-
-</script>
- </head>
- <body onload="init()">
- </body>
-</html>
diff --git a/browser/base/content/test/general/insecure_opener.html b/browser/base/content/test/general/insecure_opener.html
deleted file mode 100644
index 26ed014f6..000000000
--- a/browser/base/content/test/general/insecure_opener.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html dir="ltr" xml:lang="en-US" lang="en-US">
- <head>
- <meta charset="utf8">
- </head>
- <body>
- <a id="link" target="_blank" href="https://example.com/browser/toolkit/components/passwordmgr/test/browser/form_basic.html">Click me, I'm "secure".</a>
- </body>
-</html>
diff --git a/browser/base/content/test/general/mochitest.ini b/browser/base/content/test/general/mochitest.ini
deleted file mode 100644
index a07a01b87..000000000
--- a/browser/base/content/test/general/mochitest.ini
+++ /dev/null
@@ -1,27 +0,0 @@
-[DEFAULT]
-support-files =
- audio.ogg
- bug364677-data.xml
- bug364677-data.xml^headers^
- bug395533-data.txt
- contextmenu_common.js
- ctxmenu-image.png
- head_plain.js
- offlineByDefault.js
- offlineChild.cacheManifest
- offlineChild.cacheManifest^headers^
- offlineChild.html
- offlineChild2.cacheManifest
- offlineChild2.cacheManifest^headers^
- offlineChild2.html
- offlineEvent.cacheManifest
- offlineEvent.cacheManifest^headers^
- offlineEvent.html
- subtst_contextmenu.html
- video.ogg
- !/image/test/mochitest/blue.png
-
-[test_bug364677.html]
-[test_bug395533.html]
-[test_offlineNotification.html]
-skip-if = e10s # Bug 1257785
diff --git a/browser/base/content/test/general/moz.png b/browser/base/content/test/general/moz.png
deleted file mode 100644
index 769c63634..000000000
--- a/browser/base/content/test/general/moz.png
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/navigating_window_with_download.html b/browser/base/content/test/general/navigating_window_with_download.html
deleted file mode 100644
index 6b0918941..000000000
--- a/browser/base/content/test/general/navigating_window_with_download.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head><title>This window will navigate while you're downloading something</title></head>
- <body>
- <iframe src="http://mochi.test:8888/browser/browser/base/content/test/general/unknownContentType_file.pif"></iframe>
- </body>
-</html>
diff --git a/browser/base/content/test/general/offlineByDefault.js b/browser/base/content/test/general/offlineByDefault.js
deleted file mode 100644
index 72f7e52a0..000000000
--- a/browser/base/content/test/general/offlineByDefault.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var offlineByDefault = {
- defaultValue: false,
- prefBranch: SpecialPowers.Cc["@mozilla.org/preferences-service;1"].getService(SpecialPowers.Ci.nsIPrefBranch),
- set: function(allow) {
- try {
- this.defaultValue = this.prefBranch.getBoolPref("offline-apps.allow_by_default");
- } catch (e) {
- this.defaultValue = false
- }
- this.prefBranch.setBoolPref("offline-apps.allow_by_default", allow);
- },
- reset: function() {
- this.prefBranch.setBoolPref("offline-apps.allow_by_default", this.defaultValue);
- }
-}
-
-offlineByDefault.set(false);
diff --git a/browser/base/content/test/general/offlineChild.cacheManifest b/browser/base/content/test/general/offlineChild.cacheManifest
deleted file mode 100644
index 091fe7194..000000000
--- a/browser/base/content/test/general/offlineChild.cacheManifest
+++ /dev/null
@@ -1,2 +0,0 @@
-CACHE MANIFEST
-offlineChild.html
diff --git a/browser/base/content/test/general/offlineChild.cacheManifest^headers^ b/browser/base/content/test/general/offlineChild.cacheManifest^headers^
deleted file mode 100644
index 257f2eb60..000000000
--- a/browser/base/content/test/general/offlineChild.cacheManifest^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: text/cache-manifest
diff --git a/browser/base/content/test/general/offlineChild.html b/browser/base/content/test/general/offlineChild.html
deleted file mode 100644
index 43f225b3b..000000000
--- a/browser/base/content/test/general/offlineChild.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html manifest="offlineChild.cacheManifest">
-<head>
-<title></title>
-<script type="text/javascript">
-
-function finish(success) {
- window.parent.postMessage(success ? "success" : "failure", "*");
-}
-
-applicationCache.oncached = function() { finish(true); }
-applicationCache.onnoupdate = function() { finish(true); }
-applicationCache.onerror = function() { finish(false); }
-
-</script>
-</head>
-
-<body>
-<h1>Child</h1>
-</body>
-</html>
diff --git a/browser/base/content/test/general/offlineChild2.cacheManifest b/browser/base/content/test/general/offlineChild2.cacheManifest
deleted file mode 100644
index 19efe54fe..000000000
--- a/browser/base/content/test/general/offlineChild2.cacheManifest
+++ /dev/null
@@ -1,2 +0,0 @@
-CACHE MANIFEST
-offlineChild2.html
diff --git a/browser/base/content/test/general/offlineChild2.cacheManifest^headers^ b/browser/base/content/test/general/offlineChild2.cacheManifest^headers^
deleted file mode 100644
index 257f2eb60..000000000
--- a/browser/base/content/test/general/offlineChild2.cacheManifest^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: text/cache-manifest
diff --git a/browser/base/content/test/general/offlineChild2.html b/browser/base/content/test/general/offlineChild2.html
deleted file mode 100644
index ac762e759..000000000
--- a/browser/base/content/test/general/offlineChild2.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html manifest="offlineChild2.cacheManifest">
-<head>
-<title></title>
-<script type="text/javascript">
-
-function finish(success) {
- window.parent.postMessage(success ? "success" : "failure", "*");
-}
-
-applicationCache.oncached = function() { finish(true); }
-applicationCache.onnoupdate = function() { finish(true); }
-applicationCache.onerror = function() { finish(false); }
-
-</script>
-</head>
-
-<body>
-<h1>Child</h1>
-</body>
-</html>
diff --git a/browser/base/content/test/general/offlineEvent.cacheManifest b/browser/base/content/test/general/offlineEvent.cacheManifest
deleted file mode 100644
index 091fe7194..000000000
--- a/browser/base/content/test/general/offlineEvent.cacheManifest
+++ /dev/null
@@ -1,2 +0,0 @@
-CACHE MANIFEST
-offlineChild.html
diff --git a/browser/base/content/test/general/offlineEvent.cacheManifest^headers^ b/browser/base/content/test/general/offlineEvent.cacheManifest^headers^
deleted file mode 100644
index 257f2eb60..000000000
--- a/browser/base/content/test/general/offlineEvent.cacheManifest^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: text/cache-manifest
diff --git a/browser/base/content/test/general/offlineEvent.html b/browser/base/content/test/general/offlineEvent.html
deleted file mode 100644
index f6e2494e2..000000000
--- a/browser/base/content/test/general/offlineEvent.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html manifest="offlineEvent.cacheManifest">
-<head>
-<title></title>
-</head>
-
-<body>
-<h1>Child</h1>
-</body>
-</html>
diff --git a/browser/base/content/test/general/offlineQuotaNotification.cacheManifest b/browser/base/content/test/general/offlineQuotaNotification.cacheManifest
deleted file mode 100644
index 2e210abd2..000000000
--- a/browser/base/content/test/general/offlineQuotaNotification.cacheManifest
+++ /dev/null
@@ -1,7 +0,0 @@
-CACHE MANIFEST
-# Any copyright is dedicated to the Public Domain.
-# http://creativecommons.org/publicdomain/zero/1.0/
-
-# store a "large" file so an "over quota warning" will be issued - any file
-# larger than 1kb and in '_BROWSER_FILES' should be right...
-title_test.svg
diff --git a/browser/base/content/test/general/offlineQuotaNotification.html b/browser/base/content/test/general/offlineQuotaNotification.html
deleted file mode 100644
index b1b91bf9e..000000000
--- a/browser/base/content/test/general/offlineQuotaNotification.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html manifest="offlineQuotaNotification.cacheManifest">
-<head>
- <meta charset="utf-8">
- <title>Test offline app quota notification</title>
- <!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-</head>
-</html>
diff --git a/browser/base/content/test/general/page_style_sample.html b/browser/base/content/test/general/page_style_sample.html
deleted file mode 100644
index 54cbaa9e6..000000000
--- a/browser/base/content/test/general/page_style_sample.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<html>
- <head>
- <title>Test for page style menu</title>
- <!-- data-state values:
- 0: should not appear in the page style menu
- 0-todo: should not appear in the page style menu, but does
- 1: should appear in the page style menu
- 2: should appear in the page style menu as the selected stylesheet -->
- <link data-state="1" href="404.css" title="1" rel="alternate stylesheet">
- <link data-state="0" title="2" rel="alternate stylesheet">
- <link data-state="0" href="404.css" rel="alternate stylesheet">
- <link data-state="0" href="404.css" title="" rel="alternate stylesheet">
- <link data-state="1" href="404.css" title="3" rel="stylesheet alternate">
- <link data-state="1" href="404.css" title="4" rel=" alternate stylesheet ">
- <link data-state="1" href="404.css" title="5" rel="alternate stylesheet">
- <link data-state="2" href="404.css" title="6" rel="stylesheet">
- <link data-state="1" href="404.css" title="7" rel="foo stylesheet">
- <link data-state="0" href="404.css" title="8" rel="alternate">
- <link data-state="1" href="404.css" title="9" rel="alternate STYLEsheet">
- <link data-state="1" href="404.css" title="10" rel="alternate stylesheet" media="">
- <link data-state="1" href="404.css" title="11" rel="alternate stylesheet" media="all">
- <link data-state="1" href="404.css" title="12" rel="alternate stylesheet" media="ALL ">
- <link data-state="1" href="404.css" title="13" rel="alternate stylesheet" media="screen">
- <link data-state="1" href="404.css" title="14" rel="alternate stylesheet" media=" Screen">
- <link data-state="0" href="404.css" title="15" rel="alternate stylesheet" media="screen foo">
- <link data-state="0" href="404.css" title="16" rel="alternate stylesheet" media="all screen">
- <link data-state="0" href="404.css" title="17" rel="alternate stylesheet" media="foo bar">
- <link data-state="1" href="404.css" title="18" rel="alternate stylesheet" media="all,screen">
- <link data-state="1" href="404.css" title="19" rel="alternate stylesheet" media="all, screen">
- <link data-state="0" href="404.css" title="20" rel="alternate stylesheet" media="all screen">
- <link data-state="0" href="404.css" title="21" rel="alternate stylesheet" media="foo">
- <link data-state="0" href="404.css" title="22" rel="alternate stylesheet" media="allscreen">
- <link data-state="0" href="404.css" title="23" rel="alternate stylesheet" media="_all">
- <link data-state="0" href="404.css" title="24" rel="alternate stylesheet" media="not screen">
- <link data-state="1" href="404.css" title="25" rel="alternate stylesheet" media="only screen">
- <link data-state="1" href="404.css" title="26" rel="alternate stylesheet" media="screen and (min-device-width: 1px)">
- <link data-state="0" href="404.css" title="27" rel="alternate stylesheet" media="screen and (max-device-width: 1px)">
- <style data-state="1" title="28">/* some more styles */</style>
- </head>
- <body></body>
-</html>
diff --git a/browser/base/content/test/general/parsingTestHelpers.jsm b/browser/base/content/test/general/parsingTestHelpers.jsm
deleted file mode 100644
index 69c764483..000000000
--- a/browser/base/content/test/general/parsingTestHelpers.jsm
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["generateURIsFromDirTree"];
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-/* Shorthand constructors to construct an nsI(Local)File and zip reader: */
-const LocalFile = new Components.Constructor("@mozilla.org/file/local;1", Ci.nsIFile, "initWithPath");
-const ZipReader = new Components.Constructor("@mozilla.org/libjar/zip-reader;1", "nsIZipReader", "open");
-
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/osfile.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-
-
-/**
- * Returns a promise that is resolved with a list of files that have one of the
- * extensions passed, represented by their nsIURI objects, which exist inside
- * the directory passed.
- *
- * @param dir the directory which to scan for files (nsIFile)
- * @param extensions the extensions of files we're interested in (Array).
- */
-function generateURIsFromDirTree(dir, extensions) {
- if (!Array.isArray(extensions)) {
- extensions = [extensions];
- }
- let dirQueue = [dir.path];
- return Task.spawn(function*() {
- let rv = [];
- while (dirQueue.length) {
- let nextDir = dirQueue.shift();
- let {subdirs, files} = yield iterateOverPath(nextDir, extensions);
- dirQueue.push(...subdirs);
- rv.push(...files);
- }
- return rv;
- });
-}
-
-/**
- * Uses OS.File.DirectoryIterator to asynchronously iterate over a directory.
- * It returns a promise that is resolved with an object with two properties:
- * - files: an array of nsIURIs corresponding to files that match the extensions passed
- * - subdirs: an array of paths for subdirectories we need to recurse into
- * (handled by generateURIsFromDirTree above)
- *
- * @param path the path to check (string)
- * @param extensions the file extensions we're interested in.
- */
-function iterateOverPath(path, extensions) {
- let iterator = new OS.File.DirectoryIterator(path);
- let parentDir = new LocalFile(path);
- let subdirs = [];
- let files = [];
-
- let pathEntryIterator = (entry) => {
- if (entry.isDir) {
- subdirs.push(entry.path);
- } else if (extensions.some((extension) => entry.name.endsWith(extension))) {
- let file = parentDir.clone();
- file.append(entry.name);
- // the build system might leave dead symlinks hanging around, which are
- // returned as part of the directory iterator, but don't actually exist:
- if (file.exists()) {
- let uriSpec = getURLForFile(file);
- files.push(Services.io.newURI(uriSpec, null, null));
- }
- } else if (entry.name.endsWith(".ja") || entry.name.endsWith(".jar") ||
- entry.name.endsWith(".zip") || entry.name.endsWith(".xpi")) {
- let file = parentDir.clone();
- file.append(entry.name);
- for (let extension of extensions) {
- let jarEntryIterator = generateEntriesFromJarFile(file, extension);
- files.push(...jarEntryIterator);
- }
- }
- };
-
- return new Promise((resolve, reject) => {
- Task.spawn(function* () {
- try {
- // Iterate through the directory
- yield iterator.forEach(pathEntryIterator);
- resolve({files: files, subdirs: subdirs});
- } catch (ex) {
- reject(ex);
- } finally {
- iterator.close();
- }
- });
- });
-}
-
-/* Helper function to generate a URI spec (NB: not an nsIURI yet!)
- * given an nsIFile object */
-function getURLForFile(file) {
- let fileHandler = Services.io.getProtocolHandler("file");
- fileHandler = fileHandler.QueryInterface(Ci.nsIFileProtocolHandler);
- return fileHandler.getURLSpecFromActualFile(file);
-}
-
-/**
- * A generator that generates nsIURIs for particular files found in jar files
- * like omni.ja.
- *
- * @param jarFile an nsIFile object for the jar file that needs checking.
- * @param extension the extension we're interested in.
- */
-function* generateEntriesFromJarFile(jarFile, extension) {
- let zr = new ZipReader(jarFile);
- let entryEnumerator = zr.findEntries("*" + extension + "$");
-
- const kURIStart = getURLForFile(jarFile);
- while (entryEnumerator.hasMore()) {
- let entry = entryEnumerator.getNext();
- // Ignore the JS cache which is stored in omni.ja
- if (entry.startsWith("jsloader") || entry.startsWith("jssubloader")) {
- continue;
- }
- let entryURISpec = "jar:" + kURIStart + "!/" + entry;
- yield Services.io.newURI(entryURISpec, null, null);
- }
- zr.close();
-}
-
-
diff --git a/browser/base/content/test/general/permissions.html b/browser/base/content/test/general/permissions.html
deleted file mode 100644
index 46436a006..000000000
--- a/browser/base/content/test/general/permissions.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<!-- 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/. -->
-<html dir="ltr" xml:lang="en-US" lang="en-US">
- <head>
- <meta charset="utf8">
- </head>
- <body>
- <!-- This page could eventually request permissions from content
- and make sure that chrome responds appropriately -->
- <button id="geo" onclick="navigator.geolocation.getCurrentPosition(() => {})">Geolocation</button>
- </body>
-</html>
diff --git a/browser/base/content/test/general/pinning_headers.sjs b/browser/base/content/test/general/pinning_headers.sjs
deleted file mode 100644
index 51496183a..000000000
--- a/browser/base/content/test/general/pinning_headers.sjs
+++ /dev/null
@@ -1,23 +0,0 @@
-const INVALIDPIN1 = "pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\";";
-const INVALIDPIN2 = "pin-sha256=\"AAAAAAAAAAAAAAAAAAAAAAAAAj0e1Md7GkYYkVoZWmM=\";";
-const VALIDPIN = "pin-sha256=\"hXweb81C3HnmM2Ai1dnUzFba40UJMhuu8qZmvN/6WWc=\";";
-
-function handleRequest(request, response)
-{
- // avoid confusing cache behaviors
- response.setHeader("Cache-Control", "no-cache", false);
-
- response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
- switch (request.queryString) {
- case "zeromaxagevalid":
- response.setHeader("Public-Key-Pins", "max-age=0;" + VALIDPIN +
- INVALIDPIN2 + "includeSubdomains");
- break;
- case "valid":
- default:
- response.setHeader("Public-Key-Pins", "max-age=50000;" + VALIDPIN +
- INVALIDPIN2 + "includeSubdomains");
- }
-
- response.write("Hello world!" + request.host);
-}
diff --git a/browser/base/content/test/general/print_postdata.sjs b/browser/base/content/test/general/print_postdata.sjs
deleted file mode 100644
index 4175a2480..000000000
--- a/browser/base/content/test/general/print_postdata.sjs
+++ /dev/null
@@ -1,22 +0,0 @@
-const CC = Components.Constructor;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(request, response) {
- response.setHeader("Content-Type", "text/plain", false);
- if (request.method == "GET") {
- response.write(request.queryString);
- } else {
- var body = new BinaryInputStream(request.bodyInputStream);
-
- var avail;
- var bytes = [];
-
- while ((avail = body.available()) > 0)
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
-
- var data = String.fromCharCode.apply(null, bytes);
- response.bodyOutputStream.write(data, data.length);
- }
-}
diff --git a/browser/base/content/test/general/refresh_header.sjs b/browser/base/content/test/general/refresh_header.sjs
deleted file mode 100644
index 327372f9b..000000000
--- a/browser/base/content/test/general/refresh_header.sjs
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Will cause an auto-refresh to the URL provided in the query string
- * after some delay using the refresh HTTP header.
- *
- * Expects the query string to be in the format:
- *
- * ?p=[URL of the page to redirect to]&d=[delay]
- *
- * Example:
- *
- * ?p=http%3A%2F%2Fexample.org%2Fbrowser%2Fbrowser%2Fbase%2Fcontent%2Ftest%2Fgeneral%2Frefresh_meta.sjs&d=200
- */
-function handleRequest(request, response) {
- Components.utils.importGlobalProperties(["URLSearchParams"]);
- let query = new URLSearchParams(request.queryString);
-
- let page = query.get("p");
- let delay = query.get("d");
-
- response.setHeader("Content-Type", "text/html", false);
- response.setStatusLine(request.httpVersion, "200", "Found");
- response.setHeader("refresh", `${delay}; url=${page}`);
- response.write("OK");
-} \ No newline at end of file
diff --git a/browser/base/content/test/general/refresh_meta.sjs b/browser/base/content/test/general/refresh_meta.sjs
deleted file mode 100644
index 648fac1a3..000000000
--- a/browser/base/content/test/general/refresh_meta.sjs
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Will cause an auto-refresh to the URL provided in the query string
- * after some delay using a <meta> tag.
- *
- * Expects the query string to be in the format:
- *
- * ?p=[URL of the page to redirect to]&d=[delay]
- *
- * Example:
- *
- * ?p=http%3A%2F%2Fexample.org%2Fbrowser%2Fbrowser%2Fbase%2Fcontent%2Ftest%2Fgeneral%2Frefresh_meta.sjs&d=200
- */
-function handleRequest(request, response) {
- Components.utils.importGlobalProperties(["URLSearchParams"]);
- let query = new URLSearchParams(request.queryString);
-
- let page = query.get("p");
- let delay = query.get("d");
-
- let html = `<!DOCTYPE HTML>
- <html>
- <head>
- <meta charset='utf-8'>
- <META http-equiv='refresh' content='${delay}; url=${page}'>
- <title>Gonna refresh you, folks.</title>
- </head>
- <body>
- <h1>Wait for it...</h1>
- </body>
- </html>`;
-
- response.setHeader("Content-Type", "text/html", false);
- response.setStatusLine(request.httpVersion, "200", "Found");
- response.setHeader("Cache-Control", "no-cache", false);
- response.write(html);
-} \ No newline at end of file
diff --git a/browser/base/content/test/general/searchSuggestionEngine.sjs b/browser/base/content/test/general/searchSuggestionEngine.sjs
deleted file mode 100644
index 1978b4f66..000000000
--- a/browser/base/content/test/general/searchSuggestionEngine.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(req, resp) {
- let suffixes = ["foo", "bar"];
- let data = [req.queryString, suffixes.map(s => req.queryString + s)];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
-}
diff --git a/browser/base/content/test/general/searchSuggestionEngine.xml b/browser/base/content/test/general/searchSuggestionEngine.xml
deleted file mode 100644
index 3d1f294f5..000000000
--- a/browser/base/content/test/general/searchSuggestionEngine.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_searchSuggestionEngine searchSuggestionEngine.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/base/content/test/general/searchSuggestionEngine.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://mochi.test:8888/" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/base/content/test/general/searchSuggestionEngine2.xml b/browser/base/content/test/general/searchSuggestionEngine2.xml
deleted file mode 100644
index 05644649a..000000000
--- a/browser/base/content/test/general/searchSuggestionEngine2.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_searchSuggestionEngine searchSuggestionEngine2.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/base/content/test/general/searchSuggestionEngine.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://www.browser-searchSuggestionEngine.com/searchSuggestionEngine2&amp;terms={searchTerms}" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/base/content/test/general/ssl_error_reports.sjs b/browser/base/content/test/general/ssl_error_reports.sjs
deleted file mode 100644
index e2e5bafc0..000000000
--- a/browser/base/content/test/general/ssl_error_reports.sjs
+++ /dev/null
@@ -1,91 +0,0 @@
-const EXPECTED_CHAIN = [
- "MIIDCjCCAfKgAwIBAgIENUiGYDANBgkqhkiG9w0BAQsFADAmMSQwIgYDVQQDExtBbHRlcm5hdGUgVHJ1c3RlZCBBdXRob3JpdHkwHhcNMTQxMDAxMjExNDE5WhcNMjQxMDAxMjExNDE5WjAxMS8wLQYDVQQDEyZpbmNsdWRlLXN1YmRvbWFpbnMucGlubmluZy5leGFtcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALxYrge8C4eVfTb6/lJ4k/+/4J6wlnWpp5Szxy1MHhsLB+LJh/HRHqkO/tsigT204kTeU3dxuAfQHz0g+Td8dr6KICLLNVFUPw+XjhBV4AtxV8wcprs6EmdBhJgAjkFB4M76BL7/Ow0NfH012WNESn8TTbsp3isgkmrXjTZhWR33vIL1eDNimykp/Os/+JO+x9KVfdCtDCrPwO9Yusial5JiaW7qemRtVuUDL87NSJ7xokPEOSc9luv/fBamZ3rgqf3K6epqg+0o3nNCCcNFnfLW52G0t69+dIjr39WISHnqqZj3Sb7JPU6OmxTd13ByoLkoM3ZUQ2Lpas+RJvQyGXkCAwEAAaM1MDMwMQYDVR0RBCowKIImaW5jbHVkZS1zdWJkb21haW5zLnBpbm5pbmcuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBAAmzXfeoOS59FkNABRonFPRyFl7BoGpVJENUteFfTa2pdAhGYdo19Y4uILTTj+vtDAa5yryb5Uvd+YuJnExosbMMkzCrmZ9+VJCJdqUTb+idwk9/sgPl2gtGeRmefB0hXSUFHc/p1CDufSpYOmj9NCUZD2JEsybgJQNulkfAsVnS3lzDcxAwcO+RC/1uJDSiUtcBpWS4FW58liuDYE7PD67kLJHZPVUV2WCMuIl4VM2tKPtvShz1JkZ5UytOLs6jPfviNAk/ftXczaE2/RJgM2MnDX9nGzOxG6ONcVNCljL8avhFBCosutE6i5LYSZR6V14YY/xOn15WDSuWdnIsJCo=",
- "MIIC2jCCAcKgAwIBAgIBATANBgkqhkiG9w0BAQsFADAmMSQwIgYDVQQDExtBbHRlcm5hdGUgVHJ1c3RlZCBBdXRob3JpdHkwHhcNMTQwOTI1MjEyMTU0WhcNMjQwOTI1MjEyMTU0WjAmMSQwIgYDVQQDExtBbHRlcm5hdGUgVHJ1c3RlZCBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDBT+BwAhO52IWgSIdZZifU9LHOs3IR/+8DCC0WP5d/OuyKlZ6Rqd0tsd3i7durhQyjHSbLf2lJStcnFjcVEbEnNI76RuvlN8xLLn5eV+2Ayr4cZYKztudwRmw+DV/iYAiMSy0hs7m3ssfX7qpoi1aNRjUanwU0VTCPQhF1bEKAC2du+C5Z8e92zN5t87w7bYr7lt+m8197XliXEu+0s9RgnGwGaZ296BIRz6NOoJYTa43n06LU1I1+Z4d6lPdzUFrSR0GBaMhUSurUBtOin3yWiMhg1VHX/KwqGc4als5GyCVXy8HGrA/0zQPOhetxrlhEVAdK/xBt7CZvByj1Rcc7AgMBAAGjEzARMA8GA1UdEwQIMAYBAf8CAQAwDQYJKoZIhvcNAQELBQADggEBAJq/hogSRqzPWTwX4wTn/DVSNdWwFLv53qep9YrSMJ8ZsfbfK9Es4VP4dBLRQAVMJ0Z5mW1I6d/n0KayTanuUBvemYdxPi/qQNSs8UJcllqdhqWzmzAg6a0LxrMnEeKzPBPD6q8PwQ7tYP+B4sBN9tnnsnyPgti9ZiNZn5FwXZliHXseQ7FE9/SqHlLw5LXW3YtKjuti6RmuV6fq3j+D4oeC5vb1mKgIyoTqGN6ze57v8RHi+pQ8Q+kmoUn/L3Z2YmFe4SKN/4WoyXr8TdejpThGOCGCAd3565s5gOx5QfSQX11P8NZKO8hcN0tme3VzmGpHK0Z/6MTmdpNaTwQ6odk="
- ];
-
-const MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE = -16384;
-
-function parseReport(request) {
- // read the report from the request
- let inputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
- inputStream.init(request.bodyInputStream, 0x01, 0004, 0);
-
- let body = "";
- if (inputStream) {
- while (inputStream.available()) {
- body = body + inputStream.read(inputStream.available());
- }
- }
- // parse the report
- return JSON.parse(body);
-}
-
-function handleRequest(request, response) {
- let report = {};
- let certChain = [];
-
- switch (request.queryString) {
- case "succeed":
- report = parseReport(request);
- certChain = report.failedCertChain;
-
- // ensure the cert chain is what we expect
- for (idx in certChain) {
- if (certChain[idx] !== EXPECTED_CHAIN[idx]) {
- // if the chain differs, send an error response to cause test
- // failure
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>The report contained an unexpected chain</html>");
- return;
- }
- }
-
- if (report.errorCode !== MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE) {
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>The report contained an unexpected error code</html>");
- return;
- }
-
- // if all is as expected, send the 201 the client expects
- response.setStatusLine("1.1", 201, "Created");
- response.write("<html>OK</html>");
- break;
- case "nocert":
- report = parseReport(request);
- certChain = report.failedCertChain;
-
- if (certChain && certChain.length > 0) {
- // We're not expecting a chain; if there is one, send an error
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>The report contained an unexpected chain</html>");
- return;
- }
-
- // if all is as expected, send the 201 the client expects
- response.setStatusLine("1.1", 201, "Created");
- response.write("<html>OK</html>");
- break;
- case "badcert":
- report = parseReport(request);
- certChain = report.failedCertChain;
-
- if (!certChain || certChain.length != 2) {
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>The report contained an unexpected chain</html>");
- return;
- }
-
- // if all is as expected, send the 201 the client expects
- response.setStatusLine("1.1", 201, "Created");
- response.write("<html>OK</html>");
- break;
- case "error":
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>server error</html>");
- break;
- default:
- response.setStatusLine("1.1", 500, "Server error");
- response.write("<html>succeed, nocert or error expected (got " + request.queryString + ")</html>");
- break;
- }
-}
diff --git a/browser/base/content/test/general/subtst_contextmenu.html b/browser/base/content/test/general/subtst_contextmenu.html
deleted file mode 100644
index 1768f399f..000000000
--- a/browser/base/content/test/general/subtst_contextmenu.html
+++ /dev/null
@@ -1,73 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Subtest for browser context menu</title>
-</head>
-<body>
-Browser context menu subtest.
-
-<div id="test-text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>
-<a id="test-link" href="http://mozilla.com">Click the monkey!</a>
-<a id="test-mailto" href="mailto:codemonkey@mozilla.com">Mail the monkey!</a><br>
-<input id="test-input"><br>
-<img id="test-image" src="ctxmenu-image.png">
-<canvas id="test-canvas" width="100" height="100" style="background-color: blue"></canvas>
-<video controls id="test-video-ok" src="video.ogg" width="100" height="100" style="background-color: green"></video>
-<video id="test-audio-in-video" src="audio.ogg" width="100" height="100" style="background-color: red"></video>
-<video controls id="test-video-bad" src="bogus.duh" width="100" height="100" style="background-color: orange"></video>
-<video controls id="test-video-bad2" width="100" height="100" style="background-color: yellow">
- <source src="bogus.duh" type="video/durrrr;">
-</video>
-<iframe id="test-iframe" width="98" height="98" style="border: 1px solid black"></iframe>
-<iframe id="test-video-in-iframe" src="video.ogg" width="98" height="98" style="border: 1px solid black"></iframe>
-<iframe id="test-audio-in-iframe" src="audio.ogg" width="98" height="98" style="border: 1px solid black"></iframe>
-<iframe id="test-image-in-iframe" src="ctxmenu-image.png" width="98" height="98" style="border: 1px solid black"></iframe>
-<textarea id="test-textarea">chssseesbbbie</textarea> <!-- a weird word which generates only one suggestion -->
-<div id="test-contenteditable" contenteditable="true">chssseefsbbbie</div> <!-- a more weird word which generates no suggestions -->
-<div id="test-contenteditable-spellcheck-false" contenteditable="true" spellcheck="false">test</div> <!-- No Check Spelling menu item -->
-<div id="test-dom-full-screen">DOM full screen FTW</div>
-<div contextmenu="myMenu">
- <p id="test-pagemenu" hopeless="true">I've got a context menu!</p>
- <menu id="myMenu" type="context">
- <menuitem label="Plain item" onclick="document.getElementById('test-pagemenu').removeAttribute('hopeless');"></menuitem>
- <menuitem label="Disabled item" disabled></menuitem>
- <menuitem> Item w/ textContent</menuitem>
- <menu>
- <menuitem type="checkbox" label="Checkbox" checked></menuitem>
- </menu>
- <menu>
- <menuitem type="radio" label="Radio1" checked></menuitem>
- <menuitem type="radio" label="Radio2"></menuitem>
- <menuitem type="radio" label="Radio3"></menuitem>
- </menu>
- <menu>
- <menuitem label="Item w/ icon" icon="favicon.ico"></menuitem>
- <menuitem label="Item w/ bad icon" icon="data://www.mozilla.org/favicon.ico"></menuitem>
- </menu>
- <menu label="Submenu">
- <menuitem type="radio" label="Radio1" radiogroup="rg"></menuitem>
- <menuitem type="radio" label="Radio2" checked radiogroup="rg"></menuitem>
- <menuitem type="radio" label="Radio3" radiogroup="rg"></menuitem>
- <menu>
- <menuitem type="checkbox" label="Checkbox"></menuitem>
- </menu>
- </menu>
- <menu hidden>
- <menuitem label="Bogus item"></menuitem>
- </menu>
- <menu>
- </menu>
- <menuitem label="Hidden item" hidden></menuitem>
- <menuitem></menuitem>
- </menu>
-</div>
-<div id="test-select-text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>
-<div id="test-select-text-link">http://mozilla.com</div>
-<a id="test-image-link" href="#"><img src="ctxmenu-image.png"></a>
-<input id="test-select-input-text" type="text" value="input">
-<input id="test-select-input-text-type-password" type="password" value="password">
-<embed id="test-plugin" style="width: 200px; height: 200px;" type="application/x-test"></embed>
-<img id="test-longdesc" src="ctxmenu-image.png" longdesc="http://www.mozilla.org"></embed>
-<iframe id="test-srcdoc" width="98" height="98" srcdoc="Hello World" style="border: 1px solid black"></iframe>
-</body>
-</html>
diff --git a/browser/base/content/test/general/subtst_contextmenu_input.html b/browser/base/content/test/general/subtst_contextmenu_input.html
deleted file mode 100644
index c5be977ea..000000000
--- a/browser/base/content/test/general/subtst_contextmenu_input.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Subtest for browser context menu</title>
-</head>
-<body>
- Browser context menu subtest.
- <input id="input_text">
- <input id="input_spellcheck_no_value">
- <input id="input_spellcheck_incorrect" spellcheck="true" value="prodkjfgigrty">
- <input id="input_spellcheck_correct" spellcheck="true" value="foo">
- <input id="input_disabled" disabled="true">
- <input id="input_password">
- <input id="input_email" type="email">
- <input id="input_tel" type="tel">
- <input id="input_url" type="url">
- <input id="input_number" type="number">
- <input id="input_date" type="date">
- <input id="input_time" type="time">
- <input id="input_color" type="color">
- <input id="input_range" type="range">
- <input id="input_search" type="search">
- <input id="input_datetime" type="datetime">
- <input id="input_month" type="month">
- <input id="input_week" type="week">
- <input id="input_datetime-local" type="datetime-local">
- <input id="input_readonly" readonly="true">
-</body>
-</html>
diff --git a/browser/base/content/test/general/subtst_contextmenu_xul.xul b/browser/base/content/test/general/subtst_contextmenu_xul.xul
deleted file mode 100644
index 5a2ab42e8..000000000
--- a/browser/base/content/test/general/subtst_contextmenu_xul.xul
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0"?>
-<!-- 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/. -->
-
-<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- xmlns:html="http://www.w3.org/1999/xhtml">
- <label id="test-xul-text-link-label" class="text-link" value="XUL text-link label" href="https://www.mozilla.com"/>
-</page>
diff --git a/browser/base/content/test/general/svg_image.html b/browser/base/content/test/general/svg_image.html
deleted file mode 100644
index 7ab17c33a..000000000
--- a/browser/base/content/test/general/svg_image.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Test for page info svg images</title>
- </head>
- <body>
- <svg width="20" height="20">
- <image xlink:href="title_test.svg" width="20" height="20">
- </svg>
- </body>
-</html>
diff --git a/browser/base/content/test/general/test-mixedcontent-securityerrors.html b/browser/base/content/test/general/test-mixedcontent-securityerrors.html
deleted file mode 100644
index cb8cfdaaf..000000000
--- a/browser/base/content/test/general/test-mixedcontent-securityerrors.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!--
- Bug 875456 - Log mixed content messages from the Mixed Content Blocker to the
- Security Pane in the Web Console
--->
-
-<!DOCTYPE HTML>
-<html dir="ltr" xml:lang="en-US" lang="en-US">
- <head>
- <meta charset="utf8">
- <title>Mixed Content test - http on https</title>
- <script src="testscript.js"></script>
- <!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
- -->
- </head>
- <body>
- <iframe src="http://example.com"></iframe>
- <img src="http://example.com/tests/image/test/mochitest/blue.png"></img>
- </body>
-</html>
diff --git a/browser/base/content/test/general/test_bug364677.html b/browser/base/content/test/general/test_bug364677.html
deleted file mode 100644
index 67b9729d1..000000000
--- a/browser/base/content/test/general/test_bug364677.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=364677
--->
-<head>
- <title>Test for Bug 364677</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=364677">Mozilla Bug 364677</a>
-<p id="display"><iframe id="testFrame" src="bug364677-data.xml"></iframe></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 364677 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- is(SpecialPowers.wrap($("testFrame")).contentDocument.documentElement.id, "feedHandler",
- "Feed served as text/xml without a channel/link should have been sniffed");
-});
-addLoadEvent(SimpleTest.finish);
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/browser/base/content/test/general/test_bug395533.html b/browser/base/content/test/general/test_bug395533.html
deleted file mode 100644
index ad6209047..000000000
--- a/browser/base/content/test/general/test_bug395533.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=395533
--->
-<head>
- <title>Test for Bug 395533</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=395533">Mozilla Bug 395533</a>
-<p id="display"><iframe id="testFrame" src="bug395533-data.txt"></iframe></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 395533 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- // Need privs because the feed seems to have an about:feeds principal or some
- // such. It's not same-origin with us in any case.
- is(SpecialPowers.wrap($("testFrame")).contentDocument.documentElement.id, "",
- "Text got sniffed as a feed?");
-});
-addLoadEvent(SimpleTest.finish);
-
-
-
-
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/browser/base/content/test/general/test_bug435035.html b/browser/base/content/test/general/test_bug435035.html
deleted file mode 100644
index a6624db15..000000000
--- a/browser/base/content/test/general/test_bug435035.html
+++ /dev/null
@@ -1 +0,0 @@
-<img src="http://example.com/browser/browser/base/content/test/general/moz.png">
diff --git a/browser/base/content/test/general/test_bug462673.html b/browser/base/content/test/general/test_bug462673.html
deleted file mode 100644
index d864990e4..000000000
--- a/browser/base/content/test/general/test_bug462673.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
-<head>
-<script>
-var w;
-function openIt() {
- w = window.open("", "window2");
-}
-function closeIt() {
- if (w) {
- w.close();
- w = null;
- }
-}
-</script>
-</head>
-<body onload="openIt();" onunload="closeIt();">
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_bug628179.html b/browser/base/content/test/general/test_bug628179.html
deleted file mode 100644
index d35e17a7c..000000000
--- a/browser/base/content/test/general/test_bug628179.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Test for closing the Find bar in subdocuments</title>
- </head>
- <body>
- <iframe id=iframe src="http://example.com/" width=320 height=240></iframe>
- </body>
-</html>
-
diff --git a/browser/base/content/test/general/test_bug839103.html b/browser/base/content/test/general/test_bug839103.html
deleted file mode 100644
index 3639d4bda..000000000
--- a/browser/base/content/test/general/test_bug839103.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>Document for Bug 839103</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <style></style>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_bug959531.html b/browser/base/content/test/general/test_bug959531.html
deleted file mode 100644
index e749b198a..000000000
--- a/browser/base/content/test/general/test_bug959531.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Test for content page with settings button</title>
- </head>
- <body>
- <button name="settings" id="settings">Settings</button>
- </body>
-</html>
diff --git a/browser/base/content/test/general/test_mcb_double_redirect_image.html b/browser/base/content/test/general/test_mcb_double_redirect_image.html
deleted file mode 100644
index 1b54774ec..000000000
--- a/browser/base/content/test/general/test_mcb_double_redirect_image.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 7-9 for Bug 1082837 - See file browser_mcb_redirect.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=1082837
--->
-<head>
- <meta charset="utf-8">
- <title>Bug 1082837</title>
- <script>
- function image_loaded() {
- document.getElementById("mctestdiv").innerHTML = "image loaded";
- }
- function image_blocked() {
- document.getElementById("mctestdiv").innerHTML = "image blocked";
- }
- </script>
-</head>
-<body>
- <div id="mctestdiv"></div>
- <img src="https://example.com/browser/browser/base/content/test/general/test_mcb_redirect.sjs?image_redirect_http_sjs" onload="image_loaded()" onerror="image_blocked()" ></image>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_mcb_redirect.html b/browser/base/content/test/general/test_mcb_redirect.html
deleted file mode 100644
index 88af791a3..000000000
--- a/browser/base/content/test/general/test_mcb_redirect.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 1 for Bug 418354 - See file browser_mcb_redirect.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=418354
--->
-<head>
- <meta charset="utf-8">
- <title>Bug 418354</title>
-</head>
-<body>
- <div id="mctestdiv">script blocked</div>
- <script src="https://example.com/browser/browser/base/content/test/general/test_mcb_redirect.sjs?script" ></script>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_mcb_redirect.js b/browser/base/content/test/general/test_mcb_redirect.js
deleted file mode 100644
index 48538c940..000000000
--- a/browser/base/content/test/general/test_mcb_redirect.js
+++ /dev/null
@@ -1,5 +0,0 @@
-/*
- * Once the mixed content blocker is disabled for the page, this scripts loads
- * and updates the text inside the div container.
- */
-document.getElementById("mctestdiv").innerHTML = "script executed";
diff --git a/browser/base/content/test/general/test_mcb_redirect.sjs b/browser/base/content/test/general/test_mcb_redirect.sjs
deleted file mode 100644
index 9a1811dfa..000000000
--- a/browser/base/content/test/general/test_mcb_redirect.sjs
+++ /dev/null
@@ -1,22 +0,0 @@
-function handleRequest(request, response) {
- var page = "<!DOCTYPE html><html><body>bug 418354 and bug 1082837</body></html>";
-
- if (request.queryString === "script") {
- var redirect = "http://example.com/browser/browser/base/content/test/general/test_mcb_redirect.js";
- response.setHeader("Cache-Control", "no-cache", false);
- } else if (request.queryString === "image_http") {
- var redirect = "http://example.com/tests/image/test/mochitest/blue.png";
- response.setHeader("Cache-Control", "max-age=3600", false);
- } else if (request.queryString === "image_redirect_http_sjs") {
- var redirect = "http://example.com/browser/browser/base/content/test/general/test_mcb_redirect.sjs?image_redirect_https";
- response.setHeader("Cache-Control", "max-age=3600", false);
- } else if (request.queryString === "image_redirect_https") {
- var redirect = "https://example.com/tests/image/test/mochitest/blue.png";
- response.setHeader("Cache-Control", "max-age=3600", false);
- }
-
- response.setHeader("Content-Type", "text/html", false);
- response.setStatusLine(request.httpVersion, "302", "Found");
- response.setHeader("Location", redirect, false);
- response.write(page);
-}
diff --git a/browser/base/content/test/general/test_mcb_redirect_image.html b/browser/base/content/test/general/test_mcb_redirect_image.html
deleted file mode 100644
index c70cd8987..000000000
--- a/browser/base/content/test/general/test_mcb_redirect_image.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 3-6 for Bug 1082837 - See file browser_mcb_redirect.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=1082837
--->
-<head>
- <meta charset="utf-8">
- <title>Bug 1082837</title>
- <script>
- function image_loaded() {
- document.getElementById("mctestdiv").innerHTML = "image loaded";
- }
- function image_blocked() {
- document.getElementById("mctestdiv").innerHTML = "image blocked";
- }
- </script>
-</head>
-<body>
- <div id="mctestdiv"></div>
- <img src="https://example.com/browser/browser/base/content/test/general/test_mcb_redirect.sjs?image_http" onload="image_loaded()" onerror="image_blocked()" ></image>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_font.css b/browser/base/content/test/general/test_no_mcb_on_http_site_font.css
deleted file mode 100644
index 68a6954cc..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_font.css
+++ /dev/null
@@ -1,10 +0,0 @@
-@font-face {
- font-family: testFont;
- src: url(http://example.com/browser/devtools/client/fontinspector/test/browser_font.woff);
-}
-body {
- font-family: Arial;
-}
-div {
- font-family: testFont;
-}
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_font.html b/browser/base/content/test/general/test_no_mcb_on_http_site_font.html
deleted file mode 100644
index 28a9cb2c0..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_font.html
+++ /dev/null
@@ -1,47 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 2 for Bug 909920 - See file browser_no_mcb_on_http_site.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=909920
--->
-<head>
- <meta charset="utf-8">
- <title>Test 2 for Bug 909920</title>
- <link rel="stylesheet" type="text/css" href="https://example.com/browser/browser/base/content/test/general/test_no_mcb_on_http_site_font.css" />
-<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-
-<script type="text/javascript">
- function checkLoadStates() {
- var ui = SpecialPowers.wrap(window)
- .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
- .getInterface(SpecialPowers.Ci.nsIWebNavigation)
- .QueryInterface(SpecialPowers.Ci.nsIDocShell)
- .securityUI;
-
- var loadedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_ACTIVE_CONTENT);
- is(loadedMixedActive, false, "OK: Should not load mixed active content!");
-
- var blockedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_ACTIVE_CONTENT);
- is(blockedMixedActive, false, "OK: Should not block mixed active content!");
-
- var loadedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_DISPLAY_CONTENT);
- is(loadedMixedDisplay, false, "OK: Should not load mixed display content!");
-
- var blockedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_DISPLAY_CONTENT);
- is(blockedMixedDisplay, false, "OK: Should not block mixed display content!");
-
- var newValue = "Verifying MCB does not trigger warning/error for an http page with https css that includes http font";
- document.getElementById("testDiv").innerHTML = newValue;
- }
-</script>
-</head>
-<body onload="checkLoadStates()">
- <div class="testDiv" id="testDiv">
- Testing MCB does not trigger warning/error for an http page with https css that includes http font
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_font2.css b/browser/base/content/test/general/test_no_mcb_on_http_site_font2.css
deleted file mode 100644
index f73b573b4..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_font2.css
+++ /dev/null
@@ -1 +0,0 @@
-@import url(http://example.com/browser/browser/base/content/test/general/test_no_mcb_on_http_site_font.css);
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_font2.html b/browser/base/content/test/general/test_no_mcb_on_http_site_font2.html
deleted file mode 100644
index 2b3164902..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_font2.html
+++ /dev/null
@@ -1,48 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 3 for Bug 909920 - See file browser_no_mcb_on_http_site.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=909920
--->
-<head>
- <meta charset="utf-8">
- <title>Test 3 for Bug 909920</title>
- <link rel="stylesheet" type="text/css" href="https://example.com/browser/browser/base/content/test/general/test_no_mcb_on_http_site_font2.css" />
-<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-
-<script type="text/javascript">
- function checkLoadStates() {
- var ui = SpecialPowers.wrap(window)
- .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
- .getInterface(SpecialPowers.Ci.nsIWebNavigation)
- .QueryInterface(SpecialPowers.Ci.nsIDocShell)
- .securityUI;
-
- var loadedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_ACTIVE_CONTENT);
- is(loadedMixedActive, false, "OK: Should not load mixed active content!");
-
- var blockedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_ACTIVE_CONTENT);
- is(blockedMixedActive, false, "OK: Should not block mixed active content!");
-
- var loadedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_DISPLAY_CONTENT);
- is(loadedMixedDisplay, false, "OK: Should not load mixed display content!");
-
- var blockedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_DISPLAY_CONTENT);
- is(blockedMixedDisplay, false, "OK: Should not block mixed display content!");
-
- var newValue = "Verifying MCB does not trigger warning/error for an http page ";
- newValue += "with https css that imports another http css which includes http font";
- document.getElementById("testDiv").innerHTML = newValue;
- }
-</script>
-</head>
-<body onload="checkLoadStates()">
- <div class="testDiv" id="testDiv">
- Testing MCB does not trigger warning/error for an http page with https css that imports another http css which includes http font
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_img.css b/browser/base/content/test/general/test_no_mcb_on_http_site_img.css
deleted file mode 100644
index d045e21ba..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_img.css
+++ /dev/null
@@ -1,3 +0,0 @@
-#testDiv {
- background: url(http://example.com/tests/image/test/mochitest/blue.png)
-}
diff --git a/browser/base/content/test/general/test_no_mcb_on_http_site_img.html b/browser/base/content/test/general/test_no_mcb_on_http_site_img.html
deleted file mode 100644
index 741573260..000000000
--- a/browser/base/content/test/general/test_no_mcb_on_http_site_img.html
+++ /dev/null
@@ -1,47 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
- Test 1 for Bug 909920 - See file browser_no_mcb_on_http_site.js for description.
- https://bugzilla.mozilla.org/show_bug.cgi?id=909920
--->
-<head>
- <meta charset="utf-8">
- <title>Test 1 for Bug 909920</title>
- <link rel="stylesheet" type="text/css" href="https://example.com/browser/browser/base/content/test/general/test_no_mcb_on_http_site_img.css" />
-<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-
-<script type="text/javascript">
- function checkLoadStates() {
- var ui = SpecialPowers.wrap(window)
- .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
- .getInterface(SpecialPowers.Ci.nsIWebNavigation)
- .QueryInterface(SpecialPowers.Ci.nsIDocShell)
- .securityUI;
-
- var loadedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_ACTIVE_CONTENT);
- is(loadedMixedActive, false, "OK: Should not load mixed active content!");
-
- var blockedMixedActive = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_ACTIVE_CONTENT);
- is(blockedMixedActive, false, "OK: Should not block mixed active content!");
-
- var loadedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_LOADED_MIXED_DISPLAY_CONTENT);
- is(loadedMixedDisplay, false, "OK: Should not load mixed display content!");
-
- var blockedMixedDisplay = ui &&
- !!(ui.state & SpecialPowers.Ci.nsIWebProgressListener.STATE_BLOCKED_MIXED_DISPLAY_CONTENT);
- is(blockedMixedDisplay, false, "OK: Should not block mixed display content!");
-
- var newValue = "Verifying MCB does not trigger warning/error for an http page with https css that includes http image";
- document.getElementById("testDiv").innerHTML = newValue;
- }
-</script>
-</head>
-<body onload="checkLoadStates()">
- <div class="testDiv" id="testDiv">
- Testing MCB does not trigger warning/error for an http page with https css that includes http image
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_offlineNotification.html b/browser/base/content/test/general/test_offlineNotification.html
deleted file mode 100644
index 4f78184b4..000000000
--- a/browser/base/content/test/general/test_offlineNotification.html
+++ /dev/null
@@ -1,129 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=462856
--->
-<head>
- <title>Test offline app notification</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="offlineByDefault.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display">
-<!-- Load the test frame twice from the same domain,
- to make sure we get notifications for both -->
-<iframe name="testFrame" src="offlineChild.html"></iframe>
-<iframe name="testFrame2" src="offlineChild2.html"></iframe>
-<!-- Load from another domain to make sure we get a second allow/deny
- notification -->
-<iframe name="testFrame3" src="http://example.com/tests/browser/base/content/test/general/offlineChild.html"></iframe>
-
-<iframe id="eventsTestFrame" src="offlineEvent.html"></iframe>
-
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-SimpleTest.waitForExplicitFinish();
-const Cc = SpecialPowers.Cc;
-
-var numFinished = 0;
-
-window.addEventListener("message", function(event) {
- is(event.data, "success", "Child was successfully cached.");
-
- if (++numFinished == 3) {
- // Clean up after ourself
- var pm = Cc["@mozilla.org/permissionmanager;1"].
- getService(SpecialPowers.Ci.nsIPermissionManager);
- var ioService = Cc["@mozilla.org/network/io-service;1"]
- .getService(SpecialPowers.Ci.nsIIOService);
- var uri1 = ioService.newURI(frames.testFrame.location, null, null);
- var uri2 = ioService.newURI(frames.testFrame3.location, null, null);
-
- var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(SpecialPowers.Ci.nsIScriptSecurityManager);
- var principal1 = ssm.createCodebasePrincipal(uri1, {});
- var principal2 = ssm.createCodebasePrincipal(uri2, {});
-
- pm.removeFromPrincipal(principal1, "offline-app");
- pm.removeFromPrincipal(principal2, "offline-app");
-
- offlineByDefault.reset();
-
- SimpleTest.finish();
- }
- }, false);
-
-var count = 0;
-var expectedEvent = "";
-function eventHandler(evt) {
- ++count;
- is(evt.type, expectedEvent, "Wrong event!");
-}
-
-function testEventHandling() {
- var events = [ "checking",
- "error",
- "noupdate",
- "downloading",
- "progress",
- "updateready",
- "cached",
- "obsolete"];
- var w = document.getElementById("eventsTestFrame").contentWindow;
- var e;
- for (var i = 0; i < events.length; ++i) {
- count = 0;
- expectedEvent = events[i];
- e = w.document.createEvent("event");
- e.initEvent(expectedEvent, true, true);
- w.applicationCache["on" + expectedEvent] = eventHandler;
- w.applicationCache.addEventListener(expectedEvent, eventHandler, true);
- w.applicationCache.dispatchEvent(e);
- is(count, 2, "Wrong number events!");
- w.applicationCache["on" + expectedEvent] = null;
- w.applicationCache.removeEventListener(expectedEvent, eventHandler, true);
- w.applicationCache.dispatchEvent(e);
- is(count, 2, "Wrong number events!");
- }
-
- // Test some random event.
- count = 0;
- expectedEvent = "foo";
- e = w.document.createEvent("event");
- e.initEvent(expectedEvent, true, true);
- w.applicationCache.addEventListener(expectedEvent, eventHandler, true);
- w.applicationCache.dispatchEvent(e);
- is(count, 1, "Wrong number events!");
- w.applicationCache.removeEventListener(expectedEvent, eventHandler, true);
- w.applicationCache.dispatchEvent(e);
- is(count, 1, "Wrong number events!");
-}
-
-function loaded() {
- testEventHandling();
-
- // Click the notification panel's "Allow" button. This should kick
- // off updates, which will eventually lead to getting messages from
- // the children.
- var wm = SpecialPowers.Cc["@mozilla.org/appshell/window-mediator;1"].
- getService(SpecialPowers.Ci.nsIWindowMediator);
- var win = wm.getMostRecentWindow("navigator:browser");
- var panel = win.PopupNotifications.panel;
- is(panel.childElementCount, 2, "2 notifications being displayed");
- panel.firstElementChild.button.click();
-
- // should have dismissed one of the notifications.
- is(panel.childElementCount, 1, "1 notification now being displayed");
- panel.firstElementChild.button.click();
-}
-
-SimpleTest.waitForFocus(loaded);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_offline_gzip.html b/browser/base/content/test/general/test_offline_gzip.html
deleted file mode 100644
index a18d6604e..000000000
--- a/browser/base/content/test/general/test_offline_gzip.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=501422
-
-When content which was transported over the network with
-Content-Type: gzip is added to the offline
-cache, it can be fetched from the cache successfully.
--->
-<head>
- <title>Test gzipped offline resources</title>
- <meta charset="utf-8">
-</head>
-<body>
-<p id="display">
-<iframe name="testFrame" src="gZipOfflineChild.html"></iframe>
-
-<div id="content" style="display: none">
-</div>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_process_flags_chrome.html b/browser/base/content/test/general/test_process_flags_chrome.html
deleted file mode 100644
index adcbf0340..000000000
--- a/browser/base/content/test/general/test_process_flags_chrome.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<body>
-<p>chrome: test page</p>
-<p><a href="chrome://mochitests/content/browser/browser/base/content/test/general/test_process_flags_chrome.html">chrome</a></p>
-<p><a href="chrome://mochitests-any/content/browser/browser/base/content/test/general/test_process_flags_chrome.html">canremote</a></p>
-<p><a href="chrome://mochitests-content/content/browser/browser/base/content/test/general/test_process_flags_chrome.html">mustremote</a></p>
-</body>
-</html>
diff --git a/browser/base/content/test/general/test_remoteTroubleshoot.html b/browser/base/content/test/general/test_remoteTroubleshoot.html
deleted file mode 100644
index 7ba1c5268..000000000
--- a/browser/base/content/test/general/test_remoteTroubleshoot.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<script>
-// This test is run multiple times, once with only strings allowed through the
-// WebChannel, and once with objects allowed. This function allows us to handle
-// both cases without too much pain.
-function makeDetails(object) {
- if (window.location.search.indexOf("object") >= 0) {
- return object;
- }
- return JSON.stringify(object)
-}
-// Add a listener for responses to our remote requests.
-window.addEventListener("WebChannelMessageToContent", function (event) {
- if (event.detail.id == "remote-troubleshooting") {
- // Send what we got back to the test.
- var backEvent = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: makeDetails({
- id: "test-remote-troubleshooting-backchannel",
- message: {
- message: event.detail.message,
- },
- }),
- });
- window.dispatchEvent(backEvent);
- // and stick it in our DOM just for good measure/diagnostics.
- document.getElementById("troubleshooting").textContent =
- JSON.stringify(event.detail.message, null, 2);
- }
-});
-
-// Make a request for the troubleshooting data as we load.
-window.onload = function() {
- var event = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: makeDetails({
- id: "remote-troubleshooting",
- message: {
- command: "request",
- },
- }),
- });
- window.dispatchEvent(event);
-}
-</script>
-
-<body>
- <pre id="troubleshooting"/>
-</body>
-
-</html>
diff --git a/browser/base/content/test/general/title_test.svg b/browser/base/content/test/general/title_test.svg
deleted file mode 100644
index 7638fd5cc..000000000
--- a/browser/base/content/test/general/title_test.svg
+++ /dev/null
@@ -1,59 +0,0 @@
-<svg width="640px" height="480px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
- <title>This is a root SVG element's title</title>
- <foreignObject>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <body>
- <svg xmlns="http://www.w3.org/2000/svg" id="svg1">
- <title>This is a non-root SVG element title</title>
- </svg>
- </body>
- </html>
- </foreignObject>
- <text id="text1" x="10px" y="32px" font-size="24px">
- This contains only &lt;title&gt;
- <title>
-
-
- This is a title
-
- </title>
- </text>
- <text id="text2" x="10px" y="96px" font-size="24px">
- This contains only &lt;desc&gt;
- <desc>This is a desc</desc>
- </text>
- <text id="text3" x="10px" y="128px" font-size="24px" title="ignored for SVG">
- This contains nothing.
- </text>
- <a id="link1" xlink:href="#">
- This link contains &lt;title&gt;
- <title>
- This is a title
- </title>
- <text id="text4" x="10px" y="192px" font-size="24px">
- </text>
- </a>
- <a id="link2" xlink:href="#">
- <text x="10px" y="192px" font-size="24px">
- This text contains &lt;title&gt;
- <title>
- This is a title
- </title>
- </text>
- </a>
- <a id="link3" xlink:href="#" xlink:title="This is an xlink:title attribute">
- <text x="10px" y="224px" font-size="24px">
- This link contains &lt;title&gt; &amp; xlink:title attr.
- <title>This is a title</title>
- </text>
- </a>
- <a id="link4" xlink:href="#" xlink:title="This is an xlink:title attribute">
- <text x="10px" y="256px" font-size="24px">
- This link contains xlink:title attr.
- </text>
- </a>
- <text id="text5" x="10px" y="160px" font-size="24px"
- xlink:title="This is an xlink:title attribute but it isn't on a link" >
- This contains nothing.
- </text>
-</svg>
diff --git a/browser/base/content/test/general/trackingPage.html b/browser/base/content/test/general/trackingPage.html
deleted file mode 100644
index 17f0e459e..000000000
--- a/browser/base/content/test/general/trackingPage.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<!-- 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/. -->
-<html dir="ltr" xml:lang="en-US" lang="en-US">
- <head>
- <meta charset="utf8">
- </head>
- <body>
- <iframe src="http://tracking.example.com/"></iframe>
- </body>
-</html>
diff --git a/browser/base/content/test/general/unknownContentType_file.pif b/browser/base/content/test/general/unknownContentType_file.pif
deleted file mode 100644
index 9353d1312..000000000
--- a/browser/base/content/test/general/unknownContentType_file.pif
+++ /dev/null
@@ -1 +0,0 @@
-Dummy content for unknownContentType_dialog_layout_data.pif
diff --git a/browser/base/content/test/general/unknownContentType_file.pif^headers^ b/browser/base/content/test/general/unknownContentType_file.pif^headers^
deleted file mode 100644
index 09b22facc..000000000
--- a/browser/base/content/test/general/unknownContentType_file.pif^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Type: application/octet-stream
diff --git a/browser/base/content/test/general/video.ogg b/browser/base/content/test/general/video.ogg
deleted file mode 100644
index ac7ece351..000000000
--- a/browser/base/content/test/general/video.ogg
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/web_video.html b/browser/base/content/test/general/web_video.html
deleted file mode 100644
index 467fb0ce1..000000000
--- a/browser/base/content/test/general/web_video.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <head>
- <title>Document with Web Video</title>
- </head>
- <body>
- This document has some web video in it.
- <br>
- <video src="web_video1.ogv" id="video1"> </video>
- </body>
-</html>
diff --git a/browser/base/content/test/general/web_video1.ogv b/browser/base/content/test/general/web_video1.ogv
deleted file mode 100644
index 093158432..000000000
--- a/browser/base/content/test/general/web_video1.ogv
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/general/web_video1.ogv^headers^ b/browser/base/content/test/general/web_video1.ogv^headers^
deleted file mode 100644
index 4511e9255..000000000
--- a/browser/base/content/test/general/web_video1.ogv^headers^
+++ /dev/null
@@ -1,3 +0,0 @@
-Content-Disposition: filename="web-video1-expectedName.ogv"
-Content-Type: video/ogg
-
diff --git a/browser/base/content/test/general/zoom_test.html b/browser/base/content/test/general/zoom_test.html
deleted file mode 100644
index bf80490ca..000000000
--- a/browser/base/content/test/general/zoom_test.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=416661
--->
- <head>
- <title>Test for zoom setting</title>
-
- </head>
- <body>
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=416661">Bug 416661</a>
- <p>Site specific zoom settings should not apply to image documents.</p>
- </body>
-</html>
diff --git a/browser/base/content/test/newtab/.eslintrc.js b/browser/base/content/test/newtab/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/newtab/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/newtab/browser.ini b/browser/base/content/test/newtab/browser.ini
deleted file mode 100644
index 2d14d208d..000000000
--- a/browser/base/content/test/newtab/browser.ini
+++ /dev/null
@@ -1,55 +0,0 @@
-[DEFAULT]
-skip-if = (os == 'linux') # Bug 1243103, Bug 1243398, etc.
-support-files =
- head.js
-
-[browser_newtab_1188015.js]
-[browser_newtab_background_captures.js]
-[browser_newtab_block.js]
-[browser_newtab_bug721442.js]
-[browser_newtab_bug722273.js]
-skip-if = (os == "mac" && debug) # temporary skip-if due to increase in intermittent failures on Mac debug - bug 1119906
-[browser_newtab_bug723102.js]
-[browser_newtab_bug723121.js]
-[browser_newtab_bug725996.js]
-[browser_newtab_bug734043.js]
-[browser_newtab_bug735987.js]
-[browser_newtab_bug752841.js]
-[browser_newtab_bug765628.js]
-[browser_newtab_bug876313.js]
-[browser_newtab_bug991111.js]
-[browser_newtab_bug991210.js]
-[browser_newtab_bug998387.js]
-[browser_newtab_bug1145428.js]
-[browser_newtab_bug1178586.js]
-[browser_newtab_bug1194895.js]
-[browser_newtab_bug1271075.js]
-[browser_newtab_disable.js]
-[browser_newtab_drag_drop.js]
-[browser_newtab_drag_drop_ext.js]
-# temporary until determine why more intermittent on VM
-subsuite = clipboard
-[browser_newtab_drop_preview.js]
-[browser_newtab_enhanced.js]
-[browser_newtab_focus.js]
-[browser_newtab_perwindow_private_browsing.js]
-[browser_newtab_reportLinkAction.js]
-[browser_newtab_reflow_load.js]
-support-files =
- content-reflows.js
-[browser_newtab_search.js]
-support-files =
- searchEngineNoLogo.xml
- searchEngineFavicon.xml
- searchEngine1xLogo.xml
- searchEngine2xLogo.xml
- searchEngine1x2xLogo.xml
- ../general/searchSuggestionEngine.xml
- ../general/searchSuggestionEngine.sjs
-[browser_newtab_sponsored_icon_click.js]
-skip-if = true # Bug 1314619
-[browser_newtab_undo.js]
-# temporary until determine why more intermittent on VM
-subsuite = clipboard
-[browser_newtab_unpin.js]
-[browser_newtab_update.js]
diff --git a/browser/base/content/test/newtab/browser_newtab_1188015.js b/browser/base/content/test/newtab/browser_newtab_1188015.js
deleted file mode 100644
index f19aae1b9..000000000
--- a/browser/base/content/test/newtab/browser_newtab_1188015.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "directory": [{
- url: "http://example1.com/",
- enhancedImageURI: "data:image/png;base64,helloWORLD2",
- title: "title1",
- type: "affiliate",
- titleBgColor: "green"
- }]
-});
-
-add_task(function* () {
- yield pushPrefs(["browser.newtab.preload", false]);
-
- // Make the page have a directory link
- yield setLinks([]);
- yield* addNewTabPageTab();
-
- let color = yield performOnCell(0, cell => {
- return cell.node.querySelector(".newtab-title").style.backgroundColor;
- });
-
- is(color, "green", "title bg color is green");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_background_captures.js b/browser/base/content/test/newtab/browser_newtab_background_captures.js
deleted file mode 100644
index 5e838196e..000000000
--- a/browser/base/content/test/newtab/browser_newtab_background_captures.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Verifies that hidden, pre-loaded newtabs don't allow background captures, and
- * when unhidden, do allow background captures.
- */
-
-const CAPTURE_PREF = "browser.pagethumbnails.capturing_disabled";
-
-add_task(function* () {
- let imports = {};
- Cu.import("resource://gre/modules/PageThumbs.jsm", imports);
-
- // Disable captures.
- yield pushPrefs([CAPTURE_PREF, false]);
-
- // Make sure the thumbnail doesn't exist yet.
- let url = "http://example.com/";
- let path = imports.PageThumbsStorage.getFilePathForURL(url);
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(path);
- try {
- file.remove(false);
- }
- catch (err) {}
-
- // Add a top site.
- yield setLinks("-1");
-
- // We need a handle to a hidden, pre-loaded newtab so we can verify that it
- // doesn't allow background captures. Ensure we have a preloaded browser.
- gBrowser._createPreloadBrowser();
-
- // Wait for the preloaded browser to load.
- if (gBrowser._preloadedBrowser.contentDocument.readyState != "complete") {
- yield BrowserTestUtils.waitForEvent(gBrowser._preloadedBrowser, "load", true);
- }
-
- // We're now ready to use the preloaded browser.
- BrowserOpenTab();
- let tab = gBrowser.selectedTab;
-
- let thumbnailCreatedPromise = new Promise(resolve => {
- // Showing the preloaded tab should trigger thumbnail capture.
- Services.obs.addObserver(function onCreate(subj, topic, data) {
- if (data != url)
- return;
- Services.obs.removeObserver(onCreate, "page-thumbnail:create");
- ok(true, "thumbnail created after preloaded tab was shown");
-
- resolve();
- }, "page-thumbnail:create", false);
- });
-
- // Enable captures.
- yield pushPrefs([CAPTURE_PREF, false]);
-
- yield thumbnailCreatedPromise;
-
- // Test finished!
- gBrowser.removeTab(tab);
- file.remove(false);
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_block.js b/browser/base/content/test/newtab/browser_newtab_block.js
deleted file mode 100644
index 70656462a..000000000
--- a/browser/base/content/test/newtab/browser_newtab_block.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-/*
- * These tests make sure that blocking/removing sites from the grid works
- * as expected. Pinned tabs should not be moved. Gaps will be re-filled
- * if more sites are available.
- */
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "suggested": [{
- url: "http://suggested.com/",
- imageURI: "data:image/png;base64,helloWORLD3",
- title: "title",
- type: "affiliate",
- adgroup_name: "test",
- frecent_sites: ["example0.com"]
- }]
-});
-
-add_task(function* () {
- let origGetFrecentSitesName = DirectoryLinksProvider.getFrecentSitesName;
- DirectoryLinksProvider.getFrecentSitesName = () => "";
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = (site) => false;
-
- // we remove sites and expect the gaps to be filled as long as there still
- // are some sites available
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield customizeNewTabPage("enhanced"); // Toggle enhanced off
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield blockCell(4);
- yield* checkGrid("0,1,2,3,5,6,7,8,9");
-
- yield blockCell(4);
- yield* checkGrid("0,1,2,3,6,7,8,9,");
-
- yield blockCell(4);
- yield* checkGrid("0,1,2,3,7,8,9,,");
-
- // we removed a pinned site
- yield restore();
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",1");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1p,2,3,4,5,6,7,8");
-
- yield blockCell(1);
- yield* checkGrid("0,2,3,4,5,6,7,8,");
-
- // we remove the last site on the grid (which is pinned) and expect the gap
- // to be re-filled and the new site to be unpinned
- yield restore();
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks(",,,,,,,,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8p");
-
- yield blockCell(8);
- yield* checkGrid("0,1,2,3,4,5,6,7,9");
-
- // we remove the first site on the grid with the last one pinned. all cells
- // but the last one should shift to the left and a new site fades in
- yield restore();
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks(",,,,,,,,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8p");
-
- yield blockCell(0);
- yield* checkGrid("1,2,3,4,5,6,7,9,8p");
-
- // Test that blocking the targeted site also removes its associated suggested tile
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- yield restore();
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- yield customizeNewTabPage("enhanced"); // Toggle enhanced on
- yield* addNewTabPageTab();
-
- yield* checkGrid("http://suggested.com/,0,1,2,3,4,5,6,7,8,9");
-
- yield blockCell(1);
- yield* addNewTabPageTab();
- yield* checkGrid("1,2,3,4,5,6,7,8,9");
- DirectoryLinksProvider.getFrecentSitesName = origGetFrecentSitesName;
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug1145428.js b/browser/base/content/test/newtab/browser_newtab_bug1145428.js
deleted file mode 100644
index 72fe70212..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug1145428.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that pinning suggested tile results in:
- * - making suggested tile a history tile and replacing enhancedImageURI with imageURI
- * - upond end of campaign, replaces landing url with baseDomain and switches
- * background image to thumbnail
- */
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "suggested": [{
- url: "http://example.com/landing/page.html",
- imageURI: "data:image/png;base64,helloWORLD3",
- enhancedImageURI: "data:image/png;base64,helloWORLD2",
- title: "title",
- type: "affiliate",
- adgroup_name: "example",
- frecent_sites: ["example0.com"],
- }]
-});
-
-add_task(function* () {
- let origGetFrecentSitesName = DirectoryLinksProvider.getFrecentSitesName;
- DirectoryLinksProvider.getFrecentSitesName = () => "";
-
- function getData(cellNum) {
- return performOnCell(cellNum, cell => {
- if (!cell.site)
- return null;
- let siteNode = cell.site.node;
- return {
- type: siteNode.getAttribute("type"),
- thumbnail: siteNode.querySelector(".newtab-thumbnail.thumbnail").style.backgroundImage,
- enhanced: siteNode.querySelector(".enhanced-content").style.backgroundImage,
- title: siteNode.querySelector(".newtab-title").textContent,
- suggested: siteNode.getAttribute("suggested"),
- url: siteNode.querySelector(".newtab-link").getAttribute("href"),
- };
- });
- }
-
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- // load another newtab since the first may not get suggested tile
- yield* addNewTabPageTab();
- yield* checkGrid("http://example.com/landing/page.html,0,1,2,3,4,5,6,7,8,9");
- // evaluate suggested tile
- let tileData = yield getData(0);
- is(tileData.type, "affiliate", "unpinned type");
- is(tileData.thumbnail, "url(\"data:image/png;base64,helloWORLD3\")", "unpinned thumbnail");
- is(tileData.enhanced, "url(\"data:image/png;base64,helloWORLD2\")", "unpinned enhanced");
- is(tileData.suggested, "true", "has suggested set", "unpinned suggested exists");
- is(tileData.url, "http://example.com/landing/page.html", "unpinned landing page");
-
- // suggested tile should not be pinned
- is(NewTabUtils.pinnedLinks.isPinned({url: "http://example.com/landing/page.html"}), false, "suggested tile is not pinned");
-
- // pin suggested tile
- let updatedPromise = whenPagesUpdated();
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-site > .newtab-control-pin", {}, gBrowser.selectedBrowser);
- yield updatedPromise;
-
- // tile should be pinned and turned into history tile
- is(NewTabUtils.pinnedLinks.isPinned({url: "http://example.com/landing/page.html"}), true, "suggested tile is pinned");
- tileData = yield getData(0);
- is(tileData.type, "history", "pinned type");
- is(tileData.suggested, null, "no suggested attribute");
- is(tileData.url, "http://example.com/landing/page.html", "original landing page");
-
- // set pinned tile endTime into past and reload the page
- NewTabUtils.pinnedLinks._links[0].endTime = Date.now() - 1000;
- yield* addNewTabPageTab();
-
- // check that url is reset to base domain and thumbnail points to moz-page-thumb service
- is(NewTabUtils.pinnedLinks.isPinned({url: "http://example.com/"}), true, "baseDomain url is pinned");
- tileData = yield getData(0);
- is(tileData.type, "history", "type is history");
- is(tileData.title, "example.com", "title changed to baseDomain");
- is(tileData.thumbnail.indexOf("moz-page-thumb") != -1, true, "thumbnail contains moz-page-thumb");
- is(tileData.enhanced, "", "no enhanced image");
- is(tileData.url, "http://example.com/", "url points to baseDomian");
-
- DirectoryLinksProvider.getFrecentSitesName = origGetFrecentSitesName;
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug1178586.js b/browser/base/content/test/newtab/browser_newtab_bug1178586.js
deleted file mode 100644
index 84d5cb577..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug1178586.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that pinned suggested tile turns into history tile
- * and remains a history tile after a user clicks on it
- */
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "suggested": [{
- url: "http://example.com/hardlanding/page.html",
- imageURI: "data:image/png;base64,helloWORLD3",
- enhancedImageURI: "data:image/png;base64,helloWORLD2",
- title: "title",
- type: "affiliate",
- adgroup_name: "example",
- frecent_sites: ["example0.com"],
- }]
-});
-
-add_task(function* () {
- let origGetFrecentSitesName = DirectoryLinksProvider.getFrecentSitesName;
- DirectoryLinksProvider.getFrecentSitesName = () => "";
-
- function getData(cellNum) {
- return performOnCell(cellNum, cell => {
- if (!cell.site)
- return null;
- let siteNode = cell.site.node;
- return {
- type: siteNode.getAttribute("type"),
- thumbnail: siteNode.querySelector(".newtab-thumbnail.thumbnail").style.backgroundImage,
- enhanced: siteNode.querySelector(".enhanced-content").style.backgroundImage,
- title: siteNode.querySelector(".newtab-title").textContent,
- suggested: siteNode.getAttribute("suggested"),
- url: siteNode.querySelector(".newtab-link").getAttribute("href"),
- };
- });
- }
-
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- // load another newtab since the first may not get suggested tile
- yield* addNewTabPageTab();
- yield* checkGrid("http://example.com/hardlanding/page.html,0,1,2,3,4,5,6,7,8,9");
- // evaluate suggested tile
- let tileData = yield getData(0);
- is(tileData.type, "affiliate", "unpinned type");
- is(tileData.thumbnail, "url(\"data:image/png;base64,helloWORLD3\")", "unpinned thumbnail");
- is(tileData.enhanced, "url(\"data:image/png;base64,helloWORLD2\")", "unpinned enhanced");
- is(tileData.suggested, "true", "has suggested set", "unpinned suggested exists");
- is(tileData.url, "http://example.com/hardlanding/page.html", "unpinned landing page");
-
- // suggested tile should not be pinned
- is(NewTabUtils.pinnedLinks.isPinned({url: "http://example.com/hardlanding/page.html"}), false, "suggested tile is not pinned");
-
- // pin suggested tile
- let updatedPromise = whenPagesUpdated();
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-site > .newtab-control-pin", {}, gBrowser.selectedBrowser);
- yield updatedPromise;
-
- // tile should be pinned and turned into history tile
- is(NewTabUtils.pinnedLinks.isPinned({url: "http://example.com/hardlanding/page.html"}), true, "suggested tile is pinned");
- tileData = yield getData(0);
- is(tileData.type, "history", "pinned type");
- is(tileData.suggested, null, "no suggested attribute");
- is(tileData.url, "http://example.com/hardlanding/page.html", "original landing page");
-
- // click the pinned tile
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-site", {}, gBrowser.selectedBrowser);
- // add new page twice to avoid using cached version
- yield* addNewTabPageTab();
- yield* addNewTabPageTab();
-
- // check that type and suggested did not change
- tileData = yield getData(0);
- is(tileData.type, "history", "pinned type");
- is(tileData.suggested, null, "no suggested attribute");
-
- DirectoryLinksProvider.getFrecentSitesName = origGetFrecentSitesName;
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug1194895.js b/browser/base/content/test/newtab/browser_newtab_bug1194895.js
deleted file mode 100644
index c08b23185..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug1194895.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PRELOAD_PREF = "browser.newtab.preload";
-const PREF_NEWTAB_COLUMNS = "browser.newtabpage.columns";
-const PREF_NEWTAB_ROWS = "browser.newtabpage.rows";
-
-function populateDirectoryTiles() {
- let directoryTiles = [];
- let i = 0;
- while (i++ < 14) {
- directoryTiles.push({
- directoryId: i,
- url: "http://example" + i + ".com/",
- enhancedImageURI: "data:image/png;base64,helloWORLD",
- title: "dirtitle" + i,
- type: "affiliate"
- });
- }
- return directoryTiles;
-}
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "directory": populateDirectoryTiles()
-});
-
-
-add_task(function* () {
- requestLongerTimeout(4);
- let origEnhanced = NewTabUtils.allPages.enhanced;
- let origCompareLinks = NewTabUtils.links.compareLinks;
- registerCleanupFunction(() => {
- NewTabUtils.allPages.enhanced = origEnhanced;
- NewTabUtils.links.compareLinks = origCompareLinks;
- });
-
- // turn off preload to ensure grid updates on every setLinks
- yield pushPrefs([PRELOAD_PREF, false]);
- // set newtab to have three columns only
- yield pushPrefs([PREF_NEWTAB_COLUMNS, 3]);
- yield pushPrefs([PREF_NEWTAB_ROWS, 5]);
-
- yield* addNewTabPageTab();
- yield customizeNewTabPage("enhanced"); // Toggle enhanced off
-
- // Testing history tiles
-
- // two rows of tiles should always fit on any screen
- yield setLinks("0,1,2,3,4,5");
- yield* addNewTabPageTab();
-
- // should do not see scrollbar since tiles fit into visible space
- yield* checkGrid("0,1,2,3,4,5");
- let scrolling = yield hasScrollbar();
- ok(!scrolling, "no scrollbar");
-
- // add enough tiles to cause extra two rows and observe scrollbar
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8,9");
- scrolling = yield hasScrollbar();
- ok(scrolling, "document has scrollbar");
-
- // pin the last tile to make it stay at the bottom of the newtab
- yield pinCell(9);
- // block first 6 tiles, which should not remove the scroll bar
- // since the last tile is pinned in the nineth position
- for (let i = 0; i < 6; i++) {
- yield blockCell(0);
- }
- yield* addNewTabPageTab();
- yield* checkGrid("6,7,8,,,,,,,9p");
- scrolling = yield hasScrollbar();
- ok(scrolling, "document has scrollbar when tile is pinned to the last row");
-
- // unpin the site: this will move tile up and make scrollbar disappear
- yield unpinCell(9);
- yield* addNewTabPageTab();
- yield* checkGrid("6,7,8,9");
- scrolling = yield hasScrollbar();
- ok(!scrolling, "no scrollbar when bottom row tile is unpinned");
-
- // reset everything to clean slate
- NewTabUtils.restore();
-
- // Testing directory tiles
- yield customizeNewTabPage("enhanced"); // Toggle enhanced on
-
- // setup page with no history tiles to test directory only display
- yield setLinks([]);
- yield* addNewTabPageTab();
- ok(!scrolling, "no scrollbar for directory tiles");
-
- // introduce one history tile - it should occupy the last
- // available slot at the bottom of newtab and cause scrollbar
- yield setLinks("41");
- yield* addNewTabPageTab();
- scrolling = yield hasScrollbar();
- ok(scrolling, "adding low frecency history site causes scrollbar");
-
- // set PREF_NEWTAB_ROWS to 4, that should clip off the history tile
- // and remove scroll bar
- yield pushPrefs([PREF_NEWTAB_ROWS, 4]);
- yield* addNewTabPageTab();
-
- scrolling = yield hasScrollbar();
- ok(!scrolling, "no scrollbar if history tiles falls past max rows");
-
- // restore max rows and watch scrollbar re-appear
- yield pushPrefs([PREF_NEWTAB_ROWS, 5]);
- yield* addNewTabPageTab();
- scrolling = yield hasScrollbar();
- ok(scrolling, "scrollbar is back when max rows allow for bottom history tile");
-
- // block that history tile, and watch scrollbar disappear
- yield blockCell(14);
- yield* addNewTabPageTab();
- scrolling = yield hasScrollbar();
- ok(!scrolling, "no scrollbar after bottom history tiles is blocked");
-
- // Test well-populated user history - newtab has highly-frecent history sites
- // redefine compareLinks to always choose history tiles first
- NewTabUtils.links.compareLinks = function (aLink1, aLink2) {
- if (aLink1.type == aLink2.type) {
- return aLink2.frecency - aLink1.frecency ||
- aLink2.lastVisitDate - aLink1.lastVisitDate;
- }
- if (aLink2.type == "history") {
- return 1;
- }
- return -1;
- };
-
- // add a row of history tiles, directory tiles will be clipped off, hence no scrollbar
- yield setLinks("31,32,33");
- yield* addNewTabPageTab();
- scrolling = yield hasScrollbar();
- ok(!scrolling, "no scrollbar when directory tiles follow history tiles");
-
- // fill first four rows with history tiles and observer scrollbar
- yield setLinks("30,31,32,33,34,35,36,37,38,39");
- yield* addNewTabPageTab();
- scrolling = yield hasScrollbar();
- ok(scrolling, "scrollbar appears when history tiles need extra row");
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_bug1271075.js b/browser/base/content/test/newtab/browser_newtab_bug1271075.js
deleted file mode 100644
index 723b48fc6..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug1271075.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- is(gBrowser.tabs.length, 1, "one tab is open initially");
-
- // Add a few tabs.
- let tabs = [];
- function addTab(aURL, aReferrer) {
- let tab = gBrowser.addTab(aURL, {referrerURI: aReferrer});
- tabs.push(tab);
- return BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- }
-
- yield addTab("http://mochi.test:8888/#0");
- yield addTab("http://mochi.test:8888/#1");
- yield addTab("http://mochi.test:8888/#2");
- yield addTab("http://mochi.test:8888/#3");
-
- // Create a new tab page with a "www.example.com" tile and move it to the 2nd tab position.
- yield setLinks("-1");
- yield* addNewTabPageTab();
- gBrowser.moveTabTo(gBrowser.selectedTab, 1);
-
- // Send a middle-click and confirm that the clicked site opens immediately next to the new tab page.
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-cell",
- {button: 1}, gBrowser.selectedBrowser);
-
- yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserAtIndex(2));
- is(gBrowser.getBrowserAtIndex(2).currentURI.spec, "http://example.com/",
- "Middle click opens site in a new tab immediately to the right.");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug721442.js b/browser/base/content/test/newtab/browser_newtab_bug721442.js
deleted file mode 100644
index 99bd8d930..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug721442.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks([
- {url: "http://example7.com/", title: ""},
- {url: "http://example8.com/", title: "title"},
- {url: "http://example9.com/", title: "http://example9.com/"}
- ]);
-
- yield* addNewTabPageTab();
- yield* checkGrid("7p,8p,9p,0,1,2,3,4,5");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- function checkTooltip(aIndex, aExpected, aMessage) {
- let cell = content.gGrid.cells[aIndex];
-
- let link = cell.node.querySelector(".newtab-link");
- Assert.equal(link.getAttribute("title"), aExpected, aMessage);
- }
-
- checkTooltip(0, "http://example7.com/", "1st tooltip is correct");
- checkTooltip(1, "title\nhttp://example8.com/", "2nd tooltip is correct");
- checkTooltip(2, "http://example9.com/", "3rd tooltip is correct");
- });
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_bug722273.js b/browser/base/content/test/newtab/browser_newtab_bug722273.js
deleted file mode 100644
index 5cbfcd3ff..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug722273.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const NOW = Date.now() * 1000;
-const URL = "http://fake-site.com/";
-
-var tmp = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tmp);
-
-var {Sanitizer} = tmp;
-
-add_task(function* () {
- yield promiseSanitizeHistory();
- yield promiseAddFakeVisits();
- yield* addNewTabPageTab();
-
- let cellUrl = yield performOnCell(0, cell => { return cell.site.url; });
- is(cellUrl, URL, "first site is our fake site");
-
- let updatedPromise = whenPagesUpdated();
- yield promiseSanitizeHistory();
- yield updatedPromise;
-
- let isGone = yield performOnCell(0, cell => { return cell.site == null; });
- ok(isGone, "fake site is gone");
-});
-
-function promiseAddFakeVisits() {
- let visits = [];
- for (let i = 59; i > 0; i--) {
- visits.push({
- visitDate: NOW - i * 60 * 1000000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK
- });
- }
- let place = {
- uri: makeURI(URL),
- title: "fake site",
- visits: visits
- };
- return new Promise((resolve, reject) => {
- PlacesUtils.asyncHistory.updatePlaces(place, {
- handleError: () => reject(new Error("Couldn't add visit")),
- handleResult: function () {},
- handleCompletion: function () {
- NewTabUtils.links.populateCache(function () {
- NewTabUtils.allPages.update();
- resolve();
- }, true);
- }
- });
- });
-}
-
-function promiseSanitizeHistory() {
- let s = new Sanitizer();
- s.prefDomain = "privacy.cpd.";
-
- let prefs = gPrefService.getBranch(s.prefDomain);
- prefs.setBoolPref("history", true);
- prefs.setBoolPref("downloads", false);
- prefs.setBoolPref("cache", false);
- prefs.setBoolPref("cookies", false);
- prefs.setBoolPref("formdata", false);
- prefs.setBoolPref("offlineApps", false);
- prefs.setBoolPref("passwords", false);
- prefs.setBoolPref("sessions", false);
- prefs.setBoolPref("siteSettings", false);
-
- return s.sanitize();
-}
diff --git a/browser/base/content/test/newtab/browser_newtab_bug723102.js b/browser/base/content/test/newtab/browser_newtab_bug723102.js
deleted file mode 100644
index 02282dc97..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug723102.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- // create a new tab page and hide it.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- let firstTab = gBrowser.selectedTab;
-
- yield* addNewTabPageTab();
- yield BrowserTestUtils.removeTab(firstTab);
-
- ok(NewTabUtils.allPages.enabled, "page is enabled");
- NewTabUtils.allPages.enabled = false;
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- Assert.ok(content.gGrid.node.hasAttribute("page-disabled"), "page is disabled");
- });
-
- NewTabUtils.allPages.enabled = true;
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_bug723121.js b/browser/base/content/test/newtab/browser_newtab_bug723121.js
deleted file mode 100644
index 82f45ebd5..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug723121.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function*() {
- let grid = content.gGrid;
- let cell = grid.cells[0];
- let site = cell.site.node;
- let link = site.querySelector(".newtab-link");
-
- function checkGridLocked(aLocked, aMessage) {
- Assert.equal(grid.node.hasAttribute("locked"), aLocked, aMessage);
- }
-
- function sendDragEvent(aEventType, aTarget) {
- let dataTransfer = new content.DataTransfer(aEventType, false);
- let event = content.document.createEvent("DragEvent");
- event.initDragEvent(aEventType, true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
- aTarget.dispatchEvent(event);
- }
-
- checkGridLocked(false, "grid is unlocked");
-
- sendDragEvent("dragstart", link);
- checkGridLocked(true, "grid is now locked");
-
- sendDragEvent("dragend", link);
- checkGridLocked(false, "grid isn't locked anymore");
-
- sendDragEvent("dragstart", cell.node);
- checkGridLocked(false, "grid isn't locked - dragstart was ignored");
-
- sendDragEvent("dragstart", site);
- checkGridLocked(false, "grid isn't locked - dragstart was ignored");
- });
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug725996.js b/browser/base/content/test/newtab/browser_newtab_bug725996.js
deleted file mode 100644
index e0de809c8..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug725996.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- function doDrop(data) {
- return ContentTask.spawn(gBrowser.selectedBrowser, { data: data }, function*(args) {
- let dataTransfer = new content.DataTransfer("dragstart", false);
- dataTransfer.mozSetDataAt("text/x-moz-url", args.data, 0);
- let event = content.document.createEvent("DragEvent");
- event.initDragEvent("drop", true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
-
- let target = content.gGrid.cells[0].node;
- target.dispatchEvent(event);
- });
- }
-
- yield doDrop("http://example99.com/\nblank");
- is(NewTabUtils.pinnedLinks.links[0].url, "http://example99.com/",
- "first cell is pinned and contains the dropped site");
-
- yield whenPagesUpdated();
- yield* checkGrid("99p,0,1,2,3,4,5,6,7");
-
- yield doDrop("");
- is(NewTabUtils.pinnedLinks.links[0].url, "http://example99.com/",
- "first cell is still pinned with the site we dropped before");
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_bug734043.js b/browser/base/content/test/newtab/browser_newtab_bug734043.js
deleted file mode 100644
index 02f765274..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug734043.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- content.addEventListener("error", function () {
- sendAsyncMessage("test:newtab-error", {});
- });
- });
-
- let receivedError = false;
- let mm = gBrowser.selectedBrowser.messageManager;
- mm.addMessageListener("test:newtab-error", function onResponse(message) {
- mm.removeMessageListener("test:newtab-error", onResponse);
- ok(false, "Error event happened");
- receivedError = true;
- });
-
- let pagesUpdatedPromise = whenPagesUpdated();
-
- for (let i = 0; i < 3; i++) {
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-control-block", {}, gBrowser.selectedBrowser);
- }
-
- yield pagesUpdatedPromise;
-
- ok(!receivedError, "we got here without any errors");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug735987.js b/browser/base/content/test/newtab/browser_newtab_bug735987.js
deleted file mode 100644
index 2ae541c70..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug735987.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield* simulateExternalDrop(1);
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-
- yield blockCell(1);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield* simulateExternalDrop(1);
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-
- // Simulate a restart and force the next about:newtab
- // instance to read its data from the storage again.
- NewTabUtils.blockedLinks.resetCache();
-
- // Update all open pages, e.g. preloaded ones.
- NewTabUtils.allPages.update();
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-
- yield blockCell(1);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug752841.js b/browser/base/content/test/newtab/browser_newtab_bug752841.js
deleted file mode 100644
index e3faad13f..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug752841.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PREF_NEWTAB_ROWS = "browser.newtabpage.rows";
-const PREF_NEWTAB_COLUMNS = "browser.newtabpage.columns";
-
-function getCellsCount()
-{
- return ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- return content.gGrid.cells.length;
- });
-}
-
-add_task(function* () {
- let testValues = [
- {row: 0, column: 0},
- {row: -1, column: -1},
- {row: -1, column: 0},
- {row: 0, column: -1},
- {row: 2, column: 4},
- {row: 2, column: 5},
- ];
-
- // Expected length of grid
- let expectedValues = [1, 1, 1, 1, 8, 10];
-
- // Values before setting new pref values (15 is the default value -> 5 x 3)
- let previousValues = [15, 1, 1, 1, 1, 8];
-
- yield* addNewTabPageTab();
- let existingTab = gBrowser.selectedTab;
-
- for (let i = 0; i < expectedValues.length; i++) {
- let existingTabGridLength = yield getCellsCount();
- is(existingTabGridLength, previousValues[i],
- "Grid length of existing page before update is correctly.");
-
- yield pushPrefs([PREF_NEWTAB_ROWS, testValues[i].row]);
- yield pushPrefs([PREF_NEWTAB_COLUMNS, testValues[i].column]);
-
- existingTabGridLength = yield getCellsCount();
- is(existingTabGridLength, expectedValues[i],
- "Existing page grid is updated correctly.");
-
- yield* addNewTabPageTab();
- let newTab = gBrowser.selectedTab;
- let newTabGridLength = yield getCellsCount();
- is(newTabGridLength, expectedValues[i],
- "New page grid is updated correctly.");
-
- yield BrowserTestUtils.removeTab(newTab);
- }
-
- gBrowser.removeTab(existingTab);
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_bug765628.js b/browser/base/content/test/newtab/browser_newtab_bug765628.js
deleted file mode 100644
index 25afd32a9..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug765628.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function*() {
- const BAD_DRAG_DATA = "javascript:alert('h4ck0rz');\nbad stuff";
- const GOOD_DRAG_DATA = "http://example99.com/\nsite 99";
-
- function sendDropEvent(aCellIndex, aDragData) {
- let dataTransfer = new content.DataTransfer("dragstart", false);
- dataTransfer.mozSetDataAt("text/x-moz-url", aDragData, 0);
- let event = content.document.createEvent("DragEvent");
- event.initDragEvent("drop", true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
-
- let target = content.gGrid.cells[aCellIndex].node;
- target.dispatchEvent(event);
- }
-
- sendDropEvent(0, BAD_DRAG_DATA);
- sendDropEvent(1, GOOD_DRAG_DATA);
- });
-
- yield whenPagesUpdated();
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug876313.js b/browser/base/content/test/newtab/browser_newtab_bug876313.js
deleted file mode 100644
index 1c0b0f501..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug876313.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * This test makes sure that the changes made by unpinning
- * a site are actually written to NewTabUtils' storage.
- */
-add_task(function* () {
- // Second cell is pinned with page #99.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",99");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-
- // Unpin the second cell's site.
- yield unpinCell(1);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- // Clear the pinned cache to force NewTabUtils to read the pref again.
- NewTabUtils.pinnedLinks.resetCache();
- NewTabUtils.allPages.update();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug991111.js b/browser/base/content/test/newtab/browser_newtab_bug991111.js
deleted file mode 100644
index 37aa8213b..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug991111.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- // set max rows to 1, to avoid scroll events by clicking middle button
- yield pushPrefs(["browser.newtabpage.rows", 1]);
- yield setLinks("-1");
- yield* addNewTabPageTab();
- // we need a second newtab to honor max rows
- yield* addNewTabPageTab();
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {index: 0}, function* (args) {
- let {site} = content.wrappedJSObject.gGrid.cells[args.index];
-
- let origOnClick = site.onClick;
- site.onClick = e => {
- origOnClick.call(site, e);
- sendAsyncMessage("test:clicked-on-cell", {});
- };
- });
-
- let mm = gBrowser.selectedBrowser.messageManager;
- let messagePromise = new Promise(resolve => {
- mm.addMessageListener("test:clicked-on-cell", function onResponse(message) {
- mm.removeMessageListener("test:clicked-on-cell", onResponse);
- resolve();
- });
- });
-
- // Send a middle-click and make sure it happened
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-cell",
- {button: 1}, gBrowser.selectedBrowser);
- yield messagePromise;
- ok(true, "middle click triggered click listener");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug991210.js b/browser/base/content/test/newtab/browser_newtab_bug991210.js
deleted file mode 100644
index 367c49f5c..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug991210.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- // turn off preload to ensure that a newtab page loads
- yield pushPrefs(["browser.newtab.preload", false]);
-
- // add a test provider that waits for load
- let afterLoadProvider = {
- getLinks: function(callback) {
- this.callback = callback;
- },
- addObserver: function() {},
- };
- NewTabUtils.links.addProvider(afterLoadProvider);
-
- // wait until about:newtab loads before calling provider callback
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab");
-
- afterLoadProvider.callback([]);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let {_cellHeight, _cellWidth, node} = content.gGrid;
- Assert.notEqual(_cellHeight, null, "grid has a computed cell height");
- Assert.notEqual(_cellWidth, null, "grid has a computed cell width");
- let {height, maxHeight, maxWidth} = node.style;
- Assert.notEqual(height, "", "grid has a computed grid height");
- Assert.notEqual(maxHeight, "", "grid has a computed grid max-height");
- Assert.notEqual(maxWidth, "", "grid has a computed grid max-width");
- });
-
- // restore original state
- NewTabUtils.links.removeProvider(afterLoadProvider);
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_bug998387.js b/browser/base/content/test/newtab/browser_newtab_bug998387.js
deleted file mode 100644
index 30424c2e5..000000000
--- a/browser/base/content/test/newtab/browser_newtab_bug998387.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- // set max rows to 1, to avoid scroll events by clicking middle button
- yield pushPrefs(["browser.newtabpage.rows", 1]);
- yield setLinks("0");
- yield* addNewTabPageTab();
- // we need a second newtab to honor max rows
- yield* addNewTabPageTab();
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {index: 0}, function* (args) {
- let {site} = content.wrappedJSObject.gGrid.cells[args.index];
-
- let origOnClick = site.onClick;
- site.onClick = e => {
- origOnClick.call(site, e);
- sendAsyncMessage("test:clicked-on-cell", {});
- };
- });
-
- let mm = gBrowser.selectedBrowser.messageManager;
- let messagePromise = new Promise(resolve => {
- mm.addMessageListener("test:clicked-on-cell", function onResponse(message) {
- mm.removeMessageListener("test:clicked-on-cell", onResponse);
- resolve();
- });
- });
-
- // Send a middle-click and make sure it happened
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-control-block",
- {button: 1}, gBrowser.selectedBrowser);
-
- yield messagePromise;
- ok(true, "middle click triggered click listener");
-
- // Make sure the cell didn't actually get blocked
- yield* checkGrid("0");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_disable.js b/browser/base/content/test/newtab/browser_newtab_disable.js
deleted file mode 100644
index 58b9a18af..000000000
--- a/browser/base/content/test/newtab/browser_newtab_disable.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that the 'New Tab Page' feature can be disabled if the
- * decides not to use it.
- */
-add_task(function* () {
- // create a new tab page and hide it.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- let firstTab = yield* addNewTabPageTab();
-
- function isGridDisabled(browser = gBrowser.selectedBrowser)
- {
- return ContentTask.spawn(browser, {}, function*() {
- return content.gGrid.node.hasAttribute("page-disabled");
- });
- }
-
- let isDisabled = yield isGridDisabled();
- ok(!isDisabled, "page is not disabled");
-
- NewTabUtils.allPages.enabled = false;
-
- isDisabled = yield isGridDisabled();
- ok(isDisabled, "page is disabled");
-
- // create a second new tab page and make sure it's disabled. enable it
- // again and check if the former page gets enabled as well.
- yield* addNewTabPageTab();
- isDisabled = yield isGridDisabled(firstTab.linkedBrowser);
- ok(isDisabled, "page is disabled");
-
- // check that no sites have been rendered
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function*() {
- Assert.equal(content.document.querySelectorAll(".site").length, 0,
- "no sites have been rendered");
- });
-
- NewTabUtils.allPages.enabled = true;
-
- isDisabled = yield isGridDisabled();
- ok(!isDisabled, "page is not disabled");
-
- isDisabled = yield isGridDisabled(firstTab.linkedBrowser);
- ok(!isDisabled, "old page is not disabled");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_drag_drop.js b/browser/base/content/test/newtab/browser_newtab_drag_drop.js
deleted file mode 100644
index da9d89de7..000000000
--- a/browser/base/content/test/newtab/browser_newtab_drag_drop.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that dragging and dropping sites works as expected.
- * Sites contained in the grid need to shift around to indicate the result
- * of the drag-and-drop operation. If the grid is full and we're dragging
- * a new site into it another one gets pushed out.
- */
-add_task(function* () {
- requestLongerTimeout(2);
- yield* addNewTabPageTab();
-
- // test a simple drag-and-drop scenario
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield doDragEvent(0, 1);
- yield* checkGrid("1,0p,2,3,4,5,6,7,8");
-
- // drag a cell to its current cell and make sure it's not pinned afterwards
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- yield doDragEvent(0, 0);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- // ensure that pinned pages aren't moved if that's not necessary
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",1,2");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1p,2p,3,4,5,6,7,8");
-
- yield doDragEvent(0, 3);
- yield* checkGrid("3,1p,2p,0p,4,5,6,7,8");
-
- // pinned sites should always be moved around as blocks. if a pinned site is
- // moved around, neighboring pinned are affected as well
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("0,1");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0p,1p,2,3,4,5,6,7,8");
-
- yield doDragEvent(2, 0);
- yield* checkGrid("2p,0p,1p,3,4,5,6,7,8");
-
- // pinned sites should not be pushed out of the grid (unless there are only
- // pinned ones left on the grid)
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",,,,,,,7,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7p,8p");
-
- yield doDragEvent(2, 5);
- yield* checkGrid("0,1,3,4,5,2p,6,7p,8p");
-
- // make sure that pinned sites are re-positioned correctly
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("0,1,2,,,5");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0p,1p,2p,3,4,5p,6,7,8");
-
- yield doDragEvent(0, 4);
- yield* checkGrid("3,1p,2p,4,0p,5p,6,7,8");
-});
-
-function doDragEvent(sourceIndex, dropIndex) {
- return ContentTask.spawn(gBrowser.selectedBrowser,
- { sourceIndex: sourceIndex, dropIndex: dropIndex }, function*(args) {
- let dataTransfer = new content.DataTransfer("dragstart", false);
- let event = content.document.createEvent("DragEvent");
- event.initDragEvent("dragstart", true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
-
- let target = content.gGrid.cells[args.sourceIndex].site.node;
- target.dispatchEvent(event);
-
- event = content.document.createEvent("DragEvent");
- event.initDragEvent("drop", true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
-
- target = content.gGrid.cells[args.dropIndex].node;
- target.dispatchEvent(event);
- });
-}
diff --git a/browser/base/content/test/newtab/browser_newtab_drag_drop_ext.js b/browser/base/content/test/newtab/browser_newtab_drag_drop_ext.js
deleted file mode 100644
index 4e7b062cb..000000000
--- a/browser/base/content/test/newtab/browser_newtab_drag_drop_ext.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-const PREF_NEWTAB_COLUMNS = "browser.newtabpage.columns";
-
-/*
- * These tests make sure that dragging and dropping sites works as expected.
- * Sites contained in the grid need to shift around to indicate the result
- * of the drag-and-drop operation. If the grid is full and we're dragging
- * a new site into it another one gets pushed out.
- * This is a continuation of browser_newtab_drag_drop.js
- * to decrease test run time, focusing on external sites.
- */
- add_task(function* () {
- yield* addNewTabPageTab();
-
- // drag a new site onto the very first cell
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",,,,,,,7,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7p,8p");
-
- yield* simulateExternalDrop(0);
- yield* checkGrid("99p,0,1,2,3,4,5,7p,8p");
-
- // drag a new site onto the grid and make sure that pinned cells don't get
- // pushed out
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",,,,,,,7,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7p,8p");
-
- // force the grid to be small enough that a pinned cell could be pushed out
- yield pushPrefs([PREF_NEWTAB_COLUMNS, 3]);
- yield* simulateExternalDrop(5);
- yield* checkGrid("0,1,2,3,4,99p,5,7p,8p");
-
- // drag a new site beneath a pinned cell and make sure the pinned cell is
- // not moved
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",,,,,,,,8");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1,2,3,4,5,6,7,8p");
-
- yield* simulateExternalDrop(5);
- yield* checkGrid("0,1,2,3,4,99p,5,6,8p");
-
- // drag a new site onto a block of pinned sites and make sure they're shifted
- // around accordingly
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("0,1,2,,,,,,");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0p,1p,2p");
-
- yield* simulateExternalDrop(1);
- yield* checkGrid("0p,99p,1p,2p,3,4,5,6,7");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_drop_preview.js b/browser/base/content/test/newtab/browser_newtab_drop_preview.js
deleted file mode 100644
index f9e37f629..000000000
--- a/browser/base/content/test/newtab/browser_newtab_drop_preview.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests ensure that the drop preview correctly arranges sites when
- * dragging them around.
- */
-add_task(function* () {
- yield* addNewTabPageTab();
-
- // the first three sites are pinned - make sure they're re-arranged correctly
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("0,1,2,,,5");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0p,1p,2p,3,4,5p,6,7,8");
-
- let foundSites = yield ContentTask.spawn(gWindow.gBrowser.selectedBrowser, {}, function*() {
- let cells = content.gGrid.cells;
- content.gDrag._draggedSite = cells[0].site;
- let sites = content.gDropPreview.rearrange(cells[4]);
- content.gDrag._draggedSite = null;
-
- sites = sites.slice(0, 9);
- return sites.map(function (aSite) {
- if (!aSite)
- return "";
-
- let pinned = aSite.isPinned();
- if (pinned != aSite.node.hasAttribute("pinned")) {
- Assert.ok(false, "invalid state (site.isPinned() != site[pinned])");
- }
-
- return aSite.url.replace(/^http:\/\/example(\d+)\.com\/$/, "$1") + (pinned ? "p" : "");
- });
- });
-
- let expectedSites = "3,1p,2p,4,0p,5p,6,7,8"
- is(foundSites, expectedSites, "grid status = " + expectedSites);
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_enhanced.js b/browser/base/content/test/newtab/browser_newtab_enhanced.js
deleted file mode 100644
index 5ac07ce55..000000000
--- a/browser/base/content/test/newtab/browser_newtab_enhanced.js
+++ /dev/null
@@ -1,228 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-const PRELOAD_PREF = "browser.newtab.preload";
-
-var suggestedLink = {
- url: "http://example1.com/2",
- imageURI: "data:image/png;base64,helloWORLD3",
- title: "title2",
- type: "affiliate",
- adgroup_name: "Technology",
- frecent_sites: ["classroom.google.com", "codeacademy.org", "codecademy.com", "codeschool.com", "codeyear.com", "elearning.ut.ac.id", "how-to-build-websites.com", "htmlcodetutorial.com", "htmldog.com", "htmlplayground.com", "learn.jquery.com", "quackit.com", "roseindia.net", "teamtreehouse.com", "tizag.com", "tutorialspoint.com", "udacity.com", "w3schools.com", "webdevelopersnotes.com"]
-};
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "enhanced": [{
- url: "http://example.com/",
- enhancedImageURI: "data:image/png;base64,helloWORLD",
- title: "title",
- type: "organic",
- }],
- "directory": [{
- url: "http://example1.com/",
- enhancedImageURI: "data:image/png;base64,helloWORLD2",
- title: "title1",
- type: "organic"
- }],
- "suggested": [suggestedLink]
-});
-
-add_task(function* () {
- let origEnhanced = NewTabUtils.allPages.enhanced;
- registerCleanupFunction(() => {
- NewTabUtils.allPages.enhanced = origEnhanced;
- });
-
- yield pushPrefs([PRELOAD_PREF, false]);
-
- function getData(cellNum) {
- return performOnCell(cellNum, cell => {
- if (!cell.site)
- return null;
- let siteNode = cell.site.node;
- return {
- type: siteNode.getAttribute("type"),
- enhanced: siteNode.querySelector(".enhanced-content").style.backgroundImage,
- title: siteNode.querySelector(".newtab-title").textContent,
- suggested: siteNode.querySelector(".newtab-suggested").innerHTML
- };
- });
- }
-
- // Make the page have a directory link, enhanced link, and history link
- yield setLinks("-1");
-
- // Test with enhanced = false
- yield* addNewTabPageTab();
- yield customizeNewTabPage("classic");
- yield customizeNewTabPage("enhanced"); // Toggle enhanced off
- let {type, enhanced, title, suggested} = yield getData(0);
- isnot(type, "enhanced", "history link is not enhanced");
- is(enhanced, "", "history link has no enhanced image");
- is(title, "example.com");
- is(suggested, "", "There is no suggested explanation");
-
- let data = yield getData(1);
- is(data, null, "there is only one link and it's a history link");
-
- // Test with enhanced = true
- yield* addNewTabPageTab();
- yield customizeNewTabPage("enhanced"); // Toggle enhanced on
- ({type, enhanced, title, suggested} = yield getData(0));
- is(type, "organic", "directory link is organic");
- isnot(enhanced, "", "directory link has enhanced image");
- is(title, "title1");
- is(suggested, "", "There is no suggested explanation");
-
- ({type, enhanced, title, suggested} = yield getData(1));
- is(type, "enhanced", "history link is enhanced");
- isnot(enhanced, "", "history link has enhanced image");
- is(title, "title");
- is(suggested, "", "There is no suggested explanation");
-
- data = yield getData(2);
- is(data, null, "there are only 2 links, directory and enhanced history");
-
- // Test with a pinned link
- setPinnedLinks("-1");
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- is(type, "enhanced", "pinned history link is enhanced");
- isnot(enhanced, "", "pinned history link has enhanced image");
- is(title, "title");
- is(suggested, "", "There is no suggested explanation");
-
- ({type, enhanced, title, suggested} = yield getData(1));
- is(type, "organic", "directory link is organic");
- isnot(enhanced, "", "directory link has enhanced image");
- is(title, "title1");
- is(suggested, "", "There is no suggested explanation");
-
- data = yield getData(2);
- is(data, null, "directory link pushed out by pinned history link");
-
- // Test pinned link with enhanced = false
- yield* addNewTabPageTab();
- yield customizeNewTabPage("enhanced"); // Toggle enhanced off
- ({type, enhanced, title, suggested} = yield getData(0));
- isnot(type, "enhanced", "history link is not enhanced");
- is(enhanced, "", "history link has no enhanced image");
- is(title, "example.com");
- is(suggested, "", "There is no suggested explanation");
-
- data = yield getData(1);
- is(data, null, "directory link still pushed out by pinned history link");
-
- yield unpinCell(0);
-
-
-
- // Test that a suggested tile is not enhanced by a directory tile
- NewTabUtils.isTopPlacesSite = () => true;
- yield setLinks("-1,2,3,4,5,6,7,8");
-
- // Test with enhanced = false
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- isnot(type, "enhanced", "history link is not enhanced");
- is(enhanced, "", "history link has no enhanced image");
- is(title, "example.com");
- is(suggested, "", "There is no suggested explanation");
-
- data = yield getData(7);
- isnot(data, null, "there are 8 history links");
- data = yield getData(8);
- is(data, null, "there are 8 history links");
-
-
- // Test with enhanced = true
- yield* addNewTabPageTab();
- yield customizeNewTabPage("enhanced");
-
- // Suggested link was not enhanced by directory link with same domain
- ({type, enhanced, title, suggested} = yield getData(0));
- is(type, "affiliate", "suggested link is affiliate");
- is(enhanced, "", "suggested link has no enhanced image");
- is(title, "title2");
- ok(suggested.indexOf("Suggested for <strong> Technology </strong> visitors") > -1, "Suggested for 'Technology'");
-
- // Enhanced history link shows up second
- ({type, enhanced, title, suggested} = yield getData(1));
- is(type, "enhanced", "pinned history link is enhanced");
- isnot(enhanced, "", "pinned history link has enhanced image");
- is(title, "title");
- is(suggested, "", "There is no suggested explanation");
-
- data = yield getData(9);
- is(data, null, "there is a suggested link followed by an enhanced history link and the remaining history links");
-
-
-
- // Test no override category/adgroup name.
- let linksChangedPromise = watchLinksChangeOnce();
- yield pushPrefs([PREF_NEWTAB_DIRECTORYSOURCE,
- "data:application/json," + JSON.stringify({"suggested": [suggestedLink]})]);
- yield linksChangedPromise;
-
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- Cu.reportError("SUGGEST " + suggested);
- ok(suggested.indexOf("Suggested for <strong> Technology </strong> visitors") > -1, "Suggested for 'Technology'");
-
-
- // Test server provided explanation string.
- suggestedLink.explanation = "Suggested for %1$S enthusiasts who visit sites like %2$S";
- linksChangedPromise = watchLinksChangeOnce();
- yield pushPrefs([PREF_NEWTAB_DIRECTORYSOURCE,
- "data:application/json," + encodeURIComponent(JSON.stringify({"suggested": [suggestedLink]}))]);
- yield linksChangedPromise;
-
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- Cu.reportError("SUGGEST " + suggested);
- ok(suggested.indexOf("Suggested for <strong> Technology </strong> enthusiasts who visit sites like <strong> classroom.google.com </strong>") > -1, "Suggested for 'Technology' enthusiasts");
-
-
- // Test server provided explanation string with category override.
- suggestedLink.adgroup_name = "webdev education";
- linksChangedPromise = watchLinksChangeOnce();
- yield pushPrefs([PREF_NEWTAB_DIRECTORYSOURCE,
- "data:application/json," + encodeURIComponent(JSON.stringify({"suggested": [suggestedLink]}))]);
- yield linksChangedPromise;
-
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- Cu.reportError("SUGGEST " + suggested);
- ok(suggested.indexOf("Suggested for <strong> webdev education </strong> enthusiasts who visit sites like <strong> classroom.google.com </strong>") > -1, "Suggested for 'webdev education' enthusiasts");
-
-
-
- // Test with xml entities in category name
- suggestedLink.url = "http://example1.com/3";
- suggestedLink.adgroup_name = ">angles< & \"quotes\'";
- linksChangedPromise = watchLinksChangeOnce();
- yield pushPrefs([PREF_NEWTAB_DIRECTORYSOURCE,
- "data:application/json," + encodeURIComponent(JSON.stringify({"suggested": [suggestedLink]}))]);
- yield linksChangedPromise;
-
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- Cu.reportError("SUGGEST " + suggested);
- ok(suggested.indexOf("Suggested for <strong> &gt;angles&lt; &amp; \"quotes\' </strong> enthusiasts who visit sites like <strong> classroom.google.com </strong>") > -1, "Suggested for 'xml entities' enthusiasts");
-
-
- // Test with xml entities in explanation.
- suggestedLink.explanation = "Testing junk explanation &<>\"'";
- linksChangedPromise = watchLinksChangeOnce();
- yield pushPrefs([PREF_NEWTAB_DIRECTORYSOURCE,
- "data:application/json," + encodeURIComponent(JSON.stringify({"suggested": [suggestedLink]}))]);
- yield linksChangedPromise;
-
- yield* addNewTabPageTab();
- ({type, enhanced, title, suggested} = yield getData(0));
- Cu.reportError("SUGGEST " + suggested);
- ok(suggested.indexOf("Testing junk explanation &amp;&lt;&gt;\"'") > -1, "Junk test");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_focus.js b/browser/base/content/test/newtab/browser_newtab_focus.js
deleted file mode 100644
index ae0dd8d29..000000000
--- a/browser/base/content/test/newtab/browser_newtab_focus.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that focusing the 'New Tab Page' works as expected.
- */
-add_task(function* () {
- yield pushPrefs(["accessibility.tabfocus", 7]);
-
- // Focus count in new tab page.
- // 30 = 9 * 3 + 3 = 9 sites, each with link, pin and remove buttons; search
- // bar; search button; and toggle button. Additionaly there may or may not be
- // a scroll bar caused by fix to 1180387, which will eat an extra focus
- let FOCUS_COUNT = 30;
-
- // Create a new tab page.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("");
-
- yield* addNewTabPageTab();
- gURLBar.focus();
-
- // Count the focus with the enabled page.
- countFocus(FOCUS_COUNT);
-
- // Disable page and count the focus with the disabled page.
- NewTabUtils.allPages.enabled = false;
-
- countFocus(4);
-
- NewTabUtils.allPages.enabled = true;
-});
-
-/**
- * Focus the urlbar and count how many focus stops to return again to the urlbar.
- */
-function countFocus(aExpectedCount) {
- let focusCount = 0;
- do {
- EventUtils.synthesizeKey("VK_TAB", {});
- if (document.activeElement == gBrowser.selectedBrowser) {
- focusCount++;
- }
- } while (document.activeElement != gURLBar.inputField);
-
- ok(focusCount == aExpectedCount || focusCount == (aExpectedCount + 1),
- "Validate focus count in the new tab page.");
-}
diff --git a/browser/base/content/test/newtab/browser_newtab_perwindow_private_browsing.js b/browser/base/content/test/newtab/browser_newtab_perwindow_private_browsing.js
deleted file mode 100644
index b330bec13..000000000
--- a/browser/base/content/test/newtab/browser_newtab_perwindow_private_browsing.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests ensure that all changes made to the new tab page in private
- * browsing mode are discarded after switching back to normal mode again.
- * The private browsing mode should start with the current grid shown in normal
- * mode.
- */
-
-add_task(function* () {
- // prepare the grid
- yield testOnWindow(undefined);
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
-
- yield* addNewTabPageTab();
- yield pinCell(0);
- yield* checkGrid("0p,1,2,3,4,5,6,7,8");
-
- // open private window
- yield testOnWindow({private: true});
-
- yield* addNewTabPageTab();
- yield* checkGrid("0p,1,2,3,4,5,6,7,8");
-
- // modify the grid while we're in pb mode
- yield blockCell(1);
- yield* checkGrid("0p,2,3,4,5,6,7,8");
-
- yield unpinCell(0);
- yield* checkGrid("0,2,3,4,5,6,7,8");
-
- // open normal window
- yield testOnWindow(undefined);
-
- // check that the grid is the same as before entering pb mode
- yield* addNewTabPageTab();
- yield* checkGrid("0,2,3,4,5,6,7,8")
-});
-
-var windowsToClose = [];
-function* testOnWindow(options) {
- let newWindowPromise = BrowserTestUtils.waitForNewWindow();
- var win = OpenBrowserWindow(options);
- windowsToClose.push(win);
- gWindow = win;
- yield newWindowPromise;
-}
-
-registerCleanupFunction(function () {
- gWindow = window;
- windowsToClose.forEach(function(win) {
- win.close();
- });
-});
-
diff --git a/browser/base/content/test/newtab/browser_newtab_reflow_load.js b/browser/base/content/test/newtab/browser_newtab_reflow_load.js
deleted file mode 100644
index b8a24595e..000000000
--- a/browser/base/content/test/newtab/browser_newtab_reflow_load.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const FRAME_SCRIPT = getRootDirectory(gTestPath) + "content-reflows.js";
-const ADDITIONAL_WAIT_MS = 2000;
-
-/*
- * Ensure that loading about:newtab doesn't cause uninterruptible reflows.
- */
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- return gBrowser.selectedTab = gBrowser.addTab("about:blank", {animate: false});
- }, false);
-
- let browser = gBrowser.selectedBrowser;
- let mm = browser.messageManager;
- mm.loadFrameScript(FRAME_SCRIPT, true);
- mm.addMessageListener("newtab-reflow", ({data: stack}) => {
- ok(false, `unexpected uninterruptible reflow ${stack}`);
- });
-
- let browserLoadedPromise = BrowserTestUtils.waitForEvent(browser, "load", true);
- browser.loadURI("about:newtab");
- yield browserLoadedPromise;
-
- // Wait some more to catch sync reflows after the page has loaded.
- yield new Promise(resolve => {
- setTimeout(resolve, ADDITIONAL_WAIT_MS);
- });
-
- // Clean up.
- gBrowser.removeCurrentTab({animate: false});
-
- ok(true, "Each test requires at least one pass, fail or todo so here is a pass.");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_reportLinkAction.js b/browser/base/content/test/newtab/browser_newtab_reportLinkAction.js
deleted file mode 100644
index 24e1be369..000000000
--- a/browser/base/content/test/newtab/browser_newtab_reportLinkAction.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PRELOAD_PREF = "browser.newtab.preload";
-
-gDirectorySource = "data:application/json," + JSON.stringify({
- "directory": [{
- url: "http://example.com/organic",
- type: "organic"
- }, {
- url: "http://localhost/sponsored",
- type: "sponsored"
- }]
-});
-
-add_task(function* () {
- yield pushPrefs([PRELOAD_PREF, false]);
-
- let originalReportSitesAction = DirectoryLinksProvider.reportSitesAction;
- registerCleanupFunction(() => {
- DirectoryLinksProvider.reportSitesAction = originalReportSitesAction;
- });
-
- let expected = {};
-
- function expectReportSitesAction() {
- return new Promise(resolve => {
- DirectoryLinksProvider.reportSitesAction = function(sites, action, siteIndex) {
- let {link} = sites[siteIndex];
- is(link.type, expected.type, "got expected type");
- is(action, expected.action, "got expected action");
- is(NewTabUtils.pinnedLinks.isPinned(link), expected.pinned, "got expected pinned");
- resolve();
- }
- });
- }
-
- // Test that the last visible site (index 1) is reported
- let reportSitesPromise = expectReportSitesAction();
- expected.type = "sponsored";
- expected.action = "view";
- expected.pinned = false;
- yield* addNewTabPageTab();
- yield reportSitesPromise;
-
- // Click the pin button on the link in the 1th tile spot
- expected.action = "pin";
- // tiles become "history" when pinned
- expected.type = "history";
- expected.pinned = true;
- let pagesUpdatedPromise = whenPagesUpdated();
- reportSitesPromise = expectReportSitesAction();
-
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-cell + .newtab-cell .newtab-control-pin", {}, gBrowser.selectedBrowser);
- yield pagesUpdatedPromise;
- yield reportSitesPromise;
-
- // Unpin that link
- expected.action = "unpin";
- expected.pinned = false;
- pagesUpdatedPromise = whenPagesUpdated();
- reportSitesPromise = expectReportSitesAction();
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-cell + .newtab-cell .newtab-control-pin", {}, gBrowser.selectedBrowser);
- yield pagesUpdatedPromise;
- yield reportSitesPromise;
-
- // Block the site in the 0th tile spot
- expected.type = "organic";
- expected.action = "block";
- expected.pinned = false;
- pagesUpdatedPromise = whenPagesUpdated();
- reportSitesPromise = expectReportSitesAction();
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-site .newtab-control-block", {}, gBrowser.selectedBrowser);
- yield pagesUpdatedPromise;
- yield reportSitesPromise;
-
- // Click the 1th link now in the 0th tile spot
- expected.type = "history";
- expected.action = "click";
- reportSitesPromise = expectReportSitesAction();
- yield BrowserTestUtils.synthesizeMouseAtCenter(".newtab-site", {}, gBrowser.selectedBrowser);
- yield reportSitesPromise;
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_search.js b/browser/base/content/test/newtab/browser_newtab_search.js
deleted file mode 100644
index 19ed4ba74..000000000
--- a/browser/base/content/test/newtab/browser_newtab_search.js
+++ /dev/null
@@ -1,247 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// See browser/components/search/test/browser_*_behavior.js for tests of actual
-// searches.
-
-Cu.import("resource://gre/modules/Task.jsm");
-
-const ENGINE_NO_LOGO = {
- name: "searchEngineNoLogo.xml",
- numLogos: 0,
-};
-
-const ENGINE_FAVICON = {
- name: "searchEngineFavicon.xml",
- logoPrefix1x: "data:image/png;base64,AAABAAIAICAAAAEAIACoEAAAJgAAABAQAAABACAAaAQAAM4QAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAATCwAAEwsA",
- numLogos: 1,
-};
-ENGINE_FAVICON.logoPrefix2x = ENGINE_FAVICON.logoPrefix1x;
-
-const ENGINE_1X_LOGO = {
- name: "searchEngine1xLogo.xml",
- logoPrefix1x: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAaCAIAAABn3KYmAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADEw",
- numLogos: 1,
-};
-ENGINE_1X_LOGO.logoPrefix2x = ENGINE_1X_LOGO.logoPrefix1x;
-
-const ENGINE_2X_LOGO = {
- name: "searchEngine2xLogo.xml",
- logoPrefix2x: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAAA0CAIAAADJ8nfCAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADMU",
- numLogos: 1,
-};
-ENGINE_2X_LOGO.logoPrefix1x = ENGINE_2X_LOGO.logoPrefix2x;
-
-const ENGINE_1X_2X_LOGO = {
- name: "searchEngine1x2xLogo.xml",
- logoPrefix1x: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAaCAIAAABn3KYmAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADIG",
- logoPrefix2x: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAAA0CAIAAADJ8nfCAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADMo",
- numLogos: 2,
-};
-
-const ENGINE_SUGGESTIONS = {
- name: "searchSuggestionEngine.xml",
- numLogos: 0,
-};
-
-// The test has an expected search event queue and a search event listener.
-// Search events that are expected to happen are added to the queue, and the
-// listener consumes the queue and ensures that each event it receives is at
-// the head of the queue.
-let gExpectedSearchEventQueue = [];
-let gExpectedSearchEventResolver = null;
-
-let gNewEngines = [];
-
-add_task(function* () {
- let oldCurrentEngine = Services.search.currentEngine;
-
- yield* addNewTabPageTab();
-
- // The tab is removed at the end of the test, so there's no need to remove
- // this listener at the end of the test.
- info("Adding search event listener");
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- const SERVICE_EVENT_NAME = "ContentSearchService";
- content.addEventListener(SERVICE_EVENT_NAME, function (event) {
- sendAsyncMessage("test:search-event", { eventType: event.detail.type });
- });
- });
-
- let mm = gBrowser.selectedBrowser.messageManager;
- mm.addMessageListener("test:search-event", function (message) {
- let eventType = message.data.eventType;
- if (!gExpectedSearchEventResolver) {
- ok(false, "Got search event " + eventType + " with no promise assigned");
- }
-
- let expectedEventType = gExpectedSearchEventQueue.shift();
- is(eventType, expectedEventType, "Got expected search event " + expectedEventType);
- if (!gExpectedSearchEventQueue.length) {
- gExpectedSearchEventResolver();
- gExpectedSearchEventResolver = null;
- }
- });
-
- // Add the engine without any logos and switch to it.
- let noLogoEngine = yield promiseNewSearchEngine(ENGINE_NO_LOGO);
- let searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = noLogoEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_NO_LOGO);
-
- // Add the engine with favicon and switch to it.
- let faviconEngine = yield promiseNewSearchEngine(ENGINE_FAVICON);
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = faviconEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_FAVICON);
-
- // Add the engine with a 1x-DPI logo and switch to it.
- let logo1xEngine = yield promiseNewSearchEngine(ENGINE_1X_LOGO);
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = logo1xEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_1X_LOGO);
-
- // Add the engine with a 2x-DPI logo and switch to it.
- let logo2xEngine = yield promiseNewSearchEngine(ENGINE_2X_LOGO);
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = logo2xEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_2X_LOGO);
-
- // Add the engine with 1x- and 2x-DPI logos and switch to it.
- let logo1x2xEngine = yield promiseNewSearchEngine(ENGINE_1X_2X_LOGO);
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = logo1x2xEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_1X_2X_LOGO);
-
- // Add the engine that provides search suggestions and switch to it.
- let suggestionEngine = yield promiseNewSearchEngine(ENGINE_SUGGESTIONS);
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = suggestionEngine;
- yield searchEventsPromise;
- yield* checkCurrentEngine(ENGINE_SUGGESTIONS);
-
- // Avoid intermittent failures.
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- content.gSearch._contentSearchController.remoteTimeout = 5000;
- });
-
- // Type an X in the search input. This is only a smoke test. See
- // browser_searchSuggestionUI.js for comprehensive content search suggestion
- // UI tests.
- let suggestionsOpenPromise = new Promise(resolve => {
- mm.addMessageListener("test:newtab-suggestions-open", function onResponse(message) {
- mm.removeMessageListener("test:newtab-suggestions-open", onResponse);
- resolve();
- });
- });
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let table = content.document.getElementById("searchSuggestionTable");
-
- let input = content.document.getElementById("newtab-search-text");
- input.focus();
-
- info("Waiting for suggestions table to open");
- let observer = new content.MutationObserver(() => {
- if (input.getAttribute("aria-expanded") == "true") {
- observer.disconnect();
- Assert.ok(!table.hidden, "Search suggestion table unhidden");
- sendAsyncMessage("test:newtab-suggestions-open", {});
- }
- });
- observer.observe(input, {
- attributes: true,
- attributeFilter: ["aria-expanded"],
- });
- });
-
- let suggestionsPromise = promiseSearchEvents(["Suggestions"]);
-
- EventUtils.synthesizeKey("x", {});
-
- // Wait for the search suggestions to become visible and for the Suggestions
- // message.
- yield suggestionsOpenPromise;
- yield suggestionsPromise;
-
- // Empty the search input, causing the suggestions to be hidden.
- EventUtils.synthesizeKey("a", { accelKey: true });
- EventUtils.synthesizeKey("VK_DELETE", {});
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- Assert.ok(content.document.getElementById("searchSuggestionTable").hidden,
- "Search suggestion table hidden");
- });
-
- // Done. Revert the current engine and remove the new engines.
- searchEventsPromise = promiseSearchEvents(["CurrentEngine"]);
- Services.search.currentEngine = oldCurrentEngine;
- yield searchEventsPromise;
-
- let events = Array(gNewEngines.length).fill("CurrentState", 0, gNewEngines.length);
- searchEventsPromise = promiseSearchEvents(events);
-
- for (let engine of gNewEngines) {
- Services.search.removeEngine(engine);
- }
- yield searchEventsPromise;
-});
-
-function promiseSearchEvents(events) {
- info("Expecting search events: " + events);
- return new Promise(resolve => {
- gExpectedSearchEventQueue.push(...events);
- gExpectedSearchEventResolver = resolve;
- });
-}
-
-function promiseNewSearchEngine({name: basename, numLogos}) {
- info("Waiting for engine to be added: " + basename);
-
- // Wait for the search events triggered by adding the new engine.
- // engine-added engine-loaded
- let expectedSearchEvents = ["CurrentState", "CurrentState"];
- // engine-changed for each of the logos
- for (let i = 0; i < numLogos; i++) {
- expectedSearchEvents.push("CurrentState");
- }
- let eventPromise = promiseSearchEvents(expectedSearchEvents);
-
- // Wait for addEngine().
- let addEnginePromise = new Promise((resolve, reject) => {
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- gNewEngines.push(engine);
- resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- reject();
- },
- });
- });
-
- return Promise.all([addEnginePromise, eventPromise]).then(([newEngine, _]) => {
- return newEngine;
- });
-}
-
-function* checkCurrentEngine(engineInfo)
-{
- let engine = Services.search.currentEngine;
- ok(engine.name.includes(engineInfo.name),
- "Sanity check: current engine: engine.name=" + engine.name +
- " basename=" + engineInfo.name);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, { name: engine.name }, function* (args) {
- Assert.equal(content.gSearch._contentSearchController.defaultEngine.name,
- args.name, "currentEngineName: " + args.name);
- });
-}
diff --git a/browser/base/content/test/newtab/browser_newtab_sponsored_icon_click.js b/browser/base/content/test/newtab/browser_newtab_sponsored_icon_click.js
deleted file mode 100644
index f6bb85d47..000000000
--- a/browser/base/content/test/newtab/browser_newtab_sponsored_icon_click.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* () {
- yield setLinks("0");
- yield* addNewTabPageTab();
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- var EventUtils = {};
- EventUtils.window = {};
- EventUtils.parent = EventUtils.window;
- EventUtils._EU_Ci = Components.interfaces;
-
- Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- let cell = content.gGrid.cells[0];
-
- let site = cell.node.querySelector(".newtab-site");
- site.setAttribute("type", "sponsored");
-
- // test explain text appearing upon a click
- let sponsoredButton = site.querySelector(".newtab-sponsored");
- EventUtils.synthesizeMouseAtCenter(sponsoredButton, {}, content);
- let explain = site.querySelector(".sponsored-explain");
- Assert.notEqual(explain, null, "Sponsored explanation shown");
- Assert.ok(explain.querySelector("input").classList.contains("newtab-control-block"),
- "sponsored tiles show blocked image");
- Assert.ok(sponsoredButton.hasAttribute("active"), "Sponsored button has active attribute");
-
- // test dismissing sponsored explain
- EventUtils.synthesizeMouseAtCenter(sponsoredButton, {}, content);
- Assert.equal(site.querySelector(".sponsored-explain"), null,
- "Sponsored explanation no longer shown");
- Assert.ok(!sponsoredButton.hasAttribute("active"),
- "Sponsored button does not have active attribute");
-
- // test with enhanced tile
- site.setAttribute("type", "enhanced");
- EventUtils.synthesizeMouseAtCenter(sponsoredButton, {}, content);
- explain = site.querySelector(".sponsored-explain");
- Assert.notEqual(explain, null, "Sponsored explanation shown");
- Assert.ok(explain.querySelector("input").classList.contains("newtab-customize"),
- "enhanced tiles show customize image");
- Assert.ok(sponsoredButton.hasAttribute("active"), "Sponsored button has active attribute");
-
- // test dismissing enhanced explain
- EventUtils.synthesizeMouseAtCenter(sponsoredButton, {}, content);
- Assert.equal(site.querySelector(".sponsored-explain"), null,
- "Sponsored explanation no longer shown");
- Assert.ok(!sponsoredButton.hasAttribute("active"),
- "Sponsored button does not have active attribute");
- });
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_undo.js b/browser/base/content/test/newtab/browser_newtab_undo.js
deleted file mode 100644
index ba094cb26..000000000
--- a/browser/base/content/test/newtab/browser_newtab_undo.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that the undo dialog works as expected.
- */
-add_task(function* () {
- // remove unpinned sites and undo it
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks("5");
-
- yield* addNewTabPageTab();
- yield* checkGrid("5p,0,1,2,3,4,6,7,8");
-
- yield blockCell(4);
- yield blockCell(4);
- yield* checkGrid("5p,0,1,2,6,7,8");
-
- yield* undo();
- yield* checkGrid("5p,0,1,2,4,6,7,8");
-
- // now remove a pinned site and undo it
- yield blockCell(0);
- yield* checkGrid("0,1,2,4,6,7,8");
-
- yield* undo();
- yield* checkGrid("5p,0,1,2,4,6,7,8");
-
- // remove a site and restore all
- yield blockCell(1);
- yield* checkGrid("5p,1,2,4,6,7,8");
-
- yield* undoAll();
- yield* checkGrid("5p,0,1,2,3,4,6,7,8");
-});
-
-function* undo() {
- let updatedPromise = whenPagesUpdated();
- yield BrowserTestUtils.synthesizeMouseAtCenter("#newtab-undo-button", {}, gBrowser.selectedBrowser);
- yield updatedPromise;
-}
-
-function* undoAll() {
- let updatedPromise = whenPagesUpdated();
- yield BrowserTestUtils.synthesizeMouseAtCenter("#newtab-undo-restore-button", {}, gBrowser.selectedBrowser);
- yield updatedPromise;
-}
diff --git a/browser/base/content/test/newtab/browser_newtab_unpin.js b/browser/base/content/test/newtab/browser_newtab_unpin.js
deleted file mode 100644
index 14751465f..000000000
--- a/browser/base/content/test/newtab/browser_newtab_unpin.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests make sure that when a site gets unpinned it is either moved to
- * its actual place in the grid or removed in case it's not on the grid anymore.
- */
-add_task(function* () {
- // we have a pinned link that didn't change its position since it was pinned.
- // nothing should happen when we unpin it.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",1");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,1p,2,3,4,5,6,7,8");
-
- yield unpinCell(1);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- // we have a pinned link that is not anymore in the list of the most-visited
- // links. this should disappear, the remaining links adjust their positions
- // and a new link will appear at the end of the grid.
- yield setLinks("0,1,2,3,4,5,6,7,8");
- setPinnedLinks(",99");
-
- yield* addNewTabPageTab();
- yield* checkGrid("0,99p,1,2,3,4,5,6,7");
-
- yield unpinCell(1);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-
- // we have a pinned link that changed its position since it was pinned. it
- // should be moved to its new position after being unpinned.
- yield setLinks("0,1,2,3,4,5,6,7");
- setPinnedLinks(",1,,,,,,,0");
-
- yield* addNewTabPageTab();
- yield* checkGrid("2,1p,3,4,5,6,7,,0p");
-
- yield unpinCell(1);
- yield* checkGrid("1,2,3,4,5,6,7,,0p");
-
- yield unpinCell(8);
- yield* checkGrid("0,1,2,3,4,5,6,7,");
-
- // we have pinned link that changed its position since it was pinned. the
- // link will disappear from the grid because it's now a much lower priority
- yield setLinks("0,1,2,3,4,5,6,7,8,9");
- setPinnedLinks("9");
-
- yield* addNewTabPageTab();
- yield* checkGrid("9p,0,1,2,3,4,5,6,7");
-
- yield unpinCell(0);
- yield* checkGrid("0,1,2,3,4,5,6,7,8");
-});
diff --git a/browser/base/content/test/newtab/browser_newtab_update.js b/browser/base/content/test/newtab/browser_newtab_update.js
deleted file mode 100644
index 6cf089dfd..000000000
--- a/browser/base/content/test/newtab/browser_newtab_update.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Checks that newtab is updated as its links change.
- */
-add_task(function* () {
- // First, start with an empty page. setLinks will trigger a hidden page
- // update because it calls clearHistory. We need to wait for that update to
- // happen so that the next time we wait for a page update below, we catch the
- // right update and not the one triggered by setLinks.
- let updatedPromise = whenPagesUpdated();
- let setLinksPromise = setLinks([]);
- yield Promise.all([updatedPromise, setLinksPromise]);
-
- // Strategy: Add some visits, open a new page, check the grid, repeat.
- yield fillHistoryAndWaitForPageUpdate([1]);
- yield* addNewTabPageTab();
- yield* checkGrid("1,,,,,,,,");
-
- yield fillHistoryAndWaitForPageUpdate([2]);
- yield* addNewTabPageTab();
- yield* checkGrid("2,1,,,,,,,");
-
- yield fillHistoryAndWaitForPageUpdate([1]);
- yield* addNewTabPageTab();
- yield* checkGrid("1,2,,,,,,,");
-
- yield fillHistoryAndWaitForPageUpdate([2, 3, 4]);
- yield* addNewTabPageTab();
- yield* checkGrid("2,1,3,4,,,,,");
-
- // Make sure these added links have the right type
- let type = yield performOnCell(1, cell => { return cell.site.link.type });
- is(type, "history", "added link is history");
-});
-
-function fillHistoryAndWaitForPageUpdate(links) {
- let updatedPromise = whenPagesUpdated;
- let fillHistoryPromise = fillHistory(links.map(link));
- return Promise.all([updatedPromise, fillHistoryPromise]);
-}
-
-function link(id) {
- return { url: "http://example" + id + ".com/", title: "site#" + id };
-}
diff --git a/browser/base/content/test/newtab/content-reflows.js b/browser/base/content/test/newtab/content-reflows.js
deleted file mode 100644
index f1a53782e..000000000
--- a/browser/base/content/test/newtab/content-reflows.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-(function () {
- "use strict";
-
- const Ci = Components.interfaces;
-
- docShell.addWeakReflowObserver({
- reflow() {
- // Gather information about the current code path.
- let path = (new Error().stack).split("\n").slice(1).join("\n");
- if (path) {
- sendSyncMessage("newtab-reflow", path);
- }
- },
-
- reflowInterruptible() {
- // We're not interested in interruptible reflows.
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIReflowObserver,
- Ci.nsISupportsWeakReference])
- });
-})();
diff --git a/browser/base/content/test/newtab/head.js b/browser/base/content/test/newtab/head.js
deleted file mode 100644
index d702103a0..000000000
--- a/browser/base/content/test/newtab/head.js
+++ /dev/null
@@ -1,552 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PREF_NEWTAB_ENABLED = "browser.newtabpage.enabled";
-const PREF_NEWTAB_DIRECTORYSOURCE = "browser.newtabpage.directory.source";
-
-Services.prefs.setBoolPref(PREF_NEWTAB_ENABLED, true);
-
-var tmp = {};
-Cu.import("resource://gre/modules/NewTabUtils.jsm", tmp);
-Cu.import("resource:///modules/DirectoryLinksProvider.jsm", tmp);
-Cu.import("resource://testing-common/PlacesTestUtils.jsm", tmp);
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tmp);
-var {NewTabUtils, Sanitizer, DirectoryLinksProvider, PlacesTestUtils} = tmp;
-
-var gWindow = window;
-
-// Default to dummy/empty directory links
-var gDirectorySource = 'data:application/json,{"test":1}';
-var gOrigDirectorySource;
-
-// The tests assume all 3 rows and all 3 columns of sites are shown, but the
-// window may be too small to actually show everything. Resize it if necessary.
-var requiredSize = {};
-requiredSize.innerHeight =
- 40 + 32 + // undo container + bottom margin
- 44 + 32 + // search bar + bottom margin
- (3 * (180 + 32)) + // 3 rows * (tile height + title and bottom margin)
- 100; // breathing room
-requiredSize.innerWidth =
- (3 * (290 + 20)) + // 3 cols * (tile width + side margins)
- 100; // breathing room
-
-var oldSize = {};
-Object.keys(requiredSize).forEach(prop => {
- info([prop, gBrowser.contentWindow[prop], requiredSize[prop]]);
- if (gBrowser.contentWindow[prop] < requiredSize[prop]) {
- oldSize[prop] = gBrowser.contentWindow[prop];
- info("Changing browser " + prop + " from " + oldSize[prop] + " to " +
- requiredSize[prop]);
- gBrowser.contentWindow[prop] = requiredSize[prop];
- }
-});
-
-var screenHeight = {};
-var screenWidth = {};
-Cc["@mozilla.org/gfx/screenmanager;1"].
- getService(Ci.nsIScreenManager).
- primaryScreen.
- GetAvailRectDisplayPix({}, {}, screenWidth, screenHeight);
-screenHeight = screenHeight.value;
-screenWidth = screenWidth.value;
-
-if (screenHeight < gBrowser.contentWindow.outerHeight) {
- info("Warning: Browser outer height is now " +
- gBrowser.contentWindow.outerHeight + ", which is larger than the " +
- "available screen height, " + screenHeight +
- ". That may cause problems.");
-}
-
-if (screenWidth < gBrowser.contentWindow.outerWidth) {
- info("Warning: Browser outer width is now " +
- gBrowser.contentWindow.outerWidth + ", which is larger than the " +
- "available screen width, " + screenWidth +
- ". That may cause problems.");
-}
-
-registerCleanupFunction(function () {
- while (gWindow.gBrowser.tabs.length > 1)
- gWindow.gBrowser.removeTab(gWindow.gBrowser.tabs[1]);
-
- Object.keys(oldSize).forEach(prop => {
- if (oldSize[prop]) {
- gBrowser.contentWindow[prop] = oldSize[prop];
- }
- });
-
- // Stop any update timers to prevent unexpected updates in later tests
- let timer = NewTabUtils.allPages._scheduleUpdateTimeout;
- if (timer) {
- clearTimeout(timer);
- delete NewTabUtils.allPages._scheduleUpdateTimeout;
- }
-
- Services.prefs.clearUserPref(PREF_NEWTAB_ENABLED);
- Services.prefs.setCharPref(PREF_NEWTAB_DIRECTORYSOURCE, gOrigDirectorySource);
-
- return watchLinksChangeOnce();
-});
-
-function pushPrefs(...aPrefs) {
- return new Promise(resolve =>
- SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve));
-}
-
-/**
- * Resolves promise when directory links are downloaded and written to disk
- */
-function watchLinksChangeOnce() {
- return new Promise(resolve => {
- let observer = {
- onManyLinksChanged: () => {
- DirectoryLinksProvider.removeObserver(observer);
- resolve();
- }
- };
- observer.onDownloadFail = observer.onManyLinksChanged;
- DirectoryLinksProvider.addObserver(observer);
- });
-}
-
-add_task(function* setup() {
- registerCleanupFunction(function() {
- return new Promise(resolve => {
- function cleanupAndFinish() {
- PlacesTestUtils.clearHistory().then(() => {
- whenPagesUpdated().then(resolve);
- NewTabUtils.restore();
- });
- }
-
- let callbacks = NewTabUtils.links._populateCallbacks;
- let numCallbacks = callbacks.length;
-
- if (numCallbacks)
- callbacks.splice(0, numCallbacks, cleanupAndFinish);
- else
- cleanupAndFinish();
- });
- });
-
- let promiseReady = Task.spawn(function*() {
- yield watchLinksChangeOnce();
- yield whenPagesUpdated();
- });
-
- // Save the original directory source (which is set globally for tests)
- gOrigDirectorySource = Services.prefs.getCharPref(PREF_NEWTAB_DIRECTORYSOURCE);
- Services.prefs.setCharPref(PREF_NEWTAB_DIRECTORYSOURCE, gDirectorySource);
- yield promiseReady;
-});
-
-/** Perform an action on a cell within the newtab page.
- * @param aIndex index of cell
- * @param aFn function to call in child process or tab.
- * @returns result of calling the function.
- */
-function performOnCell(aIndex, aFn) {
- return ContentTask.spawn(gWindow.gBrowser.selectedBrowser,
- { index: aIndex, fn: aFn.toString() }, function* (args) {
- let cell = content.gGrid.cells[args.index];
- return eval(args.fn)(cell);
- });
-}
-
-/**
- * Allows to provide a list of links that is used to construct the grid.
- * @param aLinksPattern the pattern (see below)
- *
- * Example: setLinks("-1,0,1,2,3")
- * Result: [{url: "http://example.com/", title: "site#-1"},
- * {url: "http://example0.com/", title: "site#0"},
- * {url: "http://example1.com/", title: "site#1"},
- * {url: "http://example2.com/", title: "site#2"},
- * {url: "http://example3.com/", title: "site#3"}]
- */
-function setLinks(aLinks) {
- return new Promise(resolve => {
- let links = aLinks;
-
- if (typeof links == "string") {
- links = aLinks.split(/\s*,\s*/).map(function (id) {
- return {url: "http://example" + (id != "-1" ? id : "") + ".com/",
- title: "site#" + id};
- });
- }
-
- // Call populateCache() once to make sure that all link fetching that is
- // currently in progress has ended. We clear the history, fill it with the
- // given entries and call populateCache() now again to make sure the cache
- // has the desired contents.
- NewTabUtils.links.populateCache(function () {
- PlacesTestUtils.clearHistory().then(() => {
- fillHistory(links).then(() => {
- NewTabUtils.links.populateCache(function () {
- NewTabUtils.allPages.update();
- resolve();
- }, true);
- });
- });
- });
- });
-}
-
-function fillHistory(aLinks) {
- return new Promise(resolve => {
- let numLinks = aLinks.length;
- if (!numLinks) {
- executeSoon(resolve);
- return;
- }
-
- let transitionLink = Ci.nsINavHistoryService.TRANSITION_LINK;
-
- // Important: To avoid test failures due to clock jitter on Windows XP, call
- // Date.now() once here, not each time through the loop.
- let now = Date.now() * 1000;
-
- for (let i = 0; i < aLinks.length; i++) {
- let link = aLinks[i];
- let place = {
- uri: makeURI(link.url),
- title: link.title,
- // Links are secondarily sorted by visit date descending, so decrease the
- // visit date as we progress through the array so that links appear in the
- // grid in the order they're present in the array.
- visits: [{visitDate: now - i, transitionType: transitionLink}]
- };
-
- PlacesUtils.asyncHistory.updatePlaces(place, {
- handleError: () => ok(false, "couldn't add visit to history"),
- handleResult: function () {},
- handleCompletion: function () {
- if (--numLinks == 0) {
- resolve();
- }
- }
- });
- }
- });
-}
-
-/**
- * Allows to specify the list of pinned links (that have a fixed position in
- * the grid.
- * @param aLinksPattern the pattern (see below)
- *
- * Example: setPinnedLinks("3,,1")
- * Result: 'http://example3.com/' is pinned in the first cell. 'http://example1.com/' is
- * pinned in the third cell.
- */
-function setPinnedLinks(aLinks) {
- let links = aLinks;
-
- if (typeof links == "string") {
- links = aLinks.split(/\s*,\s*/).map(function (id) {
- if (id)
- return {url: "http://example" + (id != "-1" ? id : "") + ".com/",
- title: "site#" + id,
- type: "history"};
- return undefined;
- });
- }
-
- let string = Cc["@mozilla.org/supports-string;1"]
- .createInstance(Ci.nsISupportsString);
- string.data = JSON.stringify(links);
- Services.prefs.setComplexValue("browser.newtabpage.pinned",
- Ci.nsISupportsString, string);
-
- NewTabUtils.pinnedLinks.resetCache();
- NewTabUtils.allPages.update();
-}
-
-/**
- * Restore the grid state.
- */
-function restore() {
- return new Promise(resolve => {
- whenPagesUpdated().then(resolve);
- NewTabUtils.restore();
- });
-}
-
-/**
- * Wait until a given condition becomes true.
- */
-function waitForCondition(aConditionFn, aMaxTries=50, aCheckInterval=100) {
- return new Promise((resolve, reject) => {
- let tries = 0;
-
- function tryNow() {
- tries++;
-
- if (aConditionFn()) {
- resolve();
- } else if (tries < aMaxTries) {
- tryAgain();
- } else {
- reject("Condition timed out: " + aConditionFn.toSource());
- }
- }
-
- function tryAgain() {
- setTimeout(tryNow, aCheckInterval);
- }
-
- tryAgain();
- });
-}
-
-/**
- * Creates a new tab containing 'about:newtab'.
- */
-function* addNewTabPageTab() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gWindow.gBrowser, "about:newtab", false);
- let browser = tab.linkedBrowser;
-
- // Wait for the document to become visible in case it was preloaded.
- yield waitForCondition(() => !browser.contentDocument.hidden)
-
- yield new Promise(resolve => {
- if (NewTabUtils.allPages.enabled) {
- // Continue when the link cache has been populated.
- NewTabUtils.links.populateCache(function () {
- whenSearchInitDone().then(resolve);
- });
- } else {
- resolve();
- }
- });
-
- return tab;
-}
-
-/**
- * Compares the current grid arrangement with the given pattern.
- * @param the pattern (see below)
- *
- * Example: checkGrid("3p,2,,1p")
- * Result: We expect the first cell to contain the pinned site 'http://example3.com/'.
- * The second cell contains 'http://example2.com/'. The third cell is empty.
- * The fourth cell contains the pinned site 'http://example4.com/'.
- */
-function* checkGrid(pattern) {
- let length = pattern.split(",").length;
-
- yield ContentTask.spawn(gWindow.gBrowser.selectedBrowser,
- { length, pattern }, function* (args) {
- let grid = content.wrappedJSObject.gGrid;
-
- let sites = grid.sites.slice(0, args.length);
- let foundPattern = sites.map(function (aSite) {
- if (!aSite)
- return "";
-
- let pinned = aSite.isPinned();
- let hasPinnedAttr = aSite.node.hasAttribute("pinned");
-
- if (pinned != hasPinnedAttr)
- ok(false, "invalid state (site.isPinned() != site[pinned])");
-
- return aSite.url.replace(/^http:\/\/example(\d+)\.com\/$/, "$1") + (pinned ? "p" : "");
- });
-
- Assert.equal(foundPattern, args.pattern, "grid status = " + args.pattern);
- });
-}
-
-/**
- * Blocks a site from the grid.
- * @param aIndex The cell index.
- */
-function blockCell(aIndex) {
- return new Promise(resolve => {
- whenPagesUpdated().then(resolve);
- performOnCell(aIndex, cell => {
- return cell.site.block();
- });
- });
-}
-
-/**
- * Pins a site on a given position.
- * @param aIndex The cell index.
- * @param aPinIndex The index the defines where the site should be pinned.
- */
-function pinCell(aIndex) {
- performOnCell(aIndex, cell => {
- cell.site.pin();
- });
-}
-
-/**
- * Unpins the given cell's site.
- * @param aIndex The cell index.
- */
-function unpinCell(aIndex) {
- return new Promise(resolve => {
- whenPagesUpdated().then(resolve);
- performOnCell(aIndex, cell => {
- cell.site.unpin();
- });
- });
-}
-
-/**
- * Simulates a drag and drop operation. Instead of rearranging a site that is
- * is already contained in the newtab grid, this is used to simulate dragging
- * an external link onto the grid e.g. the text from the URL bar.
- * @param aDestIndex The cell index of the drop target.
- */
-function* simulateExternalDrop(aDestIndex) {
- let pagesUpdatedPromise = whenPagesUpdated();
-
- yield ContentTask.spawn(gWindow.gBrowser.selectedBrowser, aDestIndex, function*(dropIndex) {
- return new Promise(resolve => {
- const url = "data:text/html;charset=utf-8," +
- "<a id='link' href='http://example99.com/'>link</a>";
-
- let doc = content.document;
- let iframe = doc.createElement("iframe");
-
- function iframeLoaded() {
- let dataTransfer = new iframe.contentWindow.DataTransfer("dragstart", false);
- dataTransfer.mozSetDataAt("text/x-moz-url", "http://example99.com/", 0);
-
- let event = content.document.createEvent("DragEvent");
- event.initDragEvent("drop", true, true, content, 0, 0, 0, 0, 0,
- false, false, false, false, 0, null, dataTransfer);
-
- let target = content.gGrid.cells[dropIndex].node;
- target.dispatchEvent(event);
-
- iframe.remove();
-
- resolve();
- }
-
- iframe.addEventListener("load", function onLoad() {
- iframe.removeEventListener("load", onLoad);
- content.setTimeout(iframeLoaded, 0);
- });
-
- iframe.setAttribute("src", url);
- iframe.style.width = "50px";
- iframe.style.height = "50px";
- iframe.style.position = "absolute";
- iframe.style.zIndex = 50;
-
- // the frame has to be attached to a visible element
- let margin = doc.getElementById("newtab-search-container");
- margin.appendChild(iframe);
- });
- });
-
- yield pagesUpdatedPromise;
-}
-
-/**
- * Resumes testing when all pages have been updated.
- */
-function whenPagesUpdated() {
- return new Promise(resolve => {
- let page = {
- observe: _ => _,
-
- update() {
- NewTabUtils.allPages.unregister(this);
- executeSoon(resolve);
- }
- };
-
- NewTabUtils.allPages.register(page);
- registerCleanupFunction(function () {
- NewTabUtils.allPages.unregister(page);
- });
- });
-}
-
-/**
- * Waits for the response to the page's initial search state request.
- */
-function whenSearchInitDone() {
- return ContentTask.spawn(gWindow.gBrowser.selectedBrowser, {}, function*() {
- return new Promise(resolve => {
- if (content.gSearch) {
- let searchController = content.gSearch._contentSearchController;
- if (searchController.defaultEngine) {
- resolve();
- return;
- }
- }
-
- let eventName = "ContentSearchService";
- content.addEventListener(eventName, function onEvent(event) {
- if (event.detail.type == "State") {
- content.removeEventListener(eventName, onEvent);
- let resolver = function() {
- // Wait for the search controller to receive the event, then resolve.
- if (content.gSearch._contentSearchController.defaultEngine) {
- resolve();
- return;
- }
- }
- content.setTimeout(resolver, 0);
- }
- });
- });
- });
-}
-
-/**
- * Changes the newtab customization option and waits for the panel to open and close
- *
- * @param {string} aTheme
- * Can be any of("blank"|"classic"|"enhanced")
- */
-function customizeNewTabPage(aTheme) {
- return ContentTask.spawn(gWindow.gBrowser.selectedBrowser, aTheme, function*(aTheme) {
-
- let document = content.document;
- let panel = document.getElementById("newtab-customize-panel");
- let customizeButton = document.getElementById("newtab-customize-button");
-
- function panelOpened(opened) {
- return new Promise( (resolve) => {
- let options = {attributes: true, oldValue: true};
- let observer = new content.MutationObserver(function(mutations) {
- mutations.forEach(function(mutation) {
- document.getElementById("newtab-customize-" + aTheme).click();
- observer.disconnect();
- if (opened == panel.hasAttribute("open")) {
- resolve();
- }
- });
- });
- observer.observe(panel, options);
- });
- }
-
- let opened = panelOpened(true);
- customizeButton.click();
- yield opened;
-
- let closed = panelOpened(false);
- customizeButton.click();
- yield closed;
- });
-}
-
-/**
- * Reports presence of a scrollbar
- */
-function hasScrollbar() {
- return ContentTask.spawn(gWindow.gBrowser.selectedBrowser, {}, function* () {
- let docElement = content.document.documentElement;
- return docElement.scrollHeight > docElement.clientHeight;
- });
-}
diff --git a/browser/base/content/test/newtab/searchEngine1x2xLogo.xml b/browser/base/content/test/newtab/searchEngine1x2xLogo.xml
deleted file mode 100644
index c8b6749b3..000000000
--- a/browser/base/content/test/newtab/searchEngine1x2xLogo.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_newtab_search searchEngine1x2xLogo.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-newtab-search.com/1x2xlogo" rel="searchform"/>
-<!-- #00FF00 -->
-<Image width="65" height="26">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAaCAIAAABn3KYmAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADIGr0+8uwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAL0lEQVRYw+3PAREAAAQEsKd/Z3I4W4NVJtd14uDg4ODg4ODg4ODg4ODg4ODg8Pqw7M0BM+n9I0oAAAAASUVORK5CYII=</Image>
-<!-- #00FFFF -->
-<Image width="130" height="52">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAAA0CAIAAADJ8nfCAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADMoaoKANQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAYklEQVR42u3RQQ0AAAjEMMC/58MECZ9OwtqVlL4bCzAIAwZhwCAMGIQBgzBgEAYMwoBBGDAIAwZhwCAMGIQBgzBgEAYMwoBBGIQBgzBgEAYMwoBBGDAIAwZhwCAMGIQBg+5ar7sCZiri9VUAAAAASUVORK5CYII=</Image>
-</SearchPlugin>
diff --git a/browser/base/content/test/newtab/searchEngine1xLogo.xml b/browser/base/content/test/newtab/searchEngine1xLogo.xml
deleted file mode 100644
index 19ac03f48..000000000
--- a/browser/base/content/test/newtab/searchEngine1xLogo.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_newtab_search searchEngine1xLogo.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-newtab-search.com/1xlogo" rel="searchform"/>
-<!-- #FF0000 -->
-<Image width="65" height="26">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAaCAIAAABn3KYmAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADEwS9h64QAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAL0lEQVRYw+3PAREAAAQEsKd/Z3I4W4PV5LyOg4ODg4ODg4ODg4ODg4ODg4PD78MC7cwBM02qquMAAAAASUVORK5CYII=</Image>
-</SearchPlugin>
diff --git a/browser/base/content/test/newtab/searchEngine2xLogo.xml b/browser/base/content/test/newtab/searchEngine2xLogo.xml
deleted file mode 100644
index 941bf040d..000000000
--- a/browser/base/content/test/newtab/searchEngine2xLogo.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_newtab_search searchEngine2xLogo.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-newtab-search.com/2xlogo" rel="searchform"/>
-<!-- #0000FF -->
-<Image width="130" height="52">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAAA0CAIAAADJ8nfCAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gkTADMURe38sgAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAYklEQVR42u3RQQ0AAAjEsAP/nsEECZ9OwlrJRN+1BRiEAYMwYBAGDMKAQRgwCAMGYcAgDBiEAYMwYBAGDMKAQRgwCAMGYcAgDMKAQRgwCAMGYcAgDBiEAYMwYBAGDMKAQXctkIQBZ/1YP3YAAAAASUVORK5CYII=</Image>
-</SearchPlugin>
diff --git a/browser/base/content/test/newtab/searchEngineFavicon.xml b/browser/base/content/test/newtab/searchEngineFavicon.xml
deleted file mode 100644
index 6f2a970f5..000000000
--- a/browser/base/content/test/newtab/searchEngineFavicon.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_newtab_search searchEngineFavicon.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-newtab-search.com/1xlogo" rel="searchform"/>
-<Image width="16" height="16">data:application/ico;base64,AAABAAIAICAAAAEAIACoEAAAJgAAABAQAAABACAAaAQAAM4QAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAATCwAAEwsAAAAAAAAAAAAA/wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAABAAAAAgAAAAAQAgAAAAAAAABAAAEwsAABMLAAAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</Image>
-</SearchPlugin>
diff --git a/browser/base/content/test/newtab/searchEngineNoLogo.xml b/browser/base/content/test/newtab/searchEngineNoLogo.xml
deleted file mode 100644
index bbff6cf8f..000000000
--- a/browser/base/content/test/newtab/searchEngineNoLogo.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_newtab_search searchEngineNoLogo.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-newtab-search.com/nologo" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/base/content/test/plugins/.eslintrc.js b/browser/base/content/test/plugins/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/plugins/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/plugins/blockNoPlugins.xml b/browser/base/content/test/plugins/blockNoPlugins.xml
deleted file mode 100644
index e4e191b37..000000000
--- a/browser/base/content/test/plugins/blockNoPlugins.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1336406310001">
- <emItems>
- </emItems>
- <pluginItems>
- </pluginItems>
-</blocklist>
diff --git a/browser/base/content/test/plugins/blockPluginHard.xml b/browser/base/content/test/plugins/blockPluginHard.xml
deleted file mode 100644
index 24eb5bc6f..000000000
--- a/browser/base/content/test/plugins/blockPluginHard.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1336406310000">
- <emItems>
- </emItems>
- <pluginItems>
- <pluginItem blockID="p9999">
- <match name="filename" exp="libnptest\.so|nptest\.dll|Test\.plugin" />
- <versionRange severity="2"></versionRange>
- </pluginItem>
- </pluginItems>
-</blocklist>
diff --git a/browser/base/content/test/plugins/blockPluginInfoURL.xml b/browser/base/content/test/plugins/blockPluginInfoURL.xml
deleted file mode 100644
index c16808896..000000000
--- a/browser/base/content/test/plugins/blockPluginInfoURL.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1336406310000">
- <emItems>
- </emItems>
- <pluginItems>
- <pluginItem blockID="p9999">
- <match name="filename" exp="libnptest\.so|nptest\.dll|Test\.plugin" />
- <versionRange severity="2"></versionRange>
- <infoURL>http://test.url.com/</infoURL>
- </pluginItem>
- </pluginItems>
-</blocklist>
diff --git a/browser/base/content/test/plugins/blockPluginVulnerableNoUpdate.xml b/browser/base/content/test/plugins/blockPluginVulnerableNoUpdate.xml
deleted file mode 100644
index bf8545afe..000000000
--- a/browser/base/content/test/plugins/blockPluginVulnerableNoUpdate.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1336406310000">
- <emItems>
- </emItems>
- <pluginItems>
- <pluginItem blockID="p9999">
- <match name="filename" exp="libnptest\.so|nptest\.dll|Test\.plugin" />
- <versionRange severity="0" vulnerabilitystatus="2"></versionRange>
- </pluginItem>
- </pluginItems>
-</blocklist>
diff --git a/browser/base/content/test/plugins/blockPluginVulnerableUpdatable.xml b/browser/base/content/test/plugins/blockPluginVulnerableUpdatable.xml
deleted file mode 100644
index 5545162b1..000000000
--- a/browser/base/content/test/plugins/blockPluginVulnerableUpdatable.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1336406310000">
- <emItems>
- </emItems>
- <pluginItems>
- <pluginItem blockID="p9999">
- <match name="filename" exp="libnptest\.so|nptest\.dll|Test\.plugin" />
- <versionRange severity="0" vulnerabilitystatus="1"></versionRange>
- </pluginItem>
- </pluginItems>
-</blocklist>
diff --git a/browser/base/content/test/plugins/blocklist_proxy.js b/browser/base/content/test/plugins/blocklist_proxy.js
deleted file mode 100644
index 1a4ed4726..000000000
--- a/browser/base/content/test/plugins/blocklist_proxy.js
+++ /dev/null
@@ -1,78 +0,0 @@
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cm = Components.manager;
-
-const kBlocklistServiceUUID = "{66354bc9-7ed1-4692-ae1d-8da97d6b205e}";
-const kBlocklistServiceContractID = "@mozilla.org/extensions/blocklist;1";
-const kBlocklistServiceFactory = Cm.getClassObject(Cc[kBlocklistServiceContractID], Ci.nsIFactory);
-
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-
-/*
- * A lightweight blocklist proxy for the testing purposes.
- */
-var BlocklistProxy = {
- _uuid: null,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
- Ci.nsIBlocklistService,
- Ci.nsITimerCallback]),
-
- init: function() {
- if (!this._uuid) {
- this._uuid =
- Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator)
- .generateUUID();
- Cm.nsIComponentRegistrar.registerFactory(this._uuid, "",
- "@mozilla.org/extensions/blocklist;1",
- this);
- }
- },
-
- uninit: function() {
- if (this._uuid) {
- Cm.nsIComponentRegistrar.unregisterFactory(this._uuid, this);
- Cm.nsIComponentRegistrar.registerFactory(Components.ID(kBlocklistServiceUUID),
- "Blocklist Service",
- "@mozilla.org/extensions/blocklist;1",
- kBlocklistServiceFactory);
- this._uuid = null;
- }
- },
-
- notify: function (aTimer) {
- },
-
- observe: function (aSubject, aTopic, aData) {
- },
-
- isAddonBlocklisted: function (aAddon, aAppVersion, aToolkitVersion) {
- return false;
- },
-
- getAddonBlocklistState: function (aAddon, aAppVersion, aToolkitVersion) {
- return 0; // STATE_NOT_BLOCKED
- },
-
- getPluginBlocklistState: function (aPluginTag, aAppVersion, aToolkitVersion) {
- return 0; // STATE_NOT_BLOCKED
- },
-
- getAddonBlocklistURL: function (aAddon, aAppVersion, aToolkitVersion) {
- return "";
- },
-
- getPluginBlocklistURL: function (aPluginTag) {
- return "";
- },
-
- getPluginInfoURL: function (aPluginTag) {
- return "";
- },
-}
-
-BlocklistProxy.init();
-addEventListener("unload", () => {
- BlocklistProxy.uninit();
-});
diff --git a/browser/base/content/test/plugins/browser.ini b/browser/base/content/test/plugins/browser.ini
deleted file mode 100644
index cfc1f769c..000000000
--- a/browser/base/content/test/plugins/browser.ini
+++ /dev/null
@@ -1,78 +0,0 @@
-[DEFAULT]
-support-files =
- blocklist_proxy.js
- blockNoPlugins.xml
- blockPluginHard.xml
- blockPluginInfoURL.xml
- blockPluginVulnerableNoUpdate.xml
- blockPluginVulnerableUpdatable.xml
- browser_clearplugindata.html
- browser_clearplugindata_noage.html
- head.js
- plugin_add_dynamically.html
- plugin_alternate_content.html
- plugin_big.html
- plugin_both.html
- plugin_both2.html
- plugin_bug744745.html
- plugin_bug749455.html
- plugin_bug787619.html
- plugin_bug797677.html
- plugin_bug820497.html
- plugin_clickToPlayAllow.html
- plugin_clickToPlayDeny.html
- plugin_data_url.html
- plugin_hidden_to_visible.html
- plugin_iframe.html
- plugin_outsideScrollArea.html
- plugin_overlayed.html
- plugin_positioned.html
- plugin_small.html
- plugin_small_2.html
- plugin_syncRemoved.html
- plugin_test.html
- plugin_test2.html
- plugin_test3.html
- plugin_two_types.html
- plugin_unknown.html
- plugin_crashCommentAndURL.html
- plugin_zoom.html
-
-[browser_bug743421.js]
-[browser_bug744745.js]
-[browser_bug787619.js]
-[browser_bug797677.js]
-[browser_bug812562.js]
-[browser_bug818118.js]
-[browser_bug820497.js]
-[browser_clearplugindata.js]
-[browser_CTP_context_menu.js]
-skip-if = toolkit == "gtk2" || toolkit == "gtk3" # fails intermittently on Linux (bug 909342)
-[browser_CTP_crashreporting.js]
-skip-if = !crashreporter
-[browser_CTP_data_urls.js]
-[browser_CTP_drag_drop.js]
-[browser_CTP_hide_overlay.js]
-[browser_CTP_iframe.js]
-[browser_CTP_multi_allow.js]
-[browser_CTP_nonplugins.js]
-[browser_CTP_notificationBar.js]
-[browser_CTP_outsideScrollArea.js]
-[browser_CTP_remove_navigate.js]
-[browser_CTP_resize.js]
-[browser_CTP_zoom.js]
-[browser_blocking.js]
-[browser_plugins_added_dynamically.js]
-[browser_pluginnotification.js]
-[browser_plugin_reloading.js]
-[browser_blocklist_content.js]
-skip-if = !e10s
-[browser_globalplugin_crashinfobar.js]
-skip-if = !crashreporter
-[browser_pluginCrashCommentAndURL.js]
-skip-if = !crashreporter
-[browser_pageInfo_plugins.js]
-[browser_pluginCrashReportNonDeterminism.js]
-skip-if = !crashreporter || os == 'linux' # Bug 1152811
-[browser_private_clicktoplay.js]
-
diff --git a/browser/base/content/test/plugins/browser_CTP_context_menu.js b/browser/base/content/test/plugins/browser_CTP_context_menu.js
deleted file mode 100644
index 03f3e18ef..000000000
--- a/browser/base/content/test/plugins/browser_CTP_context_menu.js
+++ /dev/null
@@ -1,69 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-});
-
-// Test that the activate action in content menus for CTP plugins works
-add_task(function* () {
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- let bindingPromise = waitForEvent(gBrowser.selectedBrowser, "PluginBindingAttached", null, true, true);
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
- yield bindingPromise;
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(popupNotification, "Test 1, Should have a click-to-play notification");
-
- // check plugin state
- let pluginInfo = yield promiseForPluginInfo("test", gBrowser.selectedBrowser);
- ok(!pluginInfo.activated, "plugin should not be activated");
-
- // Display a context menu on the test plugin so we can test
- // activation menu options.
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("contextmenu", left, top, 2, 1, 0);
- });
-
- popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(popupNotification, "Should have a click-to-play notification");
- ok(popupNotification.dismissed, "notification should be dismissed");
-
- // fixes a occasional test timeout on win7 opt
- yield promiseForCondition(() => document.getElementById("context-ctp-play"));
-
- let actMenuItem = document.getElementById("context-ctp-play");
- ok(actMenuItem, "Should have a context menu entry for activating the plugin");
-
- // Activate the plugin via the context menu
- EventUtils.synthesizeMouseAtCenter(actMenuItem, {});
-
- yield promiseForCondition(() => !PopupNotifications.panel.dismissed && PopupNotifications.panel.firstChild);
-
- // Activate the plugin
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test", gBrowser.selectedBrowser);
- ok(pluginInfo.activated, "plugin should not be activated");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_crashreporting.js b/browser/base/content/test/plugins/browser_CTP_crashreporting.js
deleted file mode 100644
index bb52d5704..000000000
--- a/browser/base/content/test/plugins/browser_CTP_crashreporting.js
+++ /dev/null
@@ -1,233 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-const PLUGIN_PAGE = gTestRoot + "plugin_big.html";
-const PLUGIN_SMALL_PAGE = gTestRoot + "plugin_small.html";
-
-/**
- * Takes an nsIPropertyBag and converts it into a JavaScript Object. It
- * will also convert any nsIPropertyBag's within the nsIPropertyBag
- * recursively.
- *
- * @param aBag
- * The nsIPropertyBag to convert.
- * @return Object
- * Keyed on the names of the nsIProperty's within the nsIPropertyBag,
- * and mapping to their values.
- */
-function convertPropertyBag(aBag) {
- let result = {};
- let enumerator = aBag.enumerator;
- while (enumerator.hasMoreElements()) {
- let { name, value } = enumerator.getNext().QueryInterface(Ci.nsIProperty);
- if (value instanceof Ci.nsIPropertyBag) {
- value = convertPropertyBag(value);
- }
- result[name] = value;
- }
- return result;
-}
-
-add_task(function* setup() {
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- // The test harness sets MOZ_CRASHREPORTER_NO_REPORT, which disables plugin
- // crash reports. This test needs them enabled. The test also needs a mock
- // report server, and fortunately one is already set up by toolkit/
- // crashreporter/test/Makefile.in. Assign its URL to MOZ_CRASHREPORTER_URL,
- // which CrashSubmit.jsm uses as a server override.
- let env = Cc["@mozilla.org/process/environment;1"].
- getService(Components.interfaces.nsIEnvironment);
- let noReport = env.get("MOZ_CRASHREPORTER_NO_REPORT");
- let serverURL = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", "");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- registerCleanupFunction(function cleanUp() {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", noReport);
- env.set("MOZ_CRASHREPORTER_URL", serverURL);
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- window.focus();
- });
-});
-
-/**
- * Test that plugin crash submissions still work properly after
- * click-to-play activation.
- */
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PLUGIN_PAGE,
- }, function* (browser) {
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(browser);
-
- let pluginInfo = yield promiseForPluginInfo("test", browser);
- ok(!pluginInfo.activated, "Plugin should not be activated");
-
- // Simulate clicking the "Allow Always" button.
- let notification = PopupNotifications.getNotification("click-to-play-plugins", browser);
- yield promiseForNotificationShown(notification, browser);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // Prepare a crash report topic observer that only returns when
- // the crash report has been successfully sent.
- let crashReportChecker = (subject, data) => {
- return (data == "success");
- };
- let crashReportPromise = TestUtils.topicObserved("crash-report-status",
- crashReportChecker);
-
- yield ContentTask.spawn(browser, null, function*() {
- let plugin = content.document.getElementById("test");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
-
- yield ContentTaskUtils.waitForCondition(() => {
- return plugin.activated;
- }, "Waited too long for plugin to activate.");
-
- try {
- Components.utils.waiveXrays(plugin).crash();
- } catch (e) {
- }
-
- let doc = plugin.ownerDocument;
-
- let getUI = (anonid) => {
- return doc.getAnonymousElementByAttribute(plugin, "anonid", anonid);
- };
-
- // Now wait until the plugin crash report UI shows itself, which is
- // asynchronous.
- let statusDiv;
-
- yield ContentTaskUtils.waitForCondition(() => {
- statusDiv = getUI("submitStatus");
- return statusDiv.getAttribute("status") == "please";
- }, "Waited too long for plugin to show crash report UI");
-
- // Make sure the UI matches our expectations...
- let style = content.getComputedStyle(getUI("pleaseSubmit"));
- if (style.display != "block") {
- throw new Error(`Submission UI visibility is not correct. ` +
- `Expected block style, got ${style.display}.`);
- }
-
- // Fill the crash report in with some test values that we'll test for in
- // the parent.
- getUI("submitComment").value = "a test comment";
- let optIn = getUI("submitURLOptIn");
- if (!optIn.checked) {
- throw new Error("URL opt-in should default to true.");
- }
-
- // Submit the report.
- optIn.click();
- getUI("submitButton").click();
-
- // And wait for the parent to say that the crash report was submitted
- // successfully.
- yield ContentTaskUtils.waitForCondition(() => {
- return statusDiv.getAttribute("status") == "success";
- }, "Timed out waiting for plugin binding to be in success state");
- });
-
- let [subject, ] = yield crashReportPromise;
-
- ok(subject instanceof Ci.nsIPropertyBag,
- "The crash report subject should be an nsIPropertyBag.");
-
- let crashData = convertPropertyBag(subject);
- ok(crashData.serverCrashID, "Should have a serverCrashID set.");
-
- // Remove the submitted report file after ensuring it exists.
- let file = Cc["@mozilla.org/file/local;1"]
- .createInstance(Ci.nsILocalFile);
- file.initWithPath(Services.crashmanager._submittedDumpsDir);
- file.append(crashData.serverCrashID + ".txt");
- ok(file.exists(), "Submitted report file should exist");
- file.remove(false);
-
- ok(crashData.extra, "Extra data should exist");
- is(crashData.extra.PluginUserComment, "a test comment",
- "Comment in extra data should match comment in textbox");
-
- is(crashData.extra.PluginContentURL, undefined,
- "URL should be absent from extra data when opt-in not checked");
- });
-});
-
-/**
- * Test that plugin crash submissions still work properly after
- * click-to-play with the notification bar.
- */
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PLUGIN_SMALL_PAGE,
- }, function* (browser) {
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(browser);
-
- let pluginInfo = yield promiseForPluginInfo("test", browser);
- ok(pluginInfo.activated, "Plugin should be activated from previous test");
-
- // Prepare a crash report topic observer that only returns when
- // the crash report has been successfully sent.
- let crashReportChecker = (subject, data) => {
- return (data == "success");
- };
- let crashReportPromise = TestUtils.topicObserved("crash-report-status",
- crashReportChecker);
-
- yield ContentTask.spawn(browser, null, function*() {
- let plugin = content.document.getElementById("test");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
-
- yield ContentTaskUtils.waitForCondition(() => {
- return plugin.activated;
- }, "Waited too long for plugin to activate.");
-
- try {
- Components.utils.waiveXrays(plugin).crash();
- } catch (e) {}
- });
-
- // Wait for the notification bar to be displayed.
- let notification = yield waitForNotificationBar("plugin-crashed", browser);
-
- // Then click the button to submit the crash report.
- let buttons = notification.querySelectorAll(".notification-button");
- is(buttons.length, 2, "Should have two buttons.");
-
- // The "Submit Crash Report" button should be the second one.
- let submitButton = buttons[1];
- submitButton.click();
-
- let [subject, ] = yield crashReportPromise;
-
- ok(subject instanceof Ci.nsIPropertyBag,
- "The crash report subject should be an nsIPropertyBag.");
-
- let crashData = convertPropertyBag(subject);
- ok(crashData.serverCrashID, "Should have a serverCrashID set.");
-
- // Remove the submitted report file after ensuring it exists.
- let file = Cc["@mozilla.org/file/local;1"]
- .createInstance(Ci.nsILocalFile);
- file.initWithPath(Services.crashmanager._submittedDumpsDir);
- file.append(crashData.serverCrashID + ".txt");
- ok(file.exists(), "Submitted report file should exist");
- file.remove(false);
-
- is(crashData.extra.PluginContentURL, undefined,
- "URL should be absent from extra data when opt-in not checked");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_data_urls.js b/browser/base/content/test/plugins/browser_CTP_data_urls.js
deleted file mode 100644
index 0f4747b1e..000000000
--- a/browser/base/content/test/plugins/browser_CTP_data_urls.js
+++ /dev/null
@@ -1,255 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-});
-
-// Test that the click-to-play doorhanger still works when navigating to data URLs
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_data_url.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "Test 1a, Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 1a, plugin should not be activated");
-
- let loadPromise = promiseTabLoadEvent(gBrowser.selectedTab);
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- // navigate forward to a page with 'test' in it
- content.document.getElementById("data-link-1").click();
- });
- yield loadPromise;
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "Test 1b, Should have a click-to-play notification");
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 1b, plugin should not be activated");
-
- let promise = promisePopupNotification("click-to-play-plugins");
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- // Simulate clicking the "Allow Always" button.
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 1b, plugin should be activated");
-});
-
-// Test that the click-to-play notification doesn't break when navigating
-// to data URLs with multiple plugins.
-add_task(function* () {
- // We click activated above
- clearAllPluginPermissions();
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_data_url.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 2a, Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 2a, plugin should not be activated");
-
- let loadPromise = promiseTabLoadEvent(gBrowser.selectedTab);
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- // navigate forward to a page with 'test1' & 'test2' in it
- content.document.getElementById("data-link-2").click();
- });
- yield loadPromise;
-
- // Work around for delayed PluginBindingAttached
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- content.document.getElementById("test1").clientTop;
- content.document.getElementById("test2").clientTop;
- });
-
- pluginInfo = yield promiseForPluginInfo("test1");
- ok(!pluginInfo.activated, "Test 2a, test1 should not be activated");
- pluginInfo = yield promiseForPluginInfo("test2");
- ok(!pluginInfo.activated, "Test 2a, test2 should not be activated");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 2b, Should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- // Simulate choosing "Allow now" for the test plugin
- is(notification.options.pluginData.size, 2, "Test 2b, Should have two types of plugin in the notification");
-
- let centerAction = null;
- for (let action of notification.options.pluginData.values()) {
- if (action.pluginName == "Test") {
- centerAction = action;
- break;
- }
- }
- ok(centerAction, "Test 2b, found center action for the Test plugin");
-
- let centerItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- is(item.value, "block", "Test 2b, all plugins should start out blocked");
- if (item.action == centerAction) {
- centerItem = item;
- break;
- }
- }
- ok(centerItem, "Test 2b, found center item for the Test plugin");
-
- // "click" the button to activate the Test plugin
- centerItem.value = "allownow";
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test1");
- ok(pluginInfo.activated, "Test 2b, plugin should be activated");
-});
-
-add_task(function* () {
- // We click activated above
- clearAllPluginPermissions();
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_data_url.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-});
-
-// Test that when navigating to a data url, the plugin permission is inherited
-add_task(function* () {
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 3a, Should have a click-to-play notification");
-
- // check plugin state
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 3a, plugin should not be activated");
-
- let promise = promisePopupNotification("click-to-play-plugins");
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- // Simulate clicking the "Allow Always" button.
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 3a, plugin should be activated");
-
- let loadPromise = promiseTabLoadEvent(gBrowser.selectedTab);
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- // navigate forward to a page with 'test' in it
- content.document.getElementById("data-link-1").click();
- });
- yield loadPromise;
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 3b, plugin should be activated");
-
- clearAllPluginPermissions();
-});
-
-// Test that the click-to-play doorhanger still works
-// when directly navigating to data URLs.
-// Fails, bug XXX. Plugins plus a data url don't fire a load event.
-/*
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab,
- "data:text/html,Hi!<embed id='test' style='width:200px; height:200px' type='application/x-test'/>");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 4a, Should have a click-to-play notification");
-
- // check plugin state
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 4a, plugin should not be activated");
-
- let promise = promisePopupNotification("click-to-play-plugins");
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- // Simulate clicking the "Allow Always" button.
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 4a, plugin should be activated");
-});
-*/
diff --git a/browser/base/content/test/plugins/browser_CTP_drag_drop.js b/browser/base/content/test/plugins/browser_CTP_drag_drop.js
deleted file mode 100644
index 7c9858e27..000000000
--- a/browser/base/content/test/plugins/browser_CTP_drag_drop.js
+++ /dev/null
@@ -1,96 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gNewWindow = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gNewWindow.close();
- gNewWindow = null;
- window.focus();
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-});
-
-add_task(function* () {
- gNewWindow = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
-
- // XXX technically can't load fire before we get this call???
- yield waitForEvent(gNewWindow, "load", null, true);
-
- yield promisePopupNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser);
-
- ok(PopupNotifications.getNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser), "Should have a click-to-play notification in the tab in the new window");
- ok(!PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser), "Should not have a click-to-play notification in the old window now");
-});
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.swapBrowsersAndCloseOther(gBrowser.selectedTab, gNewWindow.gBrowser.selectedTab);
-
- yield promisePopupNotification("click-to-play-plugins", gBrowser.selectedBrowser);
-
- ok(PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser), "Should have a click-to-play notification in the initial tab again");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-});
-
-add_task(function* () {
- yield promisePopupNotification("click-to-play-plugins");
-
- gNewWindow = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
-
- yield promiseWaitForFocus(gNewWindow);
-
- yield promisePopupNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser);
-});
-
-add_task(function* () {
- ok(PopupNotifications.getNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser), "Should have a click-to-play notification in the tab in the new window");
- ok(!PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser), "Should not have a click-to-play notification in the old window now");
-
- let pluginInfo = yield promiseForPluginInfo("test", gNewWindow.gBrowser.selectedBrowser);
- ok(!pluginInfo.activated, "plugin should not be activated");
-
- yield ContentTask.spawn(gNewWindow.gBrowser.selectedBrowser, {}, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser).dismissed && gNewWindow.PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
-});
-
-add_task(function* () {
- // Click the activate button on doorhanger to make sure it works
- gNewWindow.PopupNotifications.panel.firstChild._primaryButton.click();
-
- let pluginInfo = yield promiseForPluginInfo("test", gNewWindow.gBrowser.selectedBrowser);
- ok(pluginInfo.activated, "plugin should be activated");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_hide_overlay.js b/browser/base/content/test/plugins/browser_CTP_hide_overlay.js
deleted file mode 100644
index 5fab7f6ed..000000000
--- a/browser/base/content/test/plugins/browser_CTP_hide_overlay.js
+++ /dev/null
@@ -1,88 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- // Tests that the overlay can be hidden for plugins using the close icon.
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- let closeIcon = doc.getAnonymousElementByAttribute(plugin, "anonid", "closeIcon")
- let bounds = closeIcon.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
-
- Assert.ok(!overlay.classList.contains("visible"), "overlay should be hidden.");
- });
-});
-
-// Test that the overlay cannot be interacted with after the user closes the overlay
-add_task(function* () {
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- let closeIcon = doc.getAnonymousElementByAttribute(plugin, "anonid", "closeIcon")
- let closeIconBounds = closeIcon.getBoundingClientRect();
- let overlayBounds = overlay.getBoundingClientRect();
- let overlayLeft = (overlayBounds.left + overlayBounds.right) / 2;
- let overlayTop = (overlayBounds.left + overlayBounds.right) / 2 ;
- let closeIconLeft = (closeIconBounds.left + closeIconBounds.right) / 2;
- let closeIconTop = (closeIconBounds.top + closeIconBounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- // Simulate clicking on the close icon.
- utils.sendMouseEvent("mousedown", closeIconLeft, closeIconTop, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", closeIconLeft, closeIconTop, 0, 1, 0, false, 0, 0);
-
- // Simulate clicking on the overlay.
- utils.sendMouseEvent("mousedown", overlayLeft, overlayTop, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", overlayLeft, overlayTop, 0, 1, 0, false, 0, 0);
-
- Assert.ok(overlay.hasAttribute("dismissed") && !overlay.classList.contains("visible"),
- "Overlay should be hidden");
- });
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
-
- ok(notification.dismissed, "No notification should be shown");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_iframe.js b/browser/base/content/test/plugins/browser_CTP_iframe.js
deleted file mode 100644
index 58565559f..000000000
--- a/browser/base/content/test/plugins/browser_CTP_iframe.js
+++ /dev/null
@@ -1,48 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_iframe.html");
-
- // Tests that the overlays are visible and actionable if the plugin is in an iframe.
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let frame = content.document.getElementById("frame");
- let doc = frame.contentDocument;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(plugin && overlay.classList.contains("visible"),
- "Test 1, Plugin overlay should exist, not be hidden");
-
- let closeIcon = doc.getAnonymousElementByAttribute(plugin, "anonid", "closeIcon");
- let bounds = closeIcon.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = doc.defaultView.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- Assert.ok(!overlay.classList.contains("visible"),
- "Test 1, Plugin overlay should exist, be hidden");
- });
-});
-
diff --git a/browser/base/content/test/plugins/browser_CTP_multi_allow.js b/browser/base/content/test/plugins/browser_CTP_multi_allow.js
deleted file mode 100644
index 7bc6aaabf..000000000
--- a/browser/base/content/test/plugins/browser_CTP_multi_allow.js
+++ /dev/null
@@ -1,99 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_two_types.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- // Test that the click-to-play doorhanger for multiple plugins shows the correct
- // state when re-opening without reloads or navigation.
-
- let pluginInfo = yield promiseForPluginInfo("test", gBrowser.selectedBrowser);
- ok(!pluginInfo.activated, "plugin should be activated");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(notification, "Test 1a, Should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- is(notification.options.pluginData.size, 2,
- "Test 1a, Should have two types of plugin in the notification");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- is(PopupNotifications.panel.firstChild.childNodes.length, 2, "have child nodes");
-
- let pluginItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- is(item.value, "block", "Test 1a, all plugins should start out blocked");
- if (item.action.pluginName == "Test") {
- pluginItem = item;
- }
- }
-
- // Choose "Allow now" for the test plugin
- pluginItem.value = "allownow";
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test", gBrowser.selectedBrowser);
- ok(pluginInfo.activated, "plugin should be activated");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(notification, "Test 1b, Should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- pluginItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- if (item.action.pluginName == "Test") {
- is(item.value, "allownow", "Test 1b, Test plugin should now be set to 'Allow now'");
- } else {
- is(item.value, "block", "Test 1b, Second Test plugin should still be blocked");
- pluginItem = item;
- }
- }
-
- // Choose "Allow and remember" for the Second Test plugin
- pluginItem.value = "allowalways";
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("secondtestA", gBrowser.selectedBrowser);
- ok(pluginInfo.activated, "plugin should be activated");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(notification, "Test 1c, Should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- if (item.action.pluginName == "Test") {
- is(item.value, "allownow", "Test 1c, Test plugin should be set to 'Allow now'");
- } else {
- is(item.value, "allowalways", "Test 1c, Second Test plugin should be set to 'Allow always'");
- }
- }
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_nonplugins.js b/browser/base/content/test/plugins/browser_CTP_nonplugins.js
deleted file mode 100644
index cdef44d9d..000000000
--- a/browser/base/content/test/plugins/browser_CTP_nonplugins.js
+++ /dev/null
@@ -1,58 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_DISABLED, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_two_types.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
-
- // Test that the click-to-play notification is not shown for non-plugin object elements
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(popupNotification, "Test 1, Should have a click-to-play notification");
-
- let pluginRemovedPromise = waitForEvent(gBrowser.selectedBrowser, "PluginRemoved", null, true, true);
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let plugin = content.document.getElementById("secondtestA");
- plugin.parentNode.removeChild(plugin);
- plugin = content.document.getElementById("secondtestB");
- plugin.parentNode.removeChild(plugin);
-
- let image = content.document.createElement("object");
- image.type = "image/png";
- image.data = "moz.png";
- content.document.body.appendChild(image);
- });
- yield pluginRemovedPromise;
-
- popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(popupNotification, "Test 2, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.parentNode.removeChild(plugin);
- });
-
- popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
- ok(popupNotification, "Test 3, Should still have a click-to-play notification");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_notificationBar.js b/browser/base/content/test/plugins/browser_CTP_notificationBar.js
deleted file mode 100644
index 3c7bd911c..000000000
--- a/browser/base/content/test/plugins/browser_CTP_notificationBar.js
+++ /dev/null
@@ -1,151 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_small.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- // Expecting a notification bar for hidden plugins
- yield promiseForNotificationBar("plugin-hidden", gTestBrowser);
-});
-
-add_task(function* () {
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_small.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notificationBox = gBrowser.getNotificationBox(gTestBrowser);
- yield promiseForCondition(() => notificationBox.getNotificationWithValue("plugin-hidden") === null);
-});
-
-add_task(function* () {
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_overlayed.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Expecting a plugin notification bar when plugins are overlaid.
- yield promiseForNotificationBar("plugin-hidden", gTestBrowser);
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_overlayed.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.equal(plugin.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 3b, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
- });
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 1a, plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 3b, overlay should be hidden.");
- });
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_positioned.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Expecting a plugin notification bar when plugins are overlaid offscreen.
- yield promisePopupNotification("click-to-play-plugins");
- yield promiseForNotificationBar("plugin-hidden", gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.equal(plugin.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 4b, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 4b, overlay should be hidden.");
- });
-});
-
-// Test that the notification bar is getting dismissed when directly activating plugins
-// via the doorhanger.
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_small.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Expecting a plugin notification bar when plugins are overlaid offscreen.
- yield promisePopupNotification("click-to-play-plugins");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.equal(plugin.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 6, Plugin should be click-to-play");
- });
-
- yield promisePopupNotification("click-to-play-plugins");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 6, Should have a click-to-play notification");
-
- // simulate "always allow"
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- let notificationBox = gBrowser.getNotificationBox(gTestBrowser);
- yield promiseForCondition(() => notificationBox.getNotificationWithValue("plugin-hidden") === null);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 7, plugin should be activated");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js b/browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js
deleted file mode 100644
index ccb4d11d7..000000000
--- a/browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js
+++ /dev/null
@@ -1,120 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!popupNotification, "Test 1, Should not have a click-to-play notification");
-});
-
-// Test that the click-to-play overlay is not hidden for elements
-// partially or fully outside the viewport.
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let doc = content.document;
- let p = doc.createElement('embed');
-
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
- p.style.left = "0";
- p.style.bottom = "200px";
-
- doc.getElementById('container').appendChild(p);
- });
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- let doc = content.document;
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 2, overlay should be visible.");
- });
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let doc = content.document;
- let p = doc.createElement('embed');
-
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
- p.style.left = "0";
- p.style.bottom = "-410px";
-
- doc.getElementById('container').appendChild(p);
- });
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let doc = content.document;
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 3, overlay should be visible.");
- });
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let doc = content.document;
- let p = doc.createElement('embed');
-
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
- p.style.left = "-600px";
- p.style.bottom = "0";
-
- doc.getElementById('container').appendChild(p);
- });
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let doc = content.document;
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 4, overlay should be hidden.");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_remove_navigate.js b/browser/base/content/test/plugins/browser_CTP_remove_navigate.js
deleted file mode 100644
index 8ee1c5b5a..000000000
--- a/browser/base/content/test/plugins/browser_CTP_remove_navigate.js
+++ /dev/null
@@ -1,79 +0,0 @@
-const gTestRoot = getRootDirectory(gTestPath);
-const gHttpTestRoot = gTestRoot.replace("chrome://mochitests/content/",
- "http://127.0.0.1:8888/");
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- });
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-});
-
-/**
- * Tests that if a plugin is removed just as we transition to
- * a different page, that we don't show the hidden plugin
- * notification bar on the new page.
- */
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
-
- // Load up a page with a plugin...
- let notificationPromise = waitForNotificationBar("plugin-hidden", gBrowser.selectedBrowser);
- yield promiseTabLoadEvent(gBrowser.selectedTab, gHttpTestRoot + "plugin_small.html");
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
- yield notificationPromise;
-
- // Trigger the PluginRemoved event to be fired, and then immediately
- // browse to a new page.
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.remove();
- });
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla");
-
- // There should be no hidden plugin notification bar at about:mozilla.
- let notificationBox = gBrowser.getNotificationBox(gBrowser.selectedBrowser);
- is(notificationBox.getNotificationWithValue("plugin-hidden"), null,
- "Expected no notification box");
-});
-
-/**
- * Tests that if a plugin is removed just as we transition to
- * a different page with a plugin, that we show the right notification
- * for the new page.
- */
-add_task(function* () {
- // Load up a page with a plugin...
- let notificationPromise = waitForNotificationBar("plugin-hidden", gBrowser.selectedBrowser);
- yield promiseTabLoadEvent(gBrowser.selectedTab, gHttpTestRoot + "plugin_small.html");
- yield promiseUpdatePluginBindings(gBrowser.selectedBrowser);
- yield notificationPromise;
-
- // Trigger the PluginRemoved event to be fired, and then immediately
- // browse to a new page.
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.remove();
- });
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gHttpTestRoot + "plugin_small_2.html");
- let notification = yield waitForNotificationBar("plugin-hidden", gBrowser.selectedBrowser);
- ok(notification, "There should be a notification shown for the new page.");
- // Ensure that the notification is showing information about
- // the x-second-test plugin.
- let label = notification.label;
- ok(label.includes("Second Test"), "Should mention the second plugin");
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_resize.js b/browser/base/content/test/plugins/browser_CTP_resize.js
deleted file mode 100644
index 9b2a2cd82..000000000
--- a/browser/base/content/test/plugins/browser_CTP_resize.js
+++ /dev/null
@@ -1,130 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!popupNotification, "Test 1, Should not have a click-to-play notification");
-
- yield promiseTabLoadEvent(newTab, gTestRoot + "plugin_small.html"); // 10x10 plugin
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-});
-
-// Test that the overlay is hidden for "small" plugin elements and is shown
-// once they are resized to a size that can hold the overlay
-add_task(function* () {
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "Test 2, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 2, overlay should be hidden.");
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.style.width = "300px";
- });
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 3, overlay should be hidden.");
- });
-});
-
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.style.height = "300px";
- });
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- content.document.getElementById("test").clientTop;
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 4, overlay should be visible.");
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.style.width = "10px";
- plugin.style.height = "10px";
- });
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- content.document.getElementById("test").clientTop;
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!(overlay && overlay.classList.contains("visible")),
- "Test 5, overlay should be hidden.");
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- plugin.style.height = "300px";
- plugin.style.width = "300px";
- });
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- content.document.getElementById("test").clientTop;
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 6, overlay should be visible.");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_CTP_zoom.js b/browser/base/content/test/plugins/browser_CTP_zoom.js
deleted file mode 100644
index 8b353232d..000000000
--- a/browser/base/content/test/plugins/browser_CTP_zoom.js
+++ /dev/null
@@ -1,62 +0,0 @@
-"use strict";
-
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- FullZoom.reset(); // must be called before closing the tab we zoomed!
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!popupNotification, "Test 1, Should not have a click-to-play notification");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_zoom.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-});
-
-// Enlarges the zoom level 4 times and tests that the overlay is
-// visible after each enlargement.
-add_task(function* () {
- for (let count = 0; count < 4; count++) {
-
- FullZoom.enlarge();
-
- // Reload the page
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_zoom.html");
- yield promiseUpdatePluginBindings(gTestBrowser);
- yield ContentTask.spawn(gTestBrowser, { count }, function* (args) {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Overlay should be visible for zoom change count " + args.count);
- });
- }
-});
-
-
diff --git a/browser/base/content/test/plugins/browser_blocking.js b/browser/base/content/test/plugins/browser_blocking.js
deleted file mode 100644
index 334ed9f2e..000000000
--- a/browser/base/content/test/plugins/browser_blocking.js
+++ /dev/null
@@ -1,349 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-function updateAllTestPlugins(aState) {
- setTestPluginEnabledState(aState, "Test Plug-in");
- setTestPluginEnabledState(aState, "Second Test Plug-in");
-}
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_ENABLED);
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- }));
-});
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- // Prime the content process
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>hi</html>");
-
- // Make sure the blocklist service(s) are running
- Components.classes["@mozilla.org/extensions/blocklist;1"]
- .getService(Components.interfaces.nsIBlocklistService);
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-});
-
-add_task(function* () {
- // enable hard blocklisting for the next test
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginHard.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
- ok(notification.dismissed, "Test 5: The plugin notification should be dismissed by default");
-
- yield promiseForNotificationShown(notification);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_BLOCKLISTED, "Test 5, plugin fallback type should be PLUGIN_BLOCKLISTED");
-
- is(notification.options.pluginData.size, 1, "Test 5: Only the blocked plugin should be present in the notification");
- ok(PopupNotifications.panel.firstChild._buttonContainer.hidden, "Part 5: The blocked plugins notification should not have any buttons visible.");
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
-
-// Tests a vulnerable, updatable plugin
-
-add_task(function* () {
- // enable hard blocklisting of test
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginVulnerableUpdatable.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_UPDATABLE,
- "Test 18a, plugin fallback type should be PLUGIN_VULNERABLE_UPDATABLE");
- ok(!pluginInfo.activated, "Test 18a, Plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 18a, Plugin overlay should exist, not be hidden");
-
- let updateLink = doc.getAnonymousElementByAttribute(plugin, "anonid", "checkForUpdatesLink");
- Assert.ok(updateLink.style.visibility != "hidden",
- "Test 18a, Plugin should have an update link");
- });
-
- let promise = waitForEvent(gBrowser.tabContainer, "TabOpen", null, true);
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let updateLink = doc.getAnonymousElementByAttribute(plugin, "anonid", "checkForUpdatesLink");
- let bounds = updateLink.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- promise = waitForEvent(gBrowser.tabContainer, "TabClose", null, true);
- gBrowser.removeCurrentTab();
- yield promise;
-});
-
-add_task(function* () {
- // clicking the update link should not activate the plugin
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_UPDATABLE,
- "Test 18a, plugin fallback type should be PLUGIN_VULNERABLE_UPDATABLE");
- ok(!pluginInfo.activated, "Test 18b, Plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 18b, Plugin overlay should exist, not be hidden");
- });
-});
-
-// Tests a vulnerable plugin with no update
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginVulnerableNoUpdate.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 18c, Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_NO_UPDATE,
- "Test 18c, plugin fallback type should be PLUGIN_VULNERABLE_NO_UPDATE");
- ok(!pluginInfo.activated, "Test 18c, Plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(overlay && overlay.classList.contains("visible"),
- "Test 18c, Plugin overlay should exist, not be hidden");
-
- let updateLink = doc.getAnonymousElementByAttribute(plugin, "anonid", "checkForUpdatesLink");
- Assert.ok(updateLink && updateLink.style.display != "block",
- "Test 18c, Plugin should not have an update link");
- });
-
- // check that click "Always allow" works with blocked plugins
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_NO_UPDATE,
- "Test 18c, plugin fallback type should be PLUGIN_VULNERABLE_NO_UPDATE");
- ok(pluginInfo.activated, "Test 18c, Plugin should be activated");
- let enabledState = getTestPluginEnabledState();
- ok(enabledState, "Test 18c, Plugin enabled state should be STATE_CLICKTOPLAY");
-});
-
-// continue testing "Always allow", make sure it sticks.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 18d, Waited too long for plugin to activate");
-
- clearAllPluginPermissions();
-});
-
-// clicking the in-content overlay of a vulnerable plugin should bring
-// up the notification and not directly activate the plugin
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 18f, Should have a click-to-play notification");
- ok(notification.dismissed, "Test 18f, notification should start dismissed");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 18f, Waited too long for plugin to activate");
-
- var oldEventCallback = notification.options.eventCallback;
- let promise = promiseForCondition(() => oldEventCallback == null);
- notification.options.eventCallback = function() {
- if (oldEventCallback) {
- oldEventCallback();
- }
- oldEventCallback = null;
- };
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- ok(notification, "Test 18g, Should have a click-to-play notification");
- ok(!notification.dismissed, "Test 18g, notification should be open");
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 18g, Plugin should not be activated");
-});
-
-// Test that "always allow"-ing a plugin will not allow it when it becomes
-// blocklisted.
-add_task(function* () {
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 24a, Should have a click-to-play notification");
-
- // Plugin should start as CTP
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 24a, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
- ok(!pluginInfo.activated, "Test 24a, Plugin should not be active.");
-
- // simulate "always allow"
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 24a, Plugin should be active.");
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginVulnerableUpdatable.xml", gTestBrowser);
-});
-
-// the plugin is now blocklisted, so it should not automatically load
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 24b, Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_UPDATABLE,
- "Test 24b, plugin fallback type should be PLUGIN_VULNERABLE_UPDATABLE");
- ok(!pluginInfo.activated, "Test 24b, Plugin should not be active.");
-
- // simulate "always allow"
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 24b, Plugin should be active.");
-
- clearAllPluginPermissions();
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
-
-// Plugin sync removal test. Note this test produces a notification drop down since
-// the plugin we add has zero dims.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_syncRemoved.html");
-
- // Maybe there some better trick here, we need to wait for the page load, then
- // wait for the js to execute in the page.
- yield waitForMs(500);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
- ok(notification, "Test 25: There should be a plugin notification even if the plugin was immediately removed");
- ok(notification.dismissed, "Test 25: The notification should be dismissed by default");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>hi</html>");
-});
-
-// Tests a page with a blocked plugin in it and make sure the infoURL property
-// the blocklist file gets used.
-add_task(function* () {
- clearAllPluginPermissions();
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginInfoURL.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
-
- // Since the plugin notification is dismissed by default, reshow it.
- yield promiseForNotificationShown(notification);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_BLOCKLISTED,
- "Test 26, plugin fallback type should be PLUGIN_BLOCKLISTED");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(!objLoadingContent.activated, "Plugin should not be activated.");
- });
-
- const testUrl = "http://test.url.com/";
-
- let firstPanelChild = PopupNotifications.panel.firstChild;
- let infoLink = document.getAnonymousElementByAttribute(firstPanelChild, "anonid",
- "click-to-play-plugins-notification-link");
- is(infoLink.href, testUrl,
- "Test 26, the notification URL needs to match the infoURL from the blocklist file.");
-});
-
diff --git a/browser/base/content/test/plugins/browser_blocklist_content.js b/browser/base/content/test/plugins/browser_blocklist_content.js
deleted file mode 100644
index bf4e159bc..000000000
--- a/browser/base/content/test/plugins/browser_blocklist_content.js
+++ /dev/null
@@ -1,104 +0,0 @@
-var gTestBrowser = null;
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gChromeRoot = getRootDirectory(gTestPath);
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- }));
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
-
- // Prime the blocklist service, the remote service doesn't launch on startup.
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let test = content.document.getElementById("test");
- Assert.ok(test.activated, "task 1a: test plugin should be activated!");
- });
-});
-
-// Load a fresh page, load a new plugin blocklist, then load the same page again.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>GO!</html>");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginHard.xml", gTestBrowser);
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let test = content.document.getElementById("test");
- ok(!test.activated, "task 2a: test plugin shouldn't activate!");
- });
-});
-
-// Unload the block list and lets do this again, only this time lets
-// hack around in the content blocklist service maliciously.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>GO!</html>");
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-
- // Hack the planet! Load our blocklist shim, so we can mess with blocklist
- // return results in the content process. Active until we close our tab.
- let mm = gTestBrowser.messageManager;
- info("test 3a: loading " + gChromeRoot + "blocklist_proxy.js" + "\n");
- mm.loadFrameScript(gChromeRoot + "blocklist_proxy.js", true);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let test = content.document.getElementById("test");
- Assert.ok(test.activated, "task 3a: test plugin should be activated!");
- });
-});
-
-// Load a fresh page, load a new plugin blocklist, then load the same page again.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>GO!</html>");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginHard.xml", gTestBrowser);
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let test = content.document.getElementById("test");
- Assert.ok(!test.activated, "task 4a: test plugin shouldn't activate!");
- });
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
diff --git a/browser/base/content/test/plugins/browser_bug743421.js b/browser/base/content/test/plugins/browser_bug743421.js
deleted file mode 100644
index 966e7b012..000000000
--- a/browser/base/content/test/plugins/browser_bug743421.js
+++ /dev/null
@@ -1,119 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- }));
-});
-
-add_task(function* () {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-
- // Prime the blocklist service, the remote service doesn't launch on startup.
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
-
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
-
-// Tests that navigation within the page and the window.history API doesn't break click-to-play state.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_add_dynamically.html");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!notification, "Test 1a, Should not have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin());
- });
-
- yield promisePopupNotification("click-to-play-plugins");
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementsByTagName("embed")[0];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(!objLoadingContent.activated, "Test 1b, Plugin should not be activated");
- });
-
- // Click the activate button on doorhanger to make sure it works
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
-
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementsByTagName("embed")[0];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated, "Test 1b, Plugin should be activated");
- });
-});
-
-add_task(function* () {
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 1c, Should still have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin());
- let plugin = content.document.getElementsByTagName("embed")[1];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated,
- "Test 1c, Newly inserted plugin in activated page should be activated");
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementsByTagName("embed")[1];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated, "Test 1d, Plugin should be activated");
-
- let promise = ContentTaskUtils.waitForEvent(content, "hashchange");
- content.location += "#anchorNavigation";
- yield promise;
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin());
- let plugin = content.document.getElementsByTagName("embed")[2];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated, "Test 1e, Plugin should be activated");
- });
-});
-
-add_task(function* () {
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementsByTagName("embed")[2];
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated, "Test 1f, Plugin should be activated");
-
- content.history.replaceState({}, "", "replacedState");
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin());
- plugin = content.document.getElementsByTagName("embed")[3];
- objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- Assert.ok(objLoadingContent.activated, "Test 1g, Plugin should be activated");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_bug744745.js b/browser/base/content/test/plugins/browser_bug744745.js
deleted file mode 100644
index c9f552a4e..000000000
--- a/browser/base/content/test/plugins/browser_bug744745.js
+++ /dev/null
@@ -1,50 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gNumPluginBindingsAttached = 0;
-
-function pluginBindingAttached() {
- gNumPluginBindingsAttached++;
- if (gNumPluginBindingsAttached != 1) {
- ok(false, "if we've gotten here, something is quite wrong");
- }
-}
-
-add_task(function* () {
- registerCleanupFunction(function () {
- gTestBrowser.removeEventListener("PluginBindingAttached", pluginBindingAttached, true, true);
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- gTestBrowser.addEventListener("PluginBindingAttached", pluginBindingAttached, true, true);
-
- let testRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
- yield promiseTabLoadEvent(gBrowser.selectedTab, testRoot + "plugin_bug744745.html");
-
- yield promiseForCondition(function () { return gNumPluginBindingsAttached == 1; });
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("test");
- if (!plugin) {
- Assert.ok(false, "plugin element not available.");
- return;
- }
- // We can't use MochiKit's routine
- let style = content.getComputedStyle(plugin);
- Assert.ok(("opacity" in style) && style.opacity == 1, "plugin style properly configured.");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_bug787619.js b/browser/base/content/test/plugins/browser_bug787619.js
deleted file mode 100644
index bfd52258c..000000000
--- a/browser/base/content/test/plugins/browser_bug787619.js
+++ /dev/null
@@ -1,65 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gWrapperClickCount = 0;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- let testRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
- yield promiseTabLoadEvent(gBrowser.selectedTab, testRoot + "plugin_bug787619.html");
-
- // Due to layout being async, "PluginBindAttached" may trigger later.
- // This forces a layout flush, thus triggering it, and schedules the
- // test so it is definitely executed afterwards.
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // check plugin state
- let pluginInfo = yield promiseForPluginInfo("plugin");
- ok(!pluginInfo.activated, "1a plugin should not be activated");
-
- // click the overlay to prompt
- let promise = promisePopupNotification("click-to-play-plugins");
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- let plugin = content.document.getElementById("plugin");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
- yield promise;
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("plugin");
- ok(!pluginInfo.activated, "1b plugin should not be activated");
-
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- // check plugin state
- pluginInfo = yield promiseForPluginInfo("plugin");
- ok(pluginInfo.activated, "plugin should be activated");
-
- is(gWrapperClickCount, 0, 'wrapper should not have received any clicks');
-});
diff --git a/browser/base/content/test/plugins/browser_bug797677.js b/browser/base/content/test/plugins/browser_bug797677.js
deleted file mode 100644
index 1ae9f5047..000000000
--- a/browser/base/content/test/plugins/browser_bug797677.js
+++ /dev/null
@@ -1,43 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gConsoleErrors = 0;
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- consoleService.unregisterListener(errorListener);
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- let consoleService = Cc["@mozilla.org/consoleservice;1"]
- .getService(Ci.nsIConsoleService);
- let errorListener = {
- observe: function(aMessage) {
- if (aMessage.message.includes("NS_ERROR_FAILURE"))
- gConsoleErrors++;
- }
- };
- consoleService.registerListener(errorListener);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_bug797677.html");
-
- let pluginInfo = yield promiseForPluginInfo("plugin");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_UNSUPPORTED, "plugin should not have been found.");
-
- // simple cpows
- yield ContentTask.spawn(gTestBrowser, null, function() {
- let plugin = content.document.getElementById("plugin");
- ok(plugin, "plugin should be in the page");
- });
- is(gConsoleErrors, 0, "should have no console errors");
-});
diff --git a/browser/base/content/test/plugins/browser_bug812562.js b/browser/base/content/test/plugins/browser_bug812562.js
deleted file mode 100644
index be7b00b22..000000000
--- a/browser/base/content/test/plugins/browser_bug812562.js
+++ /dev/null
@@ -1,80 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- Services.prefs.clearUserPref("plugins.click_to_play");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- }));
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- // Prime the blocklist service, the remote service doesn't launch on startup.
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-});
-
-// Tests that the going back will reshow the notification for click-to-play
-// blocklisted plugins
-add_task(function* () {
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginVulnerableUpdatable.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "test part 1: Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_UPDATABLE, "plugin should be marked as VULNERABLE");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- Assert.ok(!!content.document.getElementById("test"),
- "test part 1: plugin should not be activated");
- });
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
-});
-
-add_task(function* () {
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!popupNotification, "test part 2: Should not have a click-to-play notification");
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- Assert.ok(!content.document.getElementById("test"),
- "test part 2: plugin should not be activated");
- });
-
- let obsPromise = TestUtils.topicObserved("PopupNotifications-updateNotShowing");
- let overlayPromise = promisePopupNotification("click-to-play-plugins");
- gTestBrowser.goBack();
- yield obsPromise;
- yield overlayPromise;
-});
-
-add_task(function* () {
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "test part 3: Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_UPDATABLE, "plugin should be marked as VULNERABLE");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- Assert.ok(!!content.document.getElementById("test"),
- "test part 3: plugin should not be activated");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_bug818118.js b/browser/base/content/test/plugins/browser_bug818118.js
deleted file mode 100644
index 9dd6e22e7..000000000
--- a/browser/base/content/test/plugins/browser_bug818118.js
+++ /dev/null
@@ -1,40 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_both.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY, "plugin should be click to play");
- ok(!pluginInfo.activated, "plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, () => {
- let unknown = content.document.getElementById("unknown");
- ok(unknown, "should have unknown plugin in page");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_bug820497.js b/browser/base/content/test/plugins/browser_bug820497.js
deleted file mode 100644
index b2e0f5268..000000000
--- a/browser/base/content/test/plugins/browser_bug820497.js
+++ /dev/null
@@ -1,71 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var gNumPluginBindingsAttached = 0;
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-
- gTestBrowser.addEventListener("PluginBindingAttached", function () { gNumPluginBindingsAttached++ }, true, true);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_bug820497.html");
-
- yield promiseForCondition(function () { return gNumPluginBindingsAttached == 1; });
-
- yield ContentTask.spawn(gTestBrowser, null, () => {
- // Note we add the second plugin in the code farther down, so there's
- // no way we got here with anything but one plugin loaded.
- let doc = content.document;
- let testplugin = doc.getElementById("test");
- ok(testplugin, "should have test plugin");
- let secondtestplugin = doc.getElementById("secondtest");
- ok(!secondtestplugin, "should not yet have second test plugin");
- });
-
- yield promisePopupNotification("click-to-play-plugins");
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- is(notification.options.pluginData.size, 1, "should be 1 type of plugin in the popup notification");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- XPCNativeWrapper.unwrap(content).addSecondPlugin();
- });
-
- yield promiseForCondition(function () { return gNumPluginBindingsAttached == 2; });
-
- yield ContentTask.spawn(gTestBrowser, null, () => {
- let doc = content.document;
- let testplugin = doc.getElementById("test");
- ok(testplugin, "should have test plugin");
- let secondtestplugin = doc.getElementById("secondtest");
- ok(secondtestplugin, "should have second test plugin");
- });
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
-
- ok(notification, "should have popup notification");
-
- yield promiseForNotificationShown(notification);
-
- is(notification.options.pluginData.size, 2, "aited too long for 2 types of plugins in popup notification");
-});
diff --git a/browser/base/content/test/plugins/browser_clearplugindata.html b/browser/base/content/test/plugins/browser_clearplugindata.html
deleted file mode 100644
index 243350ba4..000000000
--- a/browser/base/content/test/plugins/browser_clearplugindata.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<html>
- <head>
- <title>Plugin Clear Site Data sanitize test</title>
-
- <embed id="plugin1" type="application/x-test" width="200" height="200"></embed>
-
- <script type="application/javascript">
- function testSteps()
- {
- // Make sure clearing by timerange is supported.
- var p = document.getElementById("plugin1");
- p.setSitesWithDataCapabilities(true);
-
- p.setSitesWithData(
- "foo.com:0:5," +
- "bar.com:0:100," +
- "baz.com:1:5," +
- "qux.com:1:100"
- );
- }
- </script>
- </head>
-
- <body onload="testSteps();"></body>
-
-</html>
diff --git a/browser/base/content/test/plugins/browser_clearplugindata.js b/browser/base/content/test/plugins/browser_clearplugindata.js
deleted file mode 100644
index 69d474fed..000000000
--- a/browser/base/content/test/plugins/browser_clearplugindata.js
+++ /dev/null
@@ -1,127 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-var gTestBrowser = null;
-
-// Test clearing plugin data using sanitize.js.
-const testURL1 = gTestRoot + "browser_clearplugindata.html";
-const testURL2 = gTestRoot + "browser_clearplugindata_noage.html";
-
-var tempScope = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tempScope);
-var Sanitizer = tempScope.Sanitizer;
-
-const pluginHostIface = Ci.nsIPluginHost;
-var pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
-pluginHost.QueryInterface(pluginHostIface);
-
-var pluginTag = getTestPlugin();
-var sanitizer = null;
-
-function stored(needles) {
- let something = pluginHost.siteHasData(this.pluginTag, null);
- if (!needles)
- return something;
-
- if (!something)
- return false;
-
- for (let i = 0; i < needles.length; ++i) {
- if (!pluginHost.siteHasData(this.pluginTag, needles[i]))
- return false;
- }
- return true;
-}
-
-add_task(function* () {
- registerCleanupFunction(function () {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- if (gTestBrowser) {
- gBrowser.removeCurrentTab();
- }
- window.focus();
- gTestBrowser = null;
- });
-});
-
-add_task(function* () {
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
-
- sanitizer = new Sanitizer();
- sanitizer.ignoreTimespan = false;
- sanitizer.prefDomain = "privacy.cpd.";
- let itemPrefs = gPrefService.getBranch(sanitizer.prefDomain);
- itemPrefs.setBoolPref("history", false);
- itemPrefs.setBoolPref("downloads", false);
- itemPrefs.setBoolPref("cache", false);
- itemPrefs.setBoolPref("cookies", true); // plugin data
- itemPrefs.setBoolPref("formdata", false);
- itemPrefs.setBoolPref("offlineApps", false);
- itemPrefs.setBoolPref("passwords", false);
- itemPrefs.setBoolPref("sessions", false);
- itemPrefs.setBoolPref("siteSettings", false);
-});
-
-add_task(function* () {
- // Load page to set data for the plugin.
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, testURL1);
-
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- ok(stored(["foo.com", "bar.com", "baz.com", "qux.com"]),
- "Data stored for sites");
-
- // Clear 20 seconds ago
- let now_uSec = Date.now() * 1000;
- sanitizer.range = [now_uSec - 20*1000000, now_uSec];
- yield sanitizer.sanitize();
-
- ok(stored(["bar.com", "qux.com"]), "Data stored for sites");
- ok(!stored(["foo.com"]), "Data cleared for foo.com");
- ok(!stored(["baz.com"]), "Data cleared for baz.com");
-
- // Clear everything
- sanitizer.range = null;
- yield sanitizer.sanitize();
-
- ok(!stored(null), "All data cleared");
-
- gBrowser.removeCurrentTab();
- gTestBrowser = null;
-});
-
-add_task(function* () {
- // Load page to set data for the plugin.
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, testURL2);
-
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- ok(stored(["foo.com", "bar.com", "baz.com", "qux.com"]),
- "Data stored for sites");
-
- // Attempt to clear 20 seconds ago. The plugin will throw
- // NS_ERROR_PLUGIN_TIME_RANGE_NOT_SUPPORTED, which should result in us
- // clearing all data regardless of age.
- let now_uSec = Date.now() * 1000;
- sanitizer.range = [now_uSec - 20*1000000, now_uSec];
- yield sanitizer.sanitize();
-
- ok(!stored(null), "All data cleared");
-
- gBrowser.removeCurrentTab();
- gTestBrowser = null;
-});
-
diff --git a/browser/base/content/test/plugins/browser_clearplugindata_noage.html b/browser/base/content/test/plugins/browser_clearplugindata_noage.html
deleted file mode 100644
index 820979541..000000000
--- a/browser/base/content/test/plugins/browser_clearplugindata_noage.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<html>
- <head>
- <title>Plugin Clear Site Data sanitize test without age</title>
-
- <embed id="plugin1" type="application/x-test" width="200" height="200"></embed>
-
- <script type="application/javascript">
- function testSteps()
- {
- // Make sure clearing by timerange is disabled.
- var p = document.getElementById("plugin1");
- p.setSitesWithDataCapabilities(false);
-
- p.setSitesWithData(
- "foo.com:0:5," +
- "bar.com:0:100," +
- "baz.com:1:5," +
- "qux.com:1:100"
- );
- }
- </script>
- </head>
-
- <body onload="testSteps();"></body>
-
-</html>
diff --git a/browser/base/content/test/plugins/browser_globalplugin_crashinfobar.js b/browser/base/content/test/plugins/browser_globalplugin_crashinfobar.js
deleted file mode 100644
index bdca32e70..000000000
--- a/browser/base/content/test/plugins/browser_globalplugin_crashinfobar.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Test that the notification bar for crashed GMPs works.
- */
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank",
- }, function* (browser) {
- yield ContentTask.spawn(browser, null, function* () {
- const GMP_CRASH_EVENT = {
- pluginID: 1,
- pluginName: "GlobalTestPlugin",
- submittedCrashReport: false,
- bubbles: true,
- cancelable: true,
- gmpPlugin: true,
- };
-
- let crashEvent = new content.PluginCrashedEvent("PluginCrashed",
- GMP_CRASH_EVENT);
- content.dispatchEvent(crashEvent);
- });
-
- let notification = yield waitForNotificationBar("plugin-crashed", browser);
-
- let notificationBox = gBrowser.getNotificationBox(browser);
- ok(notification, "Infobar was shown.");
- is(notification.priority, notificationBox.PRIORITY_WARNING_MEDIUM,
- "Correct priority.");
- is(notification.getAttribute("label"),
- "The GlobalTestPlugin plugin has crashed.",
- "Correct message.");
- });
-});
diff --git a/browser/base/content/test/plugins/browser_pageInfo_plugins.js b/browser/base/content/test/plugins/browser_pageInfo_plugins.js
deleted file mode 100644
index 0d941e0fa..000000000
--- a/browser/base/content/test/plugins/browser_pageInfo_plugins.js
+++ /dev/null
@@ -1,191 +0,0 @@
-var gHttpTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPageInfo = null;
-var gNextTest = null;
-var gTestBrowser = null;
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"]
- .getService(Components.interfaces.nsIPluginHost);
-var gPermissionManager = Components.classes["@mozilla.org/permissionmanager;1"]
- .getService(Components.interfaces.nsIPermissionManager);
-var gTestPermissionString = gPluginHost.getPermissionStringForType("application/x-test");
-var gSecondTestPermissionString = gPluginHost.getPermissionStringForType("application/x-second-test");
-
-function doOnPageLoad(url, continuation) {
- gNextTest = continuation;
- gTestBrowser.addEventListener("load", pageLoad, true);
- gTestBrowser.contentWindow.location = url;
-}
-
-function pageLoad() {
- gTestBrowser.removeEventListener("load", pageLoad);
- // The plugin events are async dispatched and can come after the load event
- // This just allows the events to fire before we then go on to test the states
- executeSoon(gNextTest);
-}
-
-function doOnOpenPageInfo(continuation) {
- Services.obs.addObserver(pageInfoObserve, "page-info-dialog-loaded", false);
- gNextTest = continuation;
- // An explanation: it looks like the test harness complains about leaked
- // windows if we don't keep a reference to every window we've opened.
- // So, don't reuse pointers to opened Page Info windows - simply append
- // to this list.
- gPageInfo = BrowserPageInfo(null, "permTab");
-}
-
-function pageInfoObserve(win, topic, data) {
- Services.obs.removeObserver(pageInfoObserve, "page-info-dialog-loaded");
- gPageInfo.onFinished.push(() => executeSoon(gNextTest));
-}
-
-function finishTest() {
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gTestPermissionString);
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gSecondTestPermissionString);
- Services.prefs.clearUserPref("plugins.click_to_play");
- gBrowser.removeCurrentTab();
-
- gPageInfo = null;
- gNextTest = null;
- gTestBrowser = null;
- gPluginHost = null;
- gPermissionManager = null;
-
- executeSoon(finish);
-}
-
-function test() {
- waitForExplicitFinish();
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gTestPermissionString);
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gSecondTestPermissionString);
- doOnPageLoad(gHttpTestRoot + "plugin_two_types.html", testPart1a);
-}
-
-// The first test plugin is CtP and the second test plugin is enabled.
-function testPart1a() {
- let test = gTestBrowser.contentDocument.getElementById("test");
- let objLoadingContent = test.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!objLoadingContent.activated, "part 1a: Test plugin should not be activated");
- let secondtest = gTestBrowser.contentDocument.getElementById("secondtestA");
- objLoadingContent = secondtest.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(objLoadingContent.activated, "part 1a: Second Test plugin should be activated");
-
- doOnOpenPageInfo(testPart1b);
-}
-
-function testPart1b() {
- let testRadioGroup = gPageInfo.document.getElementById(gTestPermissionString + "RadioGroup");
- let testRadioDefault = gPageInfo.document.getElementById(gTestPermissionString + "#0");
-
- is(testRadioGroup.selectedItem, testRadioDefault, "part 1b: Test radio group should be set to 'Default'");
- let testRadioAllow = gPageInfo.document.getElementById(gTestPermissionString + "#1");
- testRadioGroup.selectedItem = testRadioAllow;
- testRadioAllow.doCommand();
-
- let secondtestRadioGroup = gPageInfo.document.getElementById(gSecondTestPermissionString + "RadioGroup");
- let secondtestRadioDefault = gPageInfo.document.getElementById(gSecondTestPermissionString + "#0");
- is(secondtestRadioGroup.selectedItem, secondtestRadioDefault, "part 1b: Second Test radio group should be set to 'Default'");
- let secondtestRadioAsk = gPageInfo.document.getElementById(gSecondTestPermissionString + "#3");
- secondtestRadioGroup.selectedItem = secondtestRadioAsk;
- secondtestRadioAsk.doCommand();
-
- doOnPageLoad(gHttpTestRoot + "plugin_two_types.html", testPart2);
-}
-
-// Now, the Test plugin should be allowed, and the Test2 plugin should be CtP
-function testPart2() {
- let test = gTestBrowser.contentDocument.getElementById("test").
- QueryInterface(Ci.nsIObjectLoadingContent);
- ok(test.activated, "part 2: Test plugin should be activated");
-
- let secondtest = gTestBrowser.contentDocument.getElementById("secondtestA").
- QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!secondtest.activated, "part 2: Second Test plugin should not be activated");
- is(secondtest.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "part 2: Second test plugin should be click-to-play.");
-
- let testRadioGroup = gPageInfo.document.getElementById(gTestPermissionString + "RadioGroup");
- let testRadioAllow = gPageInfo.document.getElementById(gTestPermissionString + "#1");
- is(testRadioGroup.selectedItem, testRadioAllow, "part 2: Test radio group should be set to 'Allow'");
- let testRadioBlock = gPageInfo.document.getElementById(gTestPermissionString + "#2");
- testRadioGroup.selectedItem = testRadioBlock;
- testRadioBlock.doCommand();
-
- let secondtestRadioGroup = gPageInfo.document.getElementById(gSecondTestPermissionString + "RadioGroup");
- let secondtestRadioAsk = gPageInfo.document.getElementById(gSecondTestPermissionString + "#3");
- is(secondtestRadioGroup.selectedItem, secondtestRadioAsk, "part 2: Second Test radio group should be set to 'Always Ask'");
- let secondtestRadioBlock = gPageInfo.document.getElementById(gSecondTestPermissionString + "#2");
- secondtestRadioGroup.selectedItem = secondtestRadioBlock;
- secondtestRadioBlock.doCommand();
-
- doOnPageLoad(gHttpTestRoot + "plugin_two_types.html", testPart3);
-}
-
-// Now, all the things should be blocked
-function testPart3() {
- let test = gTestBrowser.contentDocument.getElementById("test").
- QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!test.activated, "part 3: Test plugin should not be activated");
- is(test.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_DISABLED,
- "part 3: Test plugin should be marked as PLUGIN_DISABLED");
-
- let secondtest = gTestBrowser.contentDocument.getElementById("secondtestA").
- QueryInterface(Ci.nsIObjectLoadingContent);
-
- ok(!secondtest.activated, "part 3: Second Test plugin should not be activated");
- is(secondtest.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_DISABLED,
- "part 3: Second test plugin should be marked as PLUGIN_DISABLED");
-
- // reset permissions
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gTestPermissionString);
- gPermissionManager.remove(makeURI("http://127.0.0.1:8888/"), gSecondTestPermissionString);
- // check that changing the permissions affects the radio state in the
- // open Page Info window
- let testRadioGroup = gPageInfo.document.getElementById(gTestPermissionString + "RadioGroup");
- let testRadioDefault = gPageInfo.document.getElementById(gTestPermissionString + "#0");
- is(testRadioGroup.selectedItem, testRadioDefault, "part 3: Test radio group should be set to 'Default'");
- let secondtestRadioGroup = gPageInfo.document.getElementById(gSecondTestPermissionString + "RadioGroup");
- let secondtestRadioDefault = gPageInfo.document.getElementById(gSecondTestPermissionString + "#0");
- is(secondtestRadioGroup.selectedItem, secondtestRadioDefault, "part 3: Second Test radio group should be set to 'Default'");
-
- doOnPageLoad(gHttpTestRoot + "plugin_two_types.html", testPart4a);
-}
-
-// Now test that setting permission directly (as from the popup notification)
-// immediately influences Page Info.
-function testPart4a() {
- // simulate "allow" from the doorhanger
- gPermissionManager.add(gTestBrowser.currentURI, gTestPermissionString, Ci.nsIPermissionManager.ALLOW_ACTION);
- gPermissionManager.add(gTestBrowser.currentURI, gSecondTestPermissionString, Ci.nsIPermissionManager.ALLOW_ACTION);
-
- // check (again) that changing the permissions affects the radio state in the
- // open Page Info window
- let testRadioGroup = gPageInfo.document.getElementById(gTestPermissionString + "RadioGroup");
- let testRadioAllow = gPageInfo.document.getElementById(gTestPermissionString + "#1");
- is(testRadioGroup.selectedItem, testRadioAllow, "part 4a: Test radio group should be set to 'Allow'");
- let secondtestRadioGroup = gPageInfo.document.getElementById(gSecondTestPermissionString + "RadioGroup");
- let secondtestRadioAllow = gPageInfo.document.getElementById(gSecondTestPermissionString + "#1");
- is(secondtestRadioGroup.selectedItem, secondtestRadioAllow, "part 4a: Second Test radio group should be set to 'Always Allow'");
-
- // now close Page Info and see that it opens with the right settings
- gPageInfo.close();
- doOnOpenPageInfo(testPart4b);
-}
-
-// check that "always allow" resulted in the radio buttons getting set to allow
-function testPart4b() {
- let testRadioGroup = gPageInfo.document.getElementById(gTestPermissionString + "RadioGroup");
- let testRadioAllow = gPageInfo.document.getElementById(gTestPermissionString + "#1");
- is(testRadioGroup.selectedItem, testRadioAllow, "part 4b: Test radio group should be set to 'Allow'");
-
- let secondtestRadioGroup = gPageInfo.document.getElementById(gSecondTestPermissionString + "RadioGroup");
- let secondtestRadioAllow = gPageInfo.document.getElementById(gSecondTestPermissionString + "#1");
- is(secondtestRadioGroup.selectedItem, secondtestRadioAllow, "part 4b: Second Test radio group should be set to 'Allow'");
-
- Services.prefs.setBoolPref("plugins.click_to_play", false);
- gPageInfo.close();
- finishTest();
-}
diff --git a/browser/base/content/test/plugins/browser_pluginCrashCommentAndURL.js b/browser/base/content/test/plugins/browser_pluginCrashCommentAndURL.js
deleted file mode 100644
index ab4743f6f..000000000
--- a/browser/base/content/test/plugins/browser_pluginCrashCommentAndURL.js
+++ /dev/null
@@ -1,207 +0,0 @@
-Cu.import("resource://gre/modules/CrashSubmit.jsm", this);
-
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gTestBrowser = null;
-var config = {};
-
-add_task(function* () {
- // The test harness sets MOZ_CRASHREPORTER_NO_REPORT, which disables plugin
- // crash reports. This test needs them enabled. The test also needs a mock
- // report server, and fortunately one is already set up by toolkit/
- // crashreporter/test/Makefile.in. Assign its URL to MOZ_CRASHREPORTER_URL,
- // which CrashSubmit.jsm uses as a server override.
- let env = Components.classes["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- let noReport = env.get("MOZ_CRASHREPORTER_NO_REPORT");
- let serverUrl = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", "");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- // Crash immediately
- Services.prefs.setIntPref("dom.ipc.plugins.timeoutSecs", 0);
-
- registerCleanupFunction(Task.async(function*() {
- Services.prefs.clearUserPref("dom.ipc.plugins.timeoutSecs");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", noReport);
- env.set("MOZ_CRASHREPORTER_URL", serverUrl);
- env = null;
- config = null;
- gTestBrowser = null;
- gBrowser.removeCurrentTab();
- window.focus();
- }));
-});
-
-add_task(function* () {
- config = {
- shouldSubmissionUIBeVisible: true,
- comment: "",
- urlOptIn: false
- };
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED);
-
- let pluginCrashed = promisePluginCrashed();
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_crashCommentAndURL.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Wait for the plugin to crash
- yield pluginCrashed;
-
- let crashReportStatus = TestUtils.topicObserved("crash-report-status", onSubmitStatus);
-
- // Test that the crash submission UI is actually visible and submit the crash report.
- yield ContentTask.spawn(gTestBrowser, config, function* (aConfig) {
- let doc = content.document;
- let plugin = doc.getElementById("plugin");
- let pleaseSubmit = doc.getAnonymousElementByAttribute(plugin, "anonid", "pleaseSubmit");
- let submitButton = doc.getAnonymousElementByAttribute(plugin, "anonid", "submitButton");
- // Test that we don't send the URL when urlOptIn is false.
- doc.getAnonymousElementByAttribute(plugin, "anonid", "submitURLOptIn").checked = aConfig.urlOptIn;
- submitButton.click();
- Assert.equal(content.getComputedStyle(pleaseSubmit).display == "block",
- aConfig.shouldSubmissionUIBeVisible, "The crash UI should be visible");
- });
-
- yield crashReportStatus;
-});
-
-add_task(function* () {
- config = {
- shouldSubmissionUIBeVisible: true,
- comment: "a test comment",
- urlOptIn: true
- };
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED);
-
- let pluginCrashed = promisePluginCrashed();
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_crashCommentAndURL.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Wait for the plugin to crash
- yield pluginCrashed;
-
- let crashReportStatus = TestUtils.topicObserved("crash-report-status", onSubmitStatus);
-
- // Test that the crash submission UI is actually visible and submit the crash report.
- yield ContentTask.spawn(gTestBrowser, config, function* (aConfig) {
- let doc = content.document;
- let plugin = doc.getElementById("plugin");
- let pleaseSubmit = doc.getAnonymousElementByAttribute(plugin, "anonid", "pleaseSubmit");
- let submitButton = doc.getAnonymousElementByAttribute(plugin, "anonid", "submitButton");
- // Test that we send the URL when urlOptIn is true.
- doc.getAnonymousElementByAttribute(plugin, "anonid", "submitURLOptIn").checked = aConfig.urlOptIn;
- doc.getAnonymousElementByAttribute(plugin, "anonid", "submitComment").value = aConfig.comment;
- submitButton.click();
- Assert.equal(content.getComputedStyle(pleaseSubmit).display == "block",
- aConfig.shouldSubmissionUIBeVisible, "The crash UI should be visible");
- });
-
- yield crashReportStatus;
-});
-
-add_task(function* () {
- config = {
- shouldSubmissionUIBeVisible: false,
- comment: "",
- urlOptIn: true
- };
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED);
-
- let pluginCrashed = promisePluginCrashed();
-
- // Make sure that the plugin container is too small to display the crash submission UI
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_crashCommentAndURL.html?" +
- encodeURIComponent(JSON.stringify({width: 300, height: 300})));
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- // Wait for the plugin to crash
- yield pluginCrashed;
-
- // Test that the crash submission UI is not visible and do not submit a crash report.
- yield ContentTask.spawn(gTestBrowser, config, function* (aConfig) {
- let doc = content.document;
- let plugin = doc.getElementById("plugin");
- let pleaseSubmit = doc.getAnonymousElementByAttribute(plugin, "anonid", "pleaseSubmit");
- Assert.equal(!!pleaseSubmit && content.getComputedStyle(pleaseSubmit).display == "block",
- aConfig.shouldSubmissionUIBeVisible, "Plugin crash UI should not be visible");
- });
-});
-
-function promisePluginCrashed() {
- return new ContentTask.spawn(gTestBrowser, {}, function* () {
- yield new Promise((resolve) => {
- addEventListener("PluginCrashReporterDisplayed", function onPluginCrashed() {
- removeEventListener("PluginCrashReporterDisplayed", onPluginCrashed);
- resolve();
- });
- });
- })
-}
-
-function onSubmitStatus(aSubject, aData) {
- // Wait for success or failed, doesn't matter which.
- if (aData != "success" && aData != "failed")
- return false;
-
- let propBag = aSubject.QueryInterface(Ci.nsIPropertyBag);
- if (aData == "success") {
- let remoteID = getPropertyBagValue(propBag, "serverCrashID");
- ok(!!remoteID, "serverCrashID should be set");
-
- // Remove the submitted report file.
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
- file.initWithPath(Services.crashmanager._submittedDumpsDir);
- file.append(remoteID + ".txt");
- ok(file.exists(), "Submitted report file should exist");
- file.remove(false);
- }
-
- let extra = getPropertyBagValue(propBag, "extra");
- ok(extra instanceof Ci.nsIPropertyBag, "Extra data should be property bag");
-
- let val = getPropertyBagValue(extra, "PluginUserComment");
- if (config.comment)
- is(val, config.comment,
- "Comment in extra data should match comment in textbox");
- else
- ok(val === undefined,
- "Comment should be absent from extra data when textbox is empty");
-
- val = getPropertyBagValue(extra, "PluginContentURL");
- if (config.urlOptIn)
- is(val, gBrowser.currentURI.spec,
- "URL in extra data should match browser URL when opt-in checked");
- else
- ok(val === undefined,
- "URL should be absent from extra data when opt-in not checked");
-
- return true;
-}
-
-function getPropertyBagValue(bag, key) {
- try {
- var val = bag.getProperty(key);
- }
- catch (e) {
- if (e.result != Cr.NS_ERROR_FAILURE) {
- throw e;
- }
- }
- return val;
-}
diff --git a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js
deleted file mode 100644
index 42ef57314..000000000
--- a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js
+++ /dev/null
@@ -1,254 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * With e10s, plugins must run in their own process. This means we have
- * three processes at a minimum when we're running a plugin:
- *
- * 1) The main browser, or "chrome" process
- * 2) The content process hosting the plugin instance
- * 3) The plugin process
- *
- * If the plugin process crashes, we cannot be sure if the chrome process
- * will hear about it first, or the content process will hear about it
- * first. Because of how IPC works, that's really up to the operating system,
- * and we assume any guarantees about it, so we have to account for both
- * possibilities.
- *
- * This test exercises the browser's reaction to both possibilities.
- */
-
-const CRASH_URL = "http://example.com/browser/browser/base/content/test/plugins/plugin_crashCommentAndURL.html";
-const CRASHED_MESSAGE = "BrowserPlugins:NPAPIPluginProcessCrashed";
-
-/**
- * In order for our test to work, we need to be able to put a plugin
- * in a very specific state. Specifically, we need it to match the
- * :-moz-handler-crashed pseudoselector. The only way I can find to
- * do that is by actually crashing the plugin. So we wait for the
- * plugin to crash and show the "please" state (since that will
- * only show if both the message from the parent has been received
- * AND the PluginCrashed event has fired).
- *
- * Once in that state, we try to rewind the clock a little bit - we clear
- * out the crashData cache in the PluginContent with a message, and we also
- * override the pluginFallbackState of the <object> to fool PluginContent
- * into believing that the plugin is in a particular state.
- *
- * @param browser
- * The browser that has loaded the CRASH_URL that we need to
- * prepare to be in the special state.
- * @param pluginFallbackState
- * The value we should override the <object>'s pluginFallbackState
- * with.
- * @return Promise
- * The Promise resolves when the plugin has officially been put into
- * the crash reporter state, and then "rewound" to have the "status"
- * attribute of the statusDiv removed. The resolved Promise returns
- * the run ID for the crashed plugin. It rejects if we never get into
- * the crash reporter state.
- */
-function preparePlugin(browser, pluginFallbackState) {
- return ContentTask.spawn(browser, pluginFallbackState, function* (pluginFallbackState) {
- let plugin = content.document.getElementById("plugin");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- // CRASH_URL will load a plugin that crashes immediately. We
- // wait until the plugin has finished being put into the crash
- // state.
- let statusDiv;
- yield ContentTaskUtils.waitForCondition(() => {
- statusDiv = plugin.ownerDocument
- .getAnonymousElementByAttribute(plugin, "anonid",
- "submitStatus");
- return statusDiv && statusDiv.getAttribute("status") == "please";
- }, "Timed out waiting for plugin to be in crash report state");
-
- // "Rewind", by wiping out the status attribute...
- statusDiv.removeAttribute("status");
- // Somehow, I'm able to get away with overriding the getter for
- // this XPCOM object. Probably because I've got chrome privledges.
- Object.defineProperty(plugin, "pluginFallbackType", {
- get: function() {
- return pluginFallbackState;
- }
- });
- return plugin.runID;
- }).then((runID) => {
- browser.messageManager.sendAsyncMessage("BrowserPlugins:Test:ClearCrashData");
- return runID;
- });
-}
-
-add_task(function* setup() {
- // Bypass click-to-play
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED);
-
- // Clear out any minidumps we create from plugins - we really don't care
- // about them.
- let crashObserver = (subject, topic, data) => {
- if (topic != "plugin-crashed") {
- return;
- }
-
- let propBag = subject.QueryInterface(Ci.nsIPropertyBag2);
- let minidumpID = propBag.getPropertyAsAString("pluginDumpID");
-
- let minidumpDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
- minidumpDir.append("minidumps");
-
- let pluginDumpFile = minidumpDir.clone();
- pluginDumpFile.append(minidumpID + ".dmp");
-
- let extraFile = minidumpDir.clone();
- extraFile.append(minidumpID + ".extra");
-
- ok(pluginDumpFile.exists(), "Found minidump");
- ok(extraFile.exists(), "Found extra file");
-
- pluginDumpFile.remove(false);
- extraFile.remove(false);
- };
-
- Services.obs.addObserver(crashObserver, "plugin-crashed", false);
- // plugins.testmode will make BrowserPlugins:Test:ClearCrashData work.
- Services.prefs.setBoolPref("plugins.testmode", true);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("plugins.testmode");
- Services.obs.removeObserver(crashObserver, "plugin-crashed");
- });
-});
-
-/**
- * In this case, the chrome process hears about the crash first.
- */
-add_task(function* testChromeHearsPluginCrashFirst() {
- // Open a remote window so that we can run this test even if e10s is not
- // enabled by default.
- let win = yield BrowserTestUtils.openNewBrowserWindow({remote: true});
- let browser = win.gBrowser.selectedBrowser;
-
- browser.loadURI(CRASH_URL);
- yield BrowserTestUtils.browserLoaded(browser);
-
- // In this case, we want the <object> to match the -moz-handler-crashed
- // pseudoselector, but we want it to seem still active, because the
- // content process is not yet supposed to know that the plugin has
- // crashed.
- let runID = yield preparePlugin(browser,
- Ci.nsIObjectLoadingContent.PLUGIN_ACTIVE);
-
- // Send the message down to PluginContent.jsm saying that the plugin has
- // crashed, and that we have a crash report.
- let mm = browser.messageManager;
- mm.sendAsyncMessage(CRASHED_MESSAGE,
- { pluginName: "", runID, state: "please" });
-
- yield ContentTask.spawn(browser, null, function* () {
- // At this point, the content process should have heard the
- // plugin crash message from the parent, and we are OK to emit
- // the PluginCrashed event.
- let plugin = content.document.getElementById("plugin");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- let statusDiv = plugin.ownerDocument
- .getAnonymousElementByAttribute(plugin, "anonid",
- "submitStatus");
-
- if (statusDiv.getAttribute("status") == "please") {
- Assert.ok(false, "Did not expect plugin to be in crash report mode yet.");
- return;
- }
-
- // Now we need the plugin to seem crashed to PluginContent.jsm, without
- // actually crashing the plugin again. We hack around this by overriding
- // the pluginFallbackType again.
- Object.defineProperty(plugin, "pluginFallbackType", {
- get: function() {
- return Ci.nsIObjectLoadingContent.PLUGIN_CRASHED;
- },
- });
-
- let event = new content.PluginCrashedEvent("PluginCrashed", {
- pluginName: "",
- pluginDumpID: "",
- browserDumpID: "",
- submittedCrashReport: false,
- bubbles: true,
- cancelable: true,
- });
-
- plugin.dispatchEvent(event);
- Assert.equal(statusDiv.getAttribute("status"), "please",
- "Should have been showing crash report UI");
- });
- yield BrowserTestUtils.closeWindow(win);
-});
-
-/**
- * In this case, the content process hears about the crash first.
- */
-add_task(function* testContentHearsCrashFirst() {
- // Open a remote window so that we can run this test even if e10s is not
- // enabled by default.
- let win = yield BrowserTestUtils.openNewBrowserWindow({remote: true});
- let browser = win.gBrowser.selectedBrowser;
-
- browser.loadURI(CRASH_URL);
- yield BrowserTestUtils.browserLoaded(browser);
-
- // In this case, we want the <object> to match the -moz-handler-crashed
- // pseudoselector, and we want the plugin to seem crashed, since the
- // content process in this case has heard about the crash first.
- let runID = yield preparePlugin(browser,
- Ci.nsIObjectLoadingContent.PLUGIN_CRASHED);
-
- yield ContentTask.spawn(browser, null, function* () {
- // At this point, the content process has not yet heard from the
- // parent about the crash report. Let's ensure that by making sure
- // we're not showing the plugin crash report UI.
- let plugin = content.document.getElementById("plugin");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- let statusDiv = plugin.ownerDocument
- .getAnonymousElementByAttribute(plugin, "anonid",
- "submitStatus");
-
- if (statusDiv.getAttribute("status") == "please") {
- Assert.ok(false, "Did not expect plugin to be in crash report mode yet.");
- }
-
- let event = new content.PluginCrashedEvent("PluginCrashed", {
- pluginName: "",
- pluginDumpID: "",
- browserDumpID: "",
- submittedCrashReport: false,
- bubbles: true,
- cancelable: true,
- });
-
- plugin.dispatchEvent(event);
-
- Assert.notEqual(statusDiv.getAttribute("status"), "please",
- "Should not yet be showing crash report UI");
- });
-
- // Now send the message down to PluginContent.jsm that the plugin has
- // crashed...
- let mm = browser.messageManager;
- mm.sendAsyncMessage(CRASHED_MESSAGE,
- { pluginName: "", runID, state: "please"});
-
- yield ContentTask.spawn(browser, null, function* () {
- // At this point, the content process will have heard the message
- // from the parent and reacted to it. We should be showing the plugin
- // crash report UI now.
- let plugin = content.document.getElementById("plugin");
- plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- let statusDiv = plugin.ownerDocument
- .getAnonymousElementByAttribute(plugin, "anonid",
- "submitStatus");
-
- Assert.equal(statusDiv.getAttribute("status"), "please",
- "Should have been showing crash report UI");
- });
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/base/content/test/plugins/browser_plugin_reloading.js b/browser/base/content/test/plugins/browser_plugin_reloading.js
deleted file mode 100644
index 7327d4cf9..000000000
--- a/browser/base/content/test/plugins/browser_plugin_reloading.js
+++ /dev/null
@@ -1,85 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-var gTestBrowser = null;
-
-function updateAllTestPlugins(aState) {
- setTestPluginEnabledState(aState, "Test Plug-in");
- setTestPluginEnabledState(aState, "Second Test Plug-in");
-}
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gTestBrowser = null;
- gBrowser.removeCurrentTab();
- window.focus();
- }));
-});
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- // Prime the blocklist service, the remote service doesn't launch on startup.
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
-
-// Tests that a click-to-play plugin retains its activated state upon reloading
-add_task(function* () {
- clearAllPluginPermissions();
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 1, Should have a click-to-play notification");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 2, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
-
- // run the plugin
- yield promisePlayObject("test");
-
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.displayedType, Ci.nsIObjectLoadingContent.TYPE_PLUGIN, "Test 3, plugin should have started");
- ok(pluginInfo.activated, "Test 4, plugin node should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let npobj1 = Components.utils.waiveXrays(plugin).getObjectValue();
- plugin.src = plugin.src;
- let pluginsDiffer = false;
- try {
- Components.utils.waiveXrays(plugin).checkObjectValue(npobj1);
- } catch (e) {
- pluginsDiffer = true;
- }
-
- Assert.ok(pluginsDiffer, "Test 5, plugins differ.");
- });
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 6, Plugin should have retained activated state.");
- is(pluginInfo.displayedType, Ci.nsIObjectLoadingContent.TYPE_PLUGIN, "Test 7, plugin should have started");
-});
diff --git a/browser/base/content/test/plugins/browser_pluginnotification.js b/browser/base/content/test/plugins/browser_pluginnotification.js
deleted file mode 100644
index bf32f37a4..000000000
--- a/browser/base/content/test/plugins/browser_pluginnotification.js
+++ /dev/null
@@ -1,626 +0,0 @@
-var gTestRoot = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-var gTestBrowser = null;
-
-function updateAllTestPlugins(aState) {
- setTestPluginEnabledState(aState, "Test Plug-in");
- setTestPluginEnabledState(aState, "Second Test Plug-in");
-}
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gTestBrowser = null;
- gBrowser.removeCurrentTab();
- window.focus();
- }));
-});
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab();
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- // Prime the blocklist service, the remote service doesn't launch on startup.
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html></html>");
- let exmsg = yield promiseInitContentBlocklistSvc(gBrowser.selectedBrowser);
- ok(!exmsg, "exception: " + exmsg);
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-});
-
-// Tests a page with an unknown plugin in it.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_unknown.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("unknown");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_UNSUPPORTED,
- "Test 1a, plugin fallback type should be PLUGIN_UNSUPPORTED");
-});
-
-// Test that the doorhanger is shown when the user clicks on the overlay
-// after having previously blocked the plugin.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Plugin should not be activated");
-
- // Simulate clicking the "Allow Now" button.
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
-
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._secondaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Plugin should be activated");
-
- // Simulate clicking the "Block" button.
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Plugin should not be activated");
-
- // Simulate clicking the overlay
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let bounds = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- ok(!notification.dismissed, "A plugin notification should be shown.");
-
- clearAllPluginPermissions();
-});
-
-// Tests that going back will reshow the notification for click-to-play plugins
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>hi</html>");
-
- // make sure the notification is gone
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!notification, "Test 11b, Should not have a click-to-play notification");
-
- gTestBrowser.webNavigation.goBack();
-
- yield promisePopupNotification("click-to-play-plugins");
-});
-
-// Tests that the "Allow Always" permission works for click-to-play plugins
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 12a, Plugin should not be activated");
-
- // Simulate clicking the "Allow Always" button.
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
-
- yield promiseForNotificationShown(notification);
-
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 12a, Plugin should be activated");
-});
-
-// Test that the "Always" permission, when set for just the Test plugin,
-// does not also allow the Second Test plugin.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_two_types.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- yield promisePopupNotification("click-to-play-plugins");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let test = content.document.getElementById("test");
- let secondtestA = content.document.getElementById("secondtestA");
- let secondtestB = content.document.getElementById("secondtestB");
- Assert.ok(test.activated && !secondtestA.activated && !secondtestB.activated,
- "Content plugins are set up");
- });
-
- clearAllPluginPermissions();
-});
-
-// Tests that the plugin's "activated" property is true for working plugins
-// with click-to-play disabled.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_ENABLED);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test2.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("test1");
- ok(pluginInfo.activated, "Test 14, Plugin should be activated");
-});
-
-// Tests that the overlay is shown instead of alternate content when
-// plugins are click to play.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_alternate_content.html");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let mainBox = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!!mainBox, "Test 15, Plugin overlay should exist");
- });
-});
-
-// Tests that mContentType is used for click-to-play plugins, and not the
-// inspected type.
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_bug749455.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 17, Should have a click-to-play notification");
-});
-
-// Tests that clicking the icon of the overlay activates the doorhanger
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 18g, Plugin should not be activated");
-
- ok(PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed,
- "Test 19a, Doorhanger should start out dismissed");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let icon = doc.getAnonymousElementByAttribute(plugin, "class", "icon");
- let bounds = icon.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed;
- yield promiseForCondition(condition);
-});
-
-// Tests that clicking the text of the overlay activates the plugin
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 18g, Plugin should not be activated");
-
- ok(PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed,
- "Test 19c, Doorhanger should start out dismissed");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let text = doc.getAnonymousElementByAttribute(plugin, "class", "msg msgClickToPlay");
- let bounds = text.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed;
- yield promiseForCondition(condition);
-});
-
-// Tests that clicking the box of the overlay activates the doorhanger
-// (just to be thorough)
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 18g, Plugin should not be activated");
-
- ok(PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed,
- "Test 19e, Doorhanger should start out dismissed");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", 50, 50, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", 50, 50, 0, 1, 0, false, 0, 0);
- });
-
- let condition = () => !PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser).dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 19e, Plugin should not be activated");
-
- clearAllPluginPermissions();
-});
-
-// Tests that a plugin in a div that goes from style="display: none" to
-// "display: block" can be clicked to activate.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_hidden_to_visible.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 20a, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- Assert.ok(!!overlay, "Test 20a, Plugin overlay should exist");
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let mainBox = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- let overlayRect = mainBox.getBoundingClientRect();
- Assert.ok(overlayRect.width == 0 && overlayRect.height == 0,
- "Test 20a, plugin should have an overlay with 0px width and height");
- });
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 20b, plugin should not be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let div = doc.getElementById("container");
- Assert.equal(div.style.display, "none",
- "Test 20b, container div should be display: none");
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let div = doc.getElementById("container");
- div.style.display = "block";
- });
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let mainBox = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
- let overlayRect = mainBox.getBoundingClientRect();
- Assert.ok(overlayRect.width == 200 && overlayRect.height == 200,
- "Test 20c, plugin should have overlay dims of 200px");
- });
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(!pluginInfo.activated, "Test 20b, plugin should not be activated");
-
- ok(notification.dismissed, "Test 20c, Doorhanger should start out dismissed");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let bounds = plugin.getBoundingClientRect();
- let left = (bounds.left + bounds.right) / 2;
- let top = (bounds.top + bounds.bottom) / 2;
- let utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- utils.sendMouseEvent("mousedown", left, top, 0, 1, 0, false, 0, 0);
- utils.sendMouseEvent("mouseup", left, top, 0, 1, 0, false, 0, 0);
- });
-
- let condition = () => !notification.dismissed && !!PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 20c, plugin should be activated");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlayRect = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- Assert.ok(overlayRect.width == 0 && overlayRect.height == 0,
- "Test 20c, plugin should have overlay dims of 0px");
- });
-
- clearAllPluginPermissions();
-});
-
-// Test having multiple different types of plugin on one page
-add_task(function* () {
- // contains three plugins, application/x-test, application/x-second-test x 2
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_two_types.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 21a, Should have a click-to-play notification");
-
- // confirm all three are blocked by ctp at this point
- let ids = ["test", "secondtestA", "secondtestB"];
- for (let id of ids) {
- yield ContentTask.spawn(gTestBrowser, { id }, function* (args) {
- let doc = content.document;
- let plugin = doc.getElementById(args.id);
- let overlayRect = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- Assert.ok(overlayRect.width == 200 && overlayRect.height == 200,
- "Test 21a, plugin " + args.id + " should have click-to-play overlay with dims");
- });
-
- let pluginInfo = yield promiseForPluginInfo(id);
- ok(!pluginInfo.activated, "Test 21a, Plugin with id=" + id + " should not be activated");
- }
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 21a, Should have a click-to-play notification");
-
- // we have to actually show the panel to get the bindings to instantiate
- yield promiseForNotificationShown(notification);
-
- is(notification.options.pluginData.size, 2, "Test 21a, Should have two types of plugin in the notification");
-
- let centerAction = null;
- for (let action of notification.options.pluginData.values()) {
- if (action.pluginName == "Test") {
- centerAction = action;
- break;
- }
- }
- ok(centerAction, "Test 21b, found center action for the Test plugin");
-
- let centerItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- is(item.value, "block", "Test 21b, all plugins should start out blocked");
- if (item.action == centerAction) {
- centerItem = item;
- break;
- }
- }
- ok(centerItem, "Test 21b, found center item for the Test plugin");
-
- // Select the allow now option in the select drop down for Test Plugin
- centerItem.value = "allownow";
-
- // "click" the button to activate the Test plugin
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- let pluginInfo = yield promiseForPluginInfo("test");
- ok(pluginInfo.activated, "Test 21b, plugin should be activated");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 21b, Should have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- ok(notification.options.pluginData.size == 2, "Test 21c, Should have one type of plugin in the notification");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- let overlayRect = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- Assert.ok(overlayRect.width == 0 && overlayRect.height == 0,
- "Test 21c, plugin should have overlay dims of 0px");
- });
-
- ids = ["secondtestA", "secondtestB"];
- for (let id of ids) {
- yield ContentTask.spawn(gTestBrowser, { id }, function* (args) {
- let doc = content.document;
- let plugin = doc.getElementById(args.id);
- let overlayRect = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- Assert.ok(overlayRect.width == 200 && overlayRect.height == 200,
- "Test 21c, plugin " + args.id + " should have click-to-play overlay with zero dims");
- });
-
-
- let pluginInfo = yield promiseForPluginInfo(id);
- ok(!pluginInfo.activated, "Test 21c, Plugin with id=" + id + " should not be activated");
- }
-
- centerAction = null;
- for (let action of notification.options.pluginData.values()) {
- if (action.pluginName == "Second Test") {
- centerAction = action;
- break;
- }
- }
- ok(centerAction, "Test 21d, found center action for the Second Test plugin");
-
- centerItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- if (item.action == centerAction) {
- is(item.value, "block", "Test 21d, test plugin 2 should start blocked");
- centerItem = item;
- break;
- }
- else {
- is(item.value, "allownow", "Test 21d, test plugin should be enabled");
- }
- }
- ok(centerItem, "Test 21d, found center item for the Second Test plugin");
-
- // Select the allow now option in the select drop down for Second Test Plguins
- centerItem.value = "allownow";
-
- // "click" the button to activate the Second Test plugins
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 21d, Should have a click-to-play notification");
-
- ids = ["test", "secondtestA", "secondtestB"];
- for (let id of ids) {
- yield ContentTask.spawn(gTestBrowser, { id }, function* (args) {
- let doc = content.document;
- let plugin = doc.getElementById(args.id);
- let overlayRect = doc.getAnonymousElementByAttribute(plugin, "anonid", "main").getBoundingClientRect();
- Assert.ok(overlayRect.width == 0 && overlayRect.height == 0,
- "Test 21d, plugin " + args.id + " should have click-to-play overlay with zero dims");
- });
-
- let pluginInfo = yield promiseForPluginInfo(id);
- ok(pluginInfo.activated, "Test 21d, Plugin with id=" + id + " should not be activated");
- }
-});
-
-// Tests that a click-to-play plugin resets its activated state when changing types
-add_task(function* () {
- clearAllPluginPermissions();
-
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 22, Should have a click-to-play notification");
-
- // Plugin should start as CTP
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 23, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- plugin.type = null;
- // We currently don't properly change state just on type change,
- // so rebind the plugin to tree. bug 767631
- plugin.parentNode.appendChild(plugin);
- });
-
- pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.displayedType, Ci.nsIObjectLoadingContent.TYPE_NULL, "Test 23, plugin should be TYPE_NULL");
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let doc = content.document;
- let plugin = doc.getElementById("test");
- plugin.type = "application/x-test";
- plugin.parentNode.appendChild(plugin);
- });
-
- pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.displayedType, Ci.nsIObjectLoadingContent.TYPE_NULL, "Test 23, plugin should be TYPE_NULL");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY,
- "Test 23, plugin fallback type should be PLUGIN_CLICK_TO_PLAY");
- ok(!pluginInfo.activated, "Test 23, plugin node should not be activated");
-});
-
-// Plugin sync removal test. Note this test produces a notification drop down since
-// the plugin we add has zero dims.
-add_task(function* () {
- updateAllTestPlugins(Ci.nsIPluginTag.STATE_CLICKTOPLAY);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_syncRemoved.html");
-
- // Maybe there some better trick here, we need to wait for the page load, then
- // wait for the js to execute in the page.
- yield waitForMs(500);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
- ok(notification, "Test 25: There should be a plugin notification even if the plugin was immediately removed");
- ok(notification.dismissed, "Test 25: The notification should be dismissed by default");
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html,<html>hi</html>");
-});
-
-// Tests a page with a blocked plugin in it and make sure the infoURL property
-// the blocklist file gets used.
-add_task(function* () {
- clearAllPluginPermissions();
-
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockPluginInfoURL.xml", gTestBrowser);
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_test.html");
-
- // Work around for delayed PluginBindingAttached
- yield promiseUpdatePluginBindings(gTestBrowser);
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins");
-
- // Since the plugin notification is dismissed by default, reshow it.
- yield promiseForNotificationShown(notification);
-
- let pluginInfo = yield promiseForPluginInfo("test");
- is(pluginInfo.pluginFallbackType, Ci.nsIObjectLoadingContent.PLUGIN_BLOCKLISTED,
- "Test 26, plugin fallback type should be PLUGIN_BLOCKLISTED");
- ok(!pluginInfo.activated, "Plugin should be activated.");
-
- const testUrl = "http://test.url.com/";
-
- let firstPanelChild = PopupNotifications.panel.firstChild;
- let infoLink = document.getAnonymousElementByAttribute(firstPanelChild, "anonid",
- "click-to-play-plugins-notification-link");
- is(infoLink.href, testUrl,
- "Test 26, the notification URL needs to match the infoURL from the blocklist file.");
-});
diff --git a/browser/base/content/test/plugins/browser_plugins_added_dynamically.js b/browser/base/content/test/plugins/browser_plugins_added_dynamically.js
deleted file mode 100644
index 22077a54d..000000000
--- a/browser/base/content/test/plugins/browser_plugins_added_dynamically.js
+++ /dev/null
@@ -1,137 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir.replace("chrome://mochitests/content/", "http://mochi.test:8888/");
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-var gTestBrowser = null;
-
-add_task(function* () {
- registerCleanupFunction(Task.async(function*() {
- clearAllPluginPermissions();
- Services.prefs.clearUserPref("plugins.click_to_play");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_ENABLED, "Second Test Plug-in");
- yield asyncSetAndUpdateBlocklist(gTestRoot + "blockNoPlugins.xml", gTestBrowser);
- resetBlocklist();
- gBrowser.removeCurrentTab();
- window.focus();
- gTestBrowser = null;
- }));
-});
-
-// "Activate" of a given type -> plugins of that type dynamically added should
-// automatically play.
-add_task(function* () {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
-
- Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
- Services.prefs.setBoolPref("plugins.click_to_play", true);
-
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Test Plug-in");
- setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY, "Second Test Plug-in");
-});
-
-add_task(function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_add_dynamically.html");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!notification, "Test 1a, Should not have a click-to-play notification");
-
- // Add a plugin of type test
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin("pluginone", "application/x-test"));
- });
-
- yield promisePopupNotification("click-to-play-plugins");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 1a, Should not have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- let centerAction = null;
- for (let action of notification.options.pluginData.values()) {
- if (action.pluginName == "Test") {
- centerAction = action;
- break;
- }
- }
- ok(centerAction, "Test 2, found center action for the Test plugin");
-
- let centerItem = null;
- for (let item of PopupNotifications.panel.firstChild.childNodes) {
- is(item.value, "block", "Test 3, all plugins should start out blocked");
- if (item.action == centerAction) {
- centerItem = item;
- break;
- }
- }
- ok(centerItem, "Test 4, found center item for the Test plugin");
-
- // Select the allow now option in the select drop down for Test Plugin
- centerItem.value = "allownow";
-
- // "click" the button to activate the Test plugin
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- let pluginInfo = yield promiseForPluginInfo("pluginone");
- ok(pluginInfo.activated, "Test 5, plugin should be activated");
-
- // Add another plugin of type test
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin("plugintwo", "application/x-test"));
- });
-
- pluginInfo = yield promiseForPluginInfo("plugintwo");
- ok(pluginInfo.activated, "Test 6, plugins should be activated");
-});
-
-// "Activate" of a given type -> plugins of other types dynamically added
-// should not automatically play.
-add_task(function* () {
- clearAllPluginPermissions();
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_add_dynamically.html");
-
- let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(!notification, "Test 7, Should not have a click-to-play notification");
-
- // Add a plugin of type test
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin("pluginone", "application/x-test"));
- });
-
- yield promisePopupNotification("click-to-play-plugins");
-
- notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(notification, "Test 8, Should not have a click-to-play notification");
-
- yield promiseForNotificationShown(notification);
-
- is(notification.options.pluginData.size, 1, "Should be one plugin action");
-
- let pluginInfo = yield promiseForPluginInfo("pluginone");
- ok(!pluginInfo.activated, "Test 8, test plugin should be activated");
-
- let condition = () => !notification.dismissed &&
- PopupNotifications.panel.firstChild;
- yield promiseForCondition(condition);
-
- // "click" the button to activate the Test plugin
- PopupNotifications.panel.firstChild._primaryButton.click();
-
- pluginInfo = yield promiseForPluginInfo("pluginone");
- ok(pluginInfo.activated, "Test 9, test plugin should be activated");
-
- yield ContentTask.spawn(gTestBrowser, {}, function* () {
- new XPCNativeWrapper(XPCNativeWrapper.unwrap(content).addPlugin("plugintwo", "application/x-second-test"));
- });
-
- yield promisePopupNotification("click-to-play-plugins");
-
- pluginInfo = yield promiseForPluginInfo("pluginone");
- ok(pluginInfo.activated, "Test 10, plugins should be activated");
- pluginInfo = yield promiseForPluginInfo("plugintwo");
- ok(!pluginInfo.activated, "Test 11, plugins should be activated");
-});
diff --git a/browser/base/content/test/plugins/browser_private_clicktoplay.js b/browser/base/content/test/plugins/browser_private_clicktoplay.js
deleted file mode 100644
index 785b1bb31..000000000
--- a/browser/base/content/test/plugins/browser_private_clicktoplay.js
+++ /dev/null
@@ -1,216 +0,0 @@
-var rootDir = getRootDirectory(gTestPath);
-const gTestRoot = rootDir;
-const gHttpTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
-
-var gTestBrowser = null;
-var gNextTest = null;
-var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var gPrivateWindow = null;
-var gPrivateBrowser = null;
-
-function finishTest() {
- clearAllPluginPermissions();
- gBrowser.removeCurrentTab();
- if (gPrivateWindow) {
- gPrivateWindow.close();
- }
- window.focus();
-}
-
-let createPrivateWindow = Task.async(function* createPrivateWindow(url) {
- gPrivateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- ok(!!gPrivateWindow, "should have created a private window.");
- gPrivateBrowser = gPrivateWindow.getBrowser().selectedBrowser;
-
- BrowserTestUtils.loadURI(gPrivateBrowser, url);
- yield BrowserTestUtils.browserLoaded(gPrivateBrowser);
-});
-
-add_task(function* test() {
- registerCleanupFunction(function() {
- clearAllPluginPermissions();
- getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED;
- getTestPlugin("Second Test Plug-in").enabledState = Ci.nsIPluginTag.STATE_ENABLED;
- });
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- gTestBrowser = gBrowser.selectedBrowser;
- let promise = BrowserTestUtils.browserLoaded(gTestBrowser);
-
- Services.prefs.setBoolPref("plugins.click_to_play", true);
- getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_CLICKTOPLAY;
- getTestPlugin("Second Test Plug-in").enabledState = Ci.nsIPluginTag.STATE_CLICKTOPLAY;
- yield promise;
-});
-
-add_task(function* test1a() {
- yield createPrivateWindow(gHttpTestRoot + "plugin_test.html");
-});
-
-add_task(function* test1b() {
- let popupNotification = gPrivateWindow.PopupNotifications.getNotification("click-to-play-plugins", gPrivateBrowser);
- ok(popupNotification, "Test 1b, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gPrivateBrowser, null, function() {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!objLoadingContent.activated, "Test 1b, Plugin should not be activated");
- });
-
- // Check the button status
- let promiseShown = BrowserTestUtils.waitForEvent(gPrivateWindow.PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
-
- yield promiseShown;
- let button1 = gPrivateWindow.PopupNotifications.panel.firstChild._primaryButton;
- let button2 = gPrivateWindow.PopupNotifications.panel.firstChild._secondaryButton;
- is(button1.getAttribute("action"), "_singleActivateNow", "Test 1b, Blocked plugin in private window should have a activate now button");
- ok(button2.hidden, "Test 1b, Blocked plugin in a private window should not have a secondary button")
-
- gPrivateWindow.close();
- BrowserTestUtils.loadURI(gTestBrowser, gHttpTestRoot + "plugin_test.html");
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* test2a() {
- // enable test plugin on this site
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "Test 2a, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!objLoadingContent.activated, "Test 2a, Plugin should not be activated");
- });
-
- // Simulate clicking the "Allow Now" button.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
- yield promiseShown;
-
- PopupNotifications.panel.firstChild._secondaryButton.click();
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- let condition = () => objLoadingContent.activated;
- yield ContentTaskUtils.waitForCondition(condition, "Test 2a, Waited too long for plugin to activate");
- });
-});
-
-add_task(function* test2c() {
- let topicObserved = TestUtils.topicObserved("PopupNotifications-updateNotShowing");
- yield createPrivateWindow(gHttpTestRoot + "plugin_test.html");
- yield topicObserved;
-
- let popupNotification = gPrivateWindow.PopupNotifications.getNotification("click-to-play-plugins", gPrivateBrowser);
- ok(popupNotification, "Test 2c, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gPrivateBrowser, null, function() {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(objLoadingContent.activated, "Test 2c, Plugin should be activated");
- });
-
- // Check the button status
- let promiseShown = BrowserTestUtils.waitForEvent(gPrivateWindow.PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
- yield promiseShown;
- let buttonContainer = gPrivateWindow.PopupNotifications.panel.firstChild._buttonContainer;
- ok(buttonContainer.hidden, "Test 2c, Activated plugin in a private window should not have visible buttons");
-
- clearAllPluginPermissions();
- gPrivateWindow.close();
-
- BrowserTestUtils.loadURI(gTestBrowser, gHttpTestRoot + "plugin_test.html");
- yield BrowserTestUtils.browserLoaded(gTestBrowser);
-});
-
-add_task(function* test3a() {
- // enable test plugin on this site
- let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
- ok(popupNotification, "Test 3a, Should have a click-to-play notification");
-
- yield ContentTask.spawn(gTestBrowser, null, function() {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- ok(!objLoadingContent.activated, "Test 3a, Plugin should not be activated");
- });
-
- // Simulate clicking the "Allow Always" button.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
- yield promiseShown;
- PopupNotifications.panel.firstChild._secondaryButton.click();
-
- yield ContentTask.spawn(gTestBrowser, null, function* () {
- let plugin = content.document.getElementById("test");
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- let condition = () => objLoadingContent.activated;
- yield ContentTaskUtils.waitForCondition(condition, "Test 3a, Waited too long for plugin to activate");
- });
-});
-
-add_task(function* test3c() {
- let topicObserved = TestUtils.topicObserved("PopupNotifications-updateNotShowing");
- yield createPrivateWindow(gHttpTestRoot + "plugin_test.html");
- yield topicObserved;
-
- let popupNotification = gPrivateWindow.PopupNotifications.getNotification("click-to-play-plugins", gPrivateBrowser);
- ok(popupNotification, "Test 3c, Should have a click-to-play notification");
-
- // Check the button status
- let promiseShown = BrowserTestUtils.waitForEvent(gPrivateWindow.PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
- yield promiseShown;
- let buttonContainer = gPrivateWindow.PopupNotifications.panel.firstChild._buttonContainer;
- ok(buttonContainer.hidden, "Test 3c, Activated plugin in a private window should not have visible buttons");
-
- BrowserTestUtils.loadURI(gPrivateBrowser, gHttpTestRoot + "plugin_two_types.html");
- yield BrowserTestUtils.browserLoaded(gPrivateBrowser);
-});
-
-add_task(function* test3d() {
- let popupNotification = gPrivateWindow.PopupNotifications.getNotification("click-to-play-plugins", gPrivateBrowser);
- ok(popupNotification, "Test 3d, Should have a click-to-play notification");
-
- // Check the list item status
- let promiseShown = BrowserTestUtils.waitForEvent(gPrivateWindow.PopupNotifications.panel,
- "Shown");
- popupNotification.reshow();
- yield promiseShown;
- let doc = gPrivateWindow.document;
- for (let item of gPrivateWindow.PopupNotifications.panel.firstChild.childNodes) {
- let allowalways = doc.getAnonymousElementByAttribute(item, "anonid", "allowalways");
- ok(allowalways, "Test 3d, should have list item for allow always");
- let allownow = doc.getAnonymousElementByAttribute(item, "anonid", "allownow");
- ok(allownow, "Test 3d, should have list item for allow now");
- let block = doc.getAnonymousElementByAttribute(item, "anonid", "block");
- ok(block, "Test 3d, should have list item for block");
-
- if (item.action.pluginName === "Test") {
- is(item.value, "allowalways", "Test 3d, Plugin should bet set to 'allow always'");
- ok(!allowalways.hidden, "Test 3d, Plugin set to 'always allow' should have a visible 'always allow' action.");
- ok(allownow.hidden, "Test 3d, Plugin set to 'always allow' should have an invisible 'allow now' action.");
- ok(block.hidden, "Test 3d, Plugin set to 'always allow' should have an invisible 'block' action.");
- } else if (item.action.pluginName === "Second Test") {
- is(item.value, "block", "Test 3d, Second plugin should bet set to 'block'");
- ok(allowalways.hidden, "Test 3d, Plugin set to 'block' should have a visible 'always allow' action.");
- ok(!allownow.hidden, "Test 3d, Plugin set to 'block' should have a visible 'allow now' action.");
- ok(!block.hidden, "Test 3d, Plugin set to 'block' should have a visible 'block' action.");
- } else {
- ok(false, "Test 3d, Unexpected plugin '"+item.action.pluginName+"'");
- }
- }
-
- finishTest();
-});
diff --git a/browser/base/content/test/plugins/head.js b/browser/base/content/test/plugins/head.js
deleted file mode 100644
index 4995c4dc6..000000000
--- a/browser/base/content/test/plugins/head.js
+++ /dev/null
@@ -1,396 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
- "resource://gre/modules/PromiseUtils.jsm");
-
-// The blocklist shim running in the content process does not initialize at
-// start up, so it's not active until we load content that needs to do a
-// check. This helper bypasses the delay to get the svc up and running
-// immediately. Note, call this after remote content has loaded.
-function promiseInitContentBlocklistSvc(aBrowser)
-{
- return ContentTask.spawn(aBrowser, {}, function* () {
- try {
- Cc["@mozilla.org/extensions/blocklist;1"]
- .getService(Ci.nsIBlocklistService);
- } catch (ex) {
- return ex.message;
- }
- return null;
- });
-}
-
-/**
- * Waits a specified number of miliseconds.
- *
- * Usage:
- * let wait = yield waitForMs(2000);
- * ok(wait, "2 seconds should now have elapsed");
- *
- * @param aMs the number of miliseconds to wait for
- * @returns a Promise that resolves to true after the time has elapsed
- */
-function waitForMs(aMs) {
- return new Promise((resolve) => {
- setTimeout(done, aMs);
- function done() {
- resolve(true);
- }
- });
-}
-
-function waitForEvent(subject, eventName, checkFn, useCapture, useUntrusted) {
- return new Promise((resolve, reject) => {
- subject.addEventListener(eventName, function listener(event) {
- try {
- if (checkFn && !checkFn(event)) {
- return;
- }
- subject.removeEventListener(eventName, listener, useCapture);
- resolve(event);
- } catch (ex) {
- try {
- subject.removeEventListener(eventName, listener, useCapture);
- } catch (ex2) {
- // Maybe the provided object does not support removeEventListener.
- }
- reject(ex);
- }
- }, useCapture, useUntrusted);
- });
-}
-
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url) {
- info("Wait tab event: load");
-
- function handle(loadedUrl) {
- if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
- info(`Skipping spurious load event for ${loadedUrl}`);
- return false;
- }
-
- info("Tab event received: load");
- return true;
- }
-
- let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
-
- if (url)
- BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
- return loaded;
-}
-
-function waitForCondition(condition, nextTest, errorMsg, aTries, aWait) {
- let tries = 0;
- let maxTries = aTries || 100; // 100 tries
- let maxWait = aWait || 100; // 100 msec x 100 tries = ten seconds
- let interval = setInterval(function() {
- if (tries >= maxTries) {
- ok(false, errorMsg);
- moveOn();
- }
- let conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, maxWait);
- let moveOn = function() { clearInterval(interval); nextTest(); };
-}
-
-// Waits for a conditional function defined by the caller to return true.
-function promiseForCondition(aConditionFn, aMessage, aTries, aWait) {
- return new Promise((resolve) => {
- waitForCondition(aConditionFn, resolve,
- (aMessage || "Condition didn't pass."),
- aTries, aWait);
- });
-}
-
-// Returns the chrome side nsIPluginTag for this plugin
-function getTestPlugin(aName) {
- let pluginName = aName || "Test Plug-in";
- let ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
- let tags = ph.getPluginTags();
-
- // Find the test plugin
- for (let i = 0; i < tags.length; i++) {
- if (tags[i].name == pluginName)
- return tags[i];
- }
- ok(false, "Unable to find plugin");
- return null;
-}
-
-// Set the 'enabledState' on the nsIPluginTag stored in the main or chrome
-// process.
-function setTestPluginEnabledState(newEnabledState, pluginName) {
- let name = pluginName || "Test Plug-in";
- let plugin = getTestPlugin(name);
- plugin.enabledState = newEnabledState;
-}
-
-// Get the 'enabledState' on the nsIPluginTag stored in the main or chrome
-// process.
-function getTestPluginEnabledState(pluginName) {
- let name = pluginName || "Test Plug-in";
- let plugin = getTestPlugin(name);
- return plugin.enabledState;
-}
-
-// Returns a promise for nsIObjectLoadingContent props data.
-function promiseForPluginInfo(aId, aBrowser) {
- let browser = aBrowser || gTestBrowser;
- return ContentTask.spawn(browser, aId, function* (aId) {
- let plugin = content.document.getElementById(aId);
- if (!(plugin instanceof Ci.nsIObjectLoadingContent))
- throw new Error("no plugin found");
- return {
- pluginFallbackType: plugin.pluginFallbackType,
- activated: plugin.activated,
- hasRunningPlugin: plugin.hasRunningPlugin,
- displayedType: plugin.displayedType,
- };
- });
-}
-
-// Return a promise and call the plugin's nsIObjectLoadingContent
-// playPlugin() method.
-function promisePlayObject(aId, aBrowser) {
- let browser = aBrowser || gTestBrowser;
- return ContentTask.spawn(browser, aId, function* (aId) {
- let plugin = content.document.getElementById(aId);
- let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
- objLoadingContent.playPlugin();
- });
-}
-
-function promiseCrashObject(aId, aBrowser) {
- let browser = aBrowser || gTestBrowser;
- return ContentTask.spawn(browser, aId, function* (aId) {
- let plugin = content.document.getElementById(aId);
- Components.utils.waiveXrays(plugin).crash();
- });
-}
-
-// Return a promise and call the plugin's getObjectValue() method.
-function promiseObjectValueResult(aId, aBrowser) {
- let browser = aBrowser || gTestBrowser;
- return ContentTask.spawn(browser, aId, function* (aId) {
- let plugin = content.document.getElementById(aId);
- return Components.utils.waiveXrays(plugin).getObjectValue();
- });
-}
-
-// Return a promise and reload the target plugin in the page
-function promiseReloadPlugin(aId, aBrowser) {
- let browser = aBrowser || gTestBrowser;
- return ContentTask.spawn(browser, aId, function* (aId) {
- let plugin = content.document.getElementById(aId);
- plugin.src = plugin.src;
- });
-}
-
-// after a test is done using the plugin doorhanger, we should just clear
-// any permissions that may have crept in
-function clearAllPluginPermissions() {
- let perms = Services.perms.enumerator;
- while (perms.hasMoreElements()) {
- let perm = perms.getNext();
- if (perm.type.startsWith('plugin')) {
- info("removing permission:" + perm.principal.origin + " " + perm.type + "\n");
- Services.perms.removePermission(perm);
- }
- }
-}
-
-function updateBlocklist(aCallback) {
- let blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
- .getService(Ci.nsITimerCallback);
- let observer = function() {
- Services.obs.removeObserver(observer, "blocklist-updated");
- SimpleTest.executeSoon(aCallback);
- };
- Services.obs.addObserver(observer, "blocklist-updated", false);
- blocklistNotifier.notify(null);
-}
-
-var _originalTestBlocklistURL = null;
-function setAndUpdateBlocklist(aURL, aCallback) {
- if (!_originalTestBlocklistURL) {
- _originalTestBlocklistURL = Services.prefs.getCharPref("extensions.blocklist.url");
- }
- Services.prefs.setCharPref("extensions.blocklist.url", aURL);
- updateBlocklist(aCallback);
-}
-
-// A generator that insures a new blocklist is loaded (in both
-// processes if applicable).
-function* asyncSetAndUpdateBlocklist(aURL, aBrowser) {
- info("*** loading new blocklist: " + aURL);
- let doTestRemote = aBrowser ? aBrowser.isRemoteBrowser : false;
- if (!_originalTestBlocklistURL) {
- _originalTestBlocklistURL = Services.prefs.getCharPref("extensions.blocklist.url");
- }
- Services.prefs.setCharPref("extensions.blocklist.url", aURL);
- let localPromise = TestUtils.topicObserved("blocklist-updated");
- let remotePromise;
- if (doTestRemote) {
- remotePromise = TestUtils.topicObserved("content-blocklist-updated");
- }
- let blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
- .getService(Ci.nsITimerCallback);
- blocklistNotifier.notify(null);
- info("*** waiting on local load");
- yield localPromise;
- if (doTestRemote) {
- info("*** waiting on remote load");
- yield remotePromise;
- }
- info("*** blocklist loaded.");
-}
-
-// Reset back to the blocklist we had at the start of the test run.
-function resetBlocklist() {
- Services.prefs.setCharPref("extensions.blocklist.url", _originalTestBlocklistURL);
-}
-
-// Insure there's a popup notification present. This test does not indicate
-// open state. aBrowser can be undefined.
-function promisePopupNotification(aName, aBrowser) {
- return new Promise((resolve) => {
- waitForCondition(() => PopupNotifications.getNotification(aName, aBrowser),
- () => {
- ok(!!PopupNotifications.getNotification(aName, aBrowser),
- aName + " notification appeared");
-
- resolve();
- }, "timeout waiting for popup notification " + aName);
- });
-}
-
-/**
- * Allows setting focus on a window, and waiting for that window to achieve
- * focus.
- *
- * @param aWindow
- * The window to focus and wait for.
- *
- * @return {Promise}
- * @resolves When the window is focused.
- * @rejects Never.
- */
-function promiseWaitForFocus(aWindow) {
- return new Promise((resolve) => {
- waitForFocus(resolve, aWindow);
- });
-}
-
-/**
- * Returns a Promise that resolves when a notification bar
- * for a browser is shown. Alternatively, for old-style callers,
- * can automatically call a callback before it resolves.
- *
- * @param notificationID
- * The ID of the notification to look for.
- * @param browser
- * The browser to check for the notification bar.
- * @param callback (optional)
- * A function to be called just before the Promise resolves.
- *
- * @return Promise
- */
-function waitForNotificationBar(notificationID, browser, callback) {
- return new Promise((resolve, reject) => {
- let notification;
- let notificationBox = gBrowser.getNotificationBox(browser);
- waitForCondition(
- () => (notification = notificationBox.getNotificationWithValue(notificationID)),
- () => {
- ok(notification, `Successfully got the ${notificationID} notification bar`);
- if (callback) {
- callback(notification);
- }
- resolve(notification);
- },
- `Waited too long for the ${notificationID} notification bar`
- );
- });
-}
-
-function promiseForNotificationBar(notificationID, browser) {
- return new Promise((resolve) => {
- waitForNotificationBar(notificationID, browser, resolve);
- });
-}
-
-/**
- * Reshow a notification and call a callback when it is reshown.
- * @param notification
- * The notification to reshow
- * @param callback
- * A function to be called when the notification has been reshown
- */
-function waitForNotificationShown(notification, callback) {
- if (PopupNotifications.panel.state == "open") {
- executeSoon(callback);
- return;
- }
- PopupNotifications.panel.addEventListener("popupshown", function onShown(e) {
- PopupNotifications.panel.removeEventListener("popupshown", onShown);
- callback();
- }, false);
- notification.reshow();
-}
-
-function promiseForNotificationShown(notification) {
- return new Promise((resolve) => {
- waitForNotificationShown(notification, resolve);
- });
-}
-
-/**
- * Due to layout being async, "PluginBindAttached" may trigger later. This
- * returns a Promise that resolves once we've forced a layout flush, which
- * triggers the PluginBindAttached event to fire. This trick only works if
- * there is some sort of plugin in the page.
- * @param browser
- * The browser to force plugin bindings in.
- * @return Promise
- */
-function promiseUpdatePluginBindings(browser) {
- return ContentTask.spawn(browser, {}, function* () {
- let doc = content.document;
- let elems = doc.getElementsByTagName('embed');
- if (!elems || elems.length < 1) {
- elems = doc.getElementsByTagName('object');
- }
- if (elems && elems.length > 0) {
- elems[0].clientTop;
- }
- });
-}
diff --git a/browser/base/content/test/plugins/plugin_add_dynamically.html b/browser/base/content/test/plugins/plugin_add_dynamically.html
deleted file mode 100644
index 863d36e09..000000000
--- a/browser/base/content/test/plugins/plugin_add_dynamically.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<script>
-function addPlugin(aId, aType="application/x-test") {
- var embed = document.createElement("embed");
- embed.setAttribute("id", aId);
- embed.style.width = "200px";
- embed.style.height = "200px";
- embed.setAttribute("type", aType);
- return document.body.appendChild(embed);
-}
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_alternate_content.html b/browser/base/content/test/plugins/plugin_alternate_content.html
deleted file mode 100644
index f8acc833c..000000000
--- a/browser/base/content/test/plugins/plugin_alternate_content.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!-- bug 739575 -->
-<html>
-<head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
-</head>
-<body>
-<object id="test" type="application/x-test" style="height: 200px; width:200px">
-<p><a href="about:blank">you should not see this link when plugins are click-to-play</a></p>
-</object>
-</body></html>
diff --git a/browser/base/content/test/plugins/plugin_big.html b/browser/base/content/test/plugins/plugin_big.html
deleted file mode 100644
index d11506176..000000000
--- a/browser/base/content/test/plugins/plugin_big.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 500px; height: 500px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_both.html b/browser/base/content/test/plugins/plugin_both.html
deleted file mode 100644
index 2335366dc..000000000
--- a/browser/base/content/test/plugins/plugin_both.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="unknown" style="width: 100px; height: 100px" type="application/x-unknown">
-<embed id="test" style="width: 100px; height: 100px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_both2.html b/browser/base/content/test/plugins/plugin_both2.html
deleted file mode 100644
index ba605d6e8..000000000
--- a/browser/base/content/test/plugins/plugin_both2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 100px; height: 100px" type="application/x-test">
-<embed id="unknown" style="width: 100px; height: 100px" type="application/x-unknown">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_bug744745.html b/browser/base/content/test/plugins/plugin_bug744745.html
deleted file mode 100644
index d0691c9c0..000000000
--- a/browser/base/content/test/plugins/plugin_bug744745.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"/></head>
-<body>
-<style>
-.x {
- opacity: 0 !important;
-}
-</style>
-<object id="test" class="x" type="application/x-test" width=200 height=200></object>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_bug749455.html b/browser/base/content/test/plugins/plugin_bug749455.html
deleted file mode 100644
index 831dc82f7..000000000
--- a/browser/base/content/test/plugins/plugin_bug749455.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!-- bug 749455 -->
-<html>
-<head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
-</head>
-<body>
-<embed src="plugin_bug749455.html" type="application/x-test" width="100px" height="100px"></embed>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_bug787619.html b/browser/base/content/test/plugins/plugin_bug787619.html
deleted file mode 100644
index cb91116f0..000000000
--- a/browser/base/content/test/plugins/plugin_bug787619.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"/></head>
-<body>
- <a id="wrapper">
- <embed id="plugin" style="width: 200px; height: 200px" type="application/x-test">
- </a>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_bug797677.html b/browser/base/content/test/plugins/plugin_bug797677.html
deleted file mode 100644
index 1545f3647..000000000
--- a/browser/base/content/test/plugins/plugin_bug797677.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"/></head>
-<body><embed id="plugin" type="9000"></embed></body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_bug820497.html b/browser/base/content/test/plugins/plugin_bug820497.html
deleted file mode 100644
index 4884e9dbe..000000000
--- a/browser/base/content/test/plugins/plugin_bug820497.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"/></head>
-<body>
-<object id="test" type="application/x-test" width=200 height=200></object>
-<script>
- function addSecondPlugin() {
- var object = document.createElement("object");
- object.type = "application/x-second-test";
- object.width = 200;
- object.height = 200;
- object.id = "secondtest";
- document.body.appendChild(object);
- }
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_clickToPlayAllow.html b/browser/base/content/test/plugins/plugin_clickToPlayAllow.html
deleted file mode 100644
index 3f5df1984..000000000
--- a/browser/base/content/test/plugins/plugin_clickToPlayAllow.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 200px; height: 200px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_clickToPlayDeny.html b/browser/base/content/test/plugins/plugin_clickToPlayDeny.html
deleted file mode 100644
index 3f5df1984..000000000
--- a/browser/base/content/test/plugins/plugin_clickToPlayDeny.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 200px; height: 200px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_crashCommentAndURL.html b/browser/base/content/test/plugins/plugin_crashCommentAndURL.html
deleted file mode 100644
index 711a19ed3..000000000
--- a/browser/base/content/test/plugins/plugin_crashCommentAndURL.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <script type="text/javascript">
- function crash() {
- var plugin = document.getElementById("plugin");
- var argStr = decodeURIComponent(window.location.search.substr(1));
- if (argStr) {
- var args = JSON.parse(argStr);
- for (var key in args)
- plugin.setAttribute(key, args[key]);
- }
- try {
- plugin.crash();
- }
- catch (err) {}
- }
- </script>
- </head>
- <body onload="crash();">
- <embed id="plugin" type="application/x-test"
- width="400" height="400"
- drawmode="solid" color="FF00FFFF">
- </embed>
- </body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_data_url.html b/browser/base/content/test/plugins/plugin_data_url.html
deleted file mode 100644
index 77e101144..000000000
--- a/browser/base/content/test/plugins/plugin_data_url.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<body>
- <a id="data-link-1" href='data:text/html,<embed id="test" style="width: 200px; height: 200px" type="application/x-test"/>'>
- data: with one plugin
- </a><br />
- <a id="data-link-2" href='data:text/html,<embed id="test1" style="width: 200px; height: 200px" type="application/x-test"/><embed id="test2" style="width: 200px; height: 200px" type="application/x-second-test"/>'>
- data: with two plugins
- </a><br />
- <object id="test" style="width: 200px; height: 200px" type="application/x-test"></object>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_hidden_to_visible.html b/browser/base/content/test/plugins/plugin_hidden_to_visible.html
deleted file mode 100644
index eeacc1874..000000000
--- a/browser/base/content/test/plugins/plugin_hidden_to_visible.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
- <div id="container" style="display: none">
- <object id="test" type="application/x-test" style="width: 200px; height: 200px;"></object>
- </div>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_iframe.html b/browser/base/content/test/plugins/plugin_iframe.html
deleted file mode 100644
index 239c9a771..000000000
--- a/browser/base/content/test/plugins/plugin_iframe.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<iframe id="frame" with="400" height="400" src="plugin_test.html">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_outsideScrollArea.html b/browser/base/content/test/plugins/plugin_outsideScrollArea.html
deleted file mode 100644
index c6ef50d5d..000000000
--- a/browser/base/content/test/plugins/plugin_outsideScrollArea.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-<style type="text/css">
-#container {
- position: fixed;
- top: 0;
- bottom: 0;
- width: 100%;
- height: 100%;
- background: blue;
-}
-
-#test {
- width: 400px;
- height: 400px;
- position: absolute;
-}
-</style>
-</head>
-<body>
- <div id="container"></div>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_overlayed.html b/browser/base/content/test/plugins/plugin_overlayed.html
deleted file mode 100644
index 11c127093..000000000
--- a/browser/base/content/test/plugins/plugin_overlayed.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<head>
- <meta charset="utf-8">
- <style type="text/css">
- .absthing {
- width: 400px;
- height: 400px;
- position: absolute;
- left: 20px;
- top: 20px;
- }
- #d1 {
- z-index: 1;
- }
- #d2 {
- z-index: 2;
- background-color: rgba(0,0,255,0.5);
- border: 1px solid red;
- }
- </style>
-<body>
- <div class="absthing" id="d1">
- <embed id="test" type="application/x-test">
- </div>
- <div class="absthing" id="d2">
- <p>This is overlaying
- </div>
diff --git a/browser/base/content/test/plugins/plugin_positioned.html b/browser/base/content/test/plugins/plugin_positioned.html
deleted file mode 100644
index 1bad7ee46..000000000
--- a/browser/base/content/test/plugins/plugin_positioned.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<head>
- <meta charset="utf-8">
- <style type="text/css">
- #test {
- position: absolute;
- left: -1000px;
- top: -1000px;
- }
- </style>
-<body>
- <embed id="test" type="application/x-test">
diff --git a/browser/base/content/test/plugins/plugin_small.html b/browser/base/content/test/plugins/plugin_small.html
deleted file mode 100644
index f37ee28c7..000000000
--- a/browser/base/content/test/plugins/plugin_small.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 10px; height: 10px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_small_2.html b/browser/base/content/test/plugins/plugin_small_2.html
deleted file mode 100644
index ebc5ffe84..000000000
--- a/browser/base/content/test/plugins/plugin_small_2.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 10px; height: 10px" type="application/x-second-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_syncRemoved.html b/browser/base/content/test/plugins/plugin_syncRemoved.html
deleted file mode 100644
index d97787056..000000000
--- a/browser/base/content/test/plugins/plugin_syncRemoved.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-<body>
-<script type="text/javascript">
- // create an embed, insert it in the doc and immediately remove it
- var embed = document.createElement('embed');
- embed.setAttribute("id", "test");
- embed.setAttribute("type", "application/x-test");
- embed.setAttribute("style", "width: 0px; height: 0px;");
- document.body.appendChild(embed);
- window.getComputedStyle(embed, null).top;
- document.body.remove(embed);
-</script>
diff --git a/browser/base/content/test/plugins/plugin_test.html b/browser/base/content/test/plugins/plugin_test.html
deleted file mode 100644
index d4b5b6ca7..000000000
--- a/browser/base/content/test/plugins/plugin_test.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 200px; height: 200px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_test2.html b/browser/base/content/test/plugins/plugin_test2.html
deleted file mode 100644
index 95614c930..000000000
--- a/browser/base/content/test/plugins/plugin_test2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test1" style="width: 200px; height: 200px" type="application/x-test">
-<embed id="test2" style="width: 200px; height: 200px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_test3.html b/browser/base/content/test/plugins/plugin_test3.html
deleted file mode 100644
index 215c02326..000000000
--- a/browser/base/content/test/plugins/plugin_test3.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="test" style="width: 0px; height: 0px" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_two_types.html b/browser/base/content/test/plugins/plugin_two_types.html
deleted file mode 100644
index 2359d2ec1..000000000
--- a/browser/base/content/test/plugins/plugin_two_types.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"/></head>
-<body>
-<embed id="test" style="width: 200px; height: 200px" type="application/x-test"/>
-<embed id="secondtestA" style="width: 200px; height: 200px" type="application/x-second-test"/>
-<embed id="secondtestB" style="width: 200px; height: 200px" type="application/x-second-test"/>
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_unknown.html b/browser/base/content/test/plugins/plugin_unknown.html
deleted file mode 100644
index 578f455cc..000000000
--- a/browser/base/content/test/plugins/plugin_unknown.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<embed id="unknown" style="width: 100px; height: 100px" type="application/x-unknown">
-</body>
-</html>
diff --git a/browser/base/content/test/plugins/plugin_zoom.html b/browser/base/content/test/plugins/plugin_zoom.html
deleted file mode 100644
index f9e598658..000000000
--- a/browser/base/content/test/plugins/plugin_zoom.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-</head>
-<body>
-<!-- The odd width and height are here to trigger bug 972237. -->
-<embed id="test" style="width: 99.789%; height: 99.123%" type="application/x-test">
-</body>
-</html>
diff --git a/browser/base/content/test/popupNotifications/.eslintrc.js b/browser/base/content/test/popupNotifications/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/popupNotifications/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/popupNotifications/browser.ini b/browser/base/content/test/popupNotifications/browser.ini
deleted file mode 100644
index 83bb7c517..000000000
--- a/browser/base/content/test/popupNotifications/browser.ini
+++ /dev/null
@@ -1,18 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-
-[browser_displayURI.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_popupNotification.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_popupNotification_2.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_popupNotification_3.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_popupNotification_4.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_popupNotification_checkbox.js]
-skip-if = (os == "linux" && (debug || asan))
-[browser_reshow_in_background.js]
-skip-if = (os == "linux" && (debug || asan))
diff --git a/browser/base/content/test/popupNotifications/browser_displayURI.js b/browser/base/content/test/popupNotifications/browser_displayURI.js
deleted file mode 100644
index 48222be19..000000000
--- a/browser/base/content/test/popupNotifications/browser_displayURI.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Make sure that the origin is shown for ContentPermissionPrompt
- * consumers e.g. geolocation.
-*/
-
-add_task(function* test_displayURI() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://test1.example.com/",
- }, function*(browser) {
- let popupShownPromise = new Promise((resolve, reject) => {
- onPopupEvent("popupshown", function() {
- resolve(this);
- });
- });
- yield ContentTask.spawn(browser, null, function*() {
- content.navigator.geolocation.getCurrentPosition(function (pos) {
- // Do nothing
- });
- });
- let panel = yield popupShownPromise;
- let notification = panel.children[0];
- let body = document.getAnonymousElementByAttribute(notification,
- "class",
- "popup-notification-body");
- ok(body.innerHTML.includes("example.com"), "Check that at least the eTLD+1 is present in the markup");
- });
-});
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification.js b/browser/base/content/test/popupNotifications/browser_popupNotification.js
deleted file mode 100644
index 6be3e4205..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification.js
+++ /dev/null
@@ -1,203 +0,0 @@
-/* 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/. */
-
-// These are shared between test #4 to #5
-var wrongBrowserNotificationObject = new BasicNotification("wrongBrowser");
-var wrongBrowserNotification;
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
- goNext();
-}
-
-var tests = [
- { id: "Test#1",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerMainCommand(popup);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.mainActionClicked, "mainAction was clicked");
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered");
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- { id: "Test#2",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerSecondaryCommand(popup, 0);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.secondaryActionClicked, "secondaryAction was clicked");
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered");
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- { id: "Test#3",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- this.notification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // test opening a notification for a background browser
- // Note: test 4 to 6 share a tab.
- { id: "Test#4",
- run: function* () {
- let tab = gBrowser.addTab("about:blank");
- isnot(gBrowser.selectedTab, tab, "new tab isn't selected");
- wrongBrowserNotificationObject.browser = gBrowser.getBrowserForTab(tab);
- let promiseTopic = promiseTopicObserved("PopupNotifications-backgroundShow");
- wrongBrowserNotification = showNotification(wrongBrowserNotificationObject);
- yield promiseTopic;
- is(PopupNotifications.isPanelOpen, false, "panel isn't open");
- ok(!wrongBrowserNotificationObject.mainActionClicked, "main action wasn't clicked");
- ok(!wrongBrowserNotificationObject.secondaryActionClicked, "secondary action wasn't clicked");
- ok(!wrongBrowserNotificationObject.dismissalCallbackTriggered, "dismissal callback wasn't called");
- goNext();
- }
- },
- // now select that browser and test to see that the notification appeared
- { id: "Test#5",
- run: function () {
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1];
- },
- onShown: function (popup) {
- checkPopup(popup, wrongBrowserNotificationObject);
- is(PopupNotifications.isPanelOpen, true, "isPanelOpen getter doesn't lie");
-
- // switch back to the old browser
- gBrowser.selectedTab = this.oldSelectedTab;
- },
- onHidden: function (popup) {
- // actually remove the notification to prevent it from reappearing
- ok(wrongBrowserNotificationObject.dismissalCallbackTriggered, "dismissal callback triggered due to tab switch");
- wrongBrowserNotification.remove();
- ok(wrongBrowserNotificationObject.removedCallbackTriggered, "removed callback triggered");
- wrongBrowserNotification = null;
- }
- },
- // test that the removed notification isn't shown on browser re-select
- { id: "Test#6",
- run: function* () {
- let promiseTopic = promiseTopicObserved("PopupNotifications-updateNotShowing");
- gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1];
- yield promiseTopic;
- is(PopupNotifications.isPanelOpen, false, "panel isn't open");
- gBrowser.removeTab(gBrowser.selectedTab);
- goNext();
- }
- },
- // Test that two notifications with the same ID result in a single displayed
- // notification.
- { id: "Test#7",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- // Show the same notification twice
- this.notification1 = showNotification(this.notifyObj);
- this.notification2 = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- this.notification2.remove();
- },
- onHidden: function (popup) {
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered");
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test that two notifications with different IDs are displayed
- { id: "Test#8",
- run: function () {
- this.testNotif1 = new BasicNotification(this.id);
- this.testNotif1.message += " 1";
- showNotification(this.testNotif1);
- this.testNotif2 = new BasicNotification(this.id);
- this.testNotif2.message += " 2";
- this.testNotif2.id += "-2";
- showNotification(this.testNotif2);
- },
- onShown: function (popup) {
- is(popup.childNodes.length, 2, "two notifications are shown");
- // Trigger the main command for the first notification, and the secondary
- // for the second. Need to do mainCommand first since the secondaryCommand
- // triggering is async.
- triggerMainCommand(popup);
- is(popup.childNodes.length, 1, "only one notification left");
- triggerSecondaryCommand(popup, 0);
- },
- onHidden: function (popup) {
- ok(this.testNotif1.mainActionClicked, "main action #1 was clicked");
- ok(!this.testNotif1.secondaryActionClicked, "secondary action #1 wasn't clicked");
- ok(!this.testNotif1.dismissalCallbackTriggered, "dismissal callback #1 wasn't called");
-
- ok(!this.testNotif2.mainActionClicked, "main action #2 wasn't clicked");
- ok(this.testNotif2.secondaryActionClicked, "secondary action #2 was clicked");
- ok(!this.testNotif2.dismissalCallbackTriggered, "dismissal callback #2 wasn't called");
- }
- },
- // Test notification without mainAction
- { id: "Test#9",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.mainAction = null;
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- this.notification.remove();
- }
- },
- // Test two notifications with different anchors
- { id: "Test#10",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.firstNotification = showNotification(this.notifyObj);
- this.notifyObj2 = new BasicNotification(this.id);
- this.notifyObj2.id += "-2";
- this.notifyObj2.anchorID = "addons-notification-icon";
- // Second showNotification() overrides the first
- this.secondNotification = showNotification(this.notifyObj2);
- },
- onShown: function (popup) {
- // This also checks that only one element is shown.
- checkPopup(popup, this.notifyObj2);
- is(document.getElementById("geo-notification-icon").boxObject.width, 0,
- "geo anchor shouldn't be visible");
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- // Remove the notifications
- this.firstNotification.remove();
- this.secondNotification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- ok(this.notifyObj2.removedCallbackTriggered, "removed callback triggered");
- }
- }
-];
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js
deleted file mode 100644
index d77098895..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js
+++ /dev/null
@@ -1,266 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
- goNext();
-}
-
-var tests = [
- // Test optional params
- { id: "Test#1",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.secondaryActions = undefined;
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- this.notification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test that icons appear
- { id: "Test#2",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.id = "geolocation";
- this.notifyObj.anchorID = "geo-notification-icon";
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- isnot(document.getElementById("geo-notification-icon").boxObject.width, 0,
- "geo anchor should be visible");
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- let icon = document.getElementById("geo-notification-icon");
- isnot(icon.boxObject.width, 0,
- "geo anchor should be visible after dismissal");
- this.notification.remove();
- is(icon.boxObject.width, 0,
- "geo anchor should not be visible after removal");
- }
- },
-
- // Test that persistence allows the notification to persist across reloads
- { id: "Test#3",
- run: function* () {
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.addOptions({
- persistence: 2
- });
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- this.complete = false;
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/")
- // Next load will remove the notification
- this.complete = true;
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/");
- },
- onHidden: function (popup) {
- ok(this.complete, "Should only have hidden the notification after 3 page loads");
- ok(this.notifyObj.removedCallbackTriggered, "removal callback triggered");
- gBrowser.removeTab(gBrowser.selectedTab);
- gBrowser.selectedTab = this.oldSelectedTab;
- }
- },
- // Test that a timeout allows the notification to persist across reloads
- { id: "Test#4",
- run: function* () {
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- this.notifyObj = new BasicNotification(this.id);
- // Set a timeout of 10 minutes that should never be hit
- this.notifyObj.addOptions({
- timeout: Date.now() + 600000
- });
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- this.complete = false;
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- // Next load will hide the notification
- this.notification.options.timeout = Date.now() - 1;
- this.complete = true;
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/");
- },
- onHidden: function (popup) {
- ok(this.complete, "Should only have hidden the notification after the timeout was passed");
- this.notification.remove();
- gBrowser.removeTab(gBrowser.selectedTab);
- gBrowser.selectedTab = this.oldSelectedTab;
- }
- },
- // Test that setting persistWhileVisible allows a visible notification to
- // persist across location changes
- { id: "Test#5",
- run: function* () {
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.addOptions({
- persistWhileVisible: true
- });
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- this.complete = false;
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/");
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- // Notification should persist across location changes
- this.complete = true;
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- ok(this.complete, "Should only have hidden the notification after it was dismissed");
- this.notification.remove();
- gBrowser.removeTab(gBrowser.selectedTab);
- gBrowser.selectedTab = this.oldSelectedTab;
- }
- },
-
- // Test that nested icon nodes correctly activate popups
- { id: "Test#6",
- run: function() {
- // Add a temporary box as the anchor with a button
- this.box = document.createElement("box");
- PopupNotifications.iconBox.appendChild(this.box);
-
- let button = document.createElement("button");
- button.setAttribute("label", "Please click me!");
- this.box.appendChild(button);
-
- // The notification should open up on the box
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.anchorID = this.box.id = "nested-box";
- this.notifyObj.addOptions({dismissed: true});
- this.notification = showNotification(this.notifyObj);
-
- // This test places a normal button in the notification area, which has
- // standard GTK styling and dimensions. Due to the clip-path, this button
- // gets clipped off, which makes it necessary to synthesize the mouse click
- // a little bit downward. To be safe, I adjusted the x-offset with the same
- // amount.
- EventUtils.synthesizeMouse(button, 4, 4, {});
- },
- onShown: function(popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function(popup) {
- this.notification.remove();
- this.box.parentNode.removeChild(this.box);
- }
- },
- // Test that popupnotifications without popups have anchor icons shown
- { id: "Test#7",
- run: function* () {
- let notifyObj = new BasicNotification(this.id);
- notifyObj.anchorID = "geo-notification-icon";
- notifyObj.addOptions({neverShow: true});
- let promiseTopic = promiseTopicObserved("PopupNotifications-updateNotShowing");
- showNotification(notifyObj);
- yield promiseTopic;
- isnot(document.getElementById("geo-notification-icon").boxObject.width, 0,
- "geo anchor should be visible");
- goNext();
- }
- },
- // Test notification "Not Now" menu item
- { id: "Test#8",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerSecondaryCommand(popup, 1);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- this.notification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test notification close button
- { id: "Test#9",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- EventUtils.synthesizeMouseAtCenter(notification.closebutton, {});
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- this.notification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test notification when chrome is hidden
- { id: "Test#10",
- run: function () {
- window.locationbar.visible = false;
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- is(popup.anchorNode.className, "tabbrowser-tab", "notification anchored to tab");
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- this.notification.remove();
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- window.locationbar.visible = true;
- }
- },
- // Test that dismissed popupnotifications can be opened on about:blank
- // (where the rest of the identity block is disabled)
- { id: "Test#11",
- run: function() {
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
-
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.anchorID = "geo-notification-icon";
- this.notifyObj.addOptions({dismissed: true});
- this.notification = showNotification(this.notifyObj);
-
- EventUtils.synthesizeMouse(document.getElementById("geo-notification-icon"), 0, 0, {});
- },
- onShown: function(popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function(popup) {
- this.notification.remove();
- gBrowser.removeTab(gBrowser.selectedTab);
- gBrowser.selectedTab = this.oldSelectedTab;
- }
- }
-];
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js
deleted file mode 100644
index 33ec3f714..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js
+++ /dev/null
@@ -1,305 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
- goNext();
-}
-
-var tests = [
- // Test notification is removed when dismissed if removeOnDismissal is true
- { id: "Test#1",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.addOptions({
- removeOnDismissal: true
- });
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered");
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test multiple notification icons are shown
- { id: "Test#2",
- run: function () {
- this.notifyObj1 = new BasicNotification(this.id);
- this.notifyObj1.id += "_1";
- this.notifyObj1.anchorID = "default-notification-icon";
- this.notification1 = showNotification(this.notifyObj1);
-
- this.notifyObj2 = new BasicNotification(this.id);
- this.notifyObj2.id += "_2";
- this.notifyObj2.anchorID = "geo-notification-icon";
- this.notification2 = showNotification(this.notifyObj2);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj2);
-
- // check notifyObj1 anchor icon is showing
- isnot(document.getElementById("default-notification-icon").boxObject.width, 0,
- "default anchor should be visible");
- // check notifyObj2 anchor icon is showing
- isnot(document.getElementById("geo-notification-icon").boxObject.width, 0,
- "geo anchor should be visible");
-
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- this.notification1.remove();
- ok(this.notifyObj1.removedCallbackTriggered, "removed callback triggered");
-
- this.notification2.remove();
- ok(this.notifyObj2.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test that multiple notification icons are removed when switching tabs
- { id: "Test#3",
- run: function () {
- // show the notification on old tab.
- this.notifyObjOld = new BasicNotification(this.id);
- this.notifyObjOld.anchorID = "default-notification-icon";
- this.notificationOld = showNotification(this.notifyObjOld);
-
- // switch tab
- this.oldSelectedTab = gBrowser.selectedTab;
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
-
- // show the notification on new tab.
- this.notifyObjNew = new BasicNotification(this.id);
- this.notifyObjNew.anchorID = "geo-notification-icon";
- this.notificationNew = showNotification(this.notifyObjNew);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObjNew);
-
- // check notifyObjOld anchor icon is removed
- is(document.getElementById("default-notification-icon").boxObject.width, 0,
- "default anchor shouldn't be visible");
- // check notifyObjNew anchor icon is showing
- isnot(document.getElementById("geo-notification-icon").boxObject.width, 0,
- "geo anchor should be visible");
-
- dismissNotification(popup);
- },
- onHidden: function (popup) {
- this.notificationNew.remove();
- gBrowser.removeTab(gBrowser.selectedTab);
-
- gBrowser.selectedTab = this.oldSelectedTab;
- this.notificationOld.remove();
- }
- },
- // test security delay - too early
- { id: "Test#4",
- run: function () {
- // Set the security delay to 100s
- PopupNotifications.buttonDelay = 100000;
-
- this.notifyObj = new BasicNotification(this.id);
- showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerMainCommand(popup);
-
- // Wait to see if the main command worked
- executeSoon(function delayedDismissal() {
- dismissNotification(popup);
- });
-
- },
- onHidden: function (popup) {
- ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked because it was too soon");
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered");
- }
- },
- // test security delay - after delay
- { id: "Test#5",
- run: function () {
- // Set the security delay to 10ms
- PopupNotifications.buttonDelay = 10;
-
- this.notifyObj = new BasicNotification(this.id);
- showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
-
- // Wait until after the delay to trigger the main action
- setTimeout(function delayedDismissal() {
- triggerMainCommand(popup);
- }, 500);
-
- },
- onHidden: function (popup) {
- ok(this.notifyObj.mainActionClicked, "mainAction was clicked after the delay");
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback was not triggered");
- PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL;
- }
- },
- // reload removes notification
- { id: "Test#6",
- run: function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- let notifyObj = new BasicNotification(this.id);
- notifyObj.options.eventCallback = function (eventName) {
- if (eventName == "removed") {
- ok(true, "Notification removed in background tab after reloading");
- goNext();
- }
- };
- showNotification(notifyObj);
- executeSoon(function () {
- gBrowser.selectedBrowser.reload();
- });
- }
- },
- // location change in background tab removes notification
- { id: "Test#7",
- run: function* () {
- let oldSelectedTab = gBrowser.selectedTab;
- let newTab = gBrowser.addTab("about:blank");
- gBrowser.selectedTab = newTab;
-
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- gBrowser.selectedTab = oldSelectedTab;
- let browser = gBrowser.getBrowserForTab(newTab);
-
- let notifyObj = new BasicNotification(this.id);
- notifyObj.browser = browser;
- notifyObj.options.eventCallback = function (eventName) {
- if (eventName == "removed") {
- ok(true, "Notification removed in background tab after reloading");
- executeSoon(function () {
- gBrowser.removeTab(newTab);
- goNext();
- });
- }
- };
- showNotification(notifyObj);
- executeSoon(function () {
- browser.reload();
- });
- }
- },
- // Popup notification anchor shouldn't disappear when a notification with the same ID is re-added in a background tab
- { id: "Test#8",
- run: function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- let originalTab = gBrowser.selectedTab;
- let bgTab = gBrowser.addTab("about:blank");
- gBrowser.selectedTab = bgTab;
- yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/");
- let anchor = document.createElement("box");
- anchor.id = "test26-anchor";
- anchor.className = "notification-anchor-icon";
- PopupNotifications.iconBox.appendChild(anchor);
-
- gBrowser.selectedTab = originalTab;
-
- let fgNotifyObj = new BasicNotification(this.id);
- fgNotifyObj.anchorID = anchor.id;
- fgNotifyObj.options.dismissed = true;
- let fgNotification = showNotification(fgNotifyObj);
-
- let bgNotifyObj = new BasicNotification(this.id);
- bgNotifyObj.anchorID = anchor.id;
- bgNotifyObj.browser = gBrowser.getBrowserForTab(bgTab);
- // show the notification in the background tab ...
- let bgNotification = showNotification(bgNotifyObj);
- // ... and re-show it
- bgNotification = showNotification(bgNotifyObj);
-
- ok(fgNotification.id, "notification has id");
- is(fgNotification.id, bgNotification.id, "notification ids are the same");
- is(anchor.getAttribute("showing"), "true", "anchor still showing");
-
- fgNotification.remove();
- gBrowser.removeTab(bgTab);
- goNext();
- }
- },
- // location change in an embedded frame should not remove a notification
- { id: "Test#9",
- run: function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html;charset=utf8,<iframe%20id='iframe'%20src='http://example.com/'>");
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.eventCallback = function (eventName) {
- if (eventName == "removed") {
- ok(false, "Notification removed from browser when subframe navigated");
- }
- };
- showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- let self = this;
- let progressListener = {
- onLocationChange: function onLocationChange() {
- gBrowser.removeProgressListener(progressListener);
-
- executeSoon(() => {
- let notification = PopupNotifications.getNotification(self.notifyObj.id,
- self.notifyObj.browser);
- ok(notification != null, "Notification remained when subframe navigated");
- self.notifyObj.options.eventCallback = undefined;
-
- notification.remove();
- });
- },
- };
-
- info("Adding progress listener and performing navigation");
- gBrowser.addProgressListener(progressListener);
- ContentTask.spawn(gBrowser.selectedBrowser, null, function() {
- content.document.getElementById("iframe")
- .setAttribute("src", "http://example.org/");
- });
- },
- onHidden: function () {}
- },
- // Popup Notifications should catch exceptions from callbacks
- { id: "Test#10",
- run: function () {
- this.testNotif1 = new BasicNotification(this.id);
- this.testNotif1.message += " 1";
- this.notification1 = showNotification(this.testNotif1);
- this.testNotif1.options.eventCallback = function (eventName) {
- info("notifyObj1.options.eventCallback: " + eventName);
- if (eventName == "dismissed") {
- throw new Error("Oops 1!");
- }
- };
-
- this.testNotif2 = new BasicNotification(this.id);
- this.testNotif2.message += " 2";
- this.testNotif2.id += "-2";
- this.testNotif2.options.eventCallback = function (eventName) {
- info("notifyObj2.options.eventCallback: " + eventName);
- if (eventName == "dismissed") {
- throw new Error("Oops 2!");
- }
- };
- this.notification2 = showNotification(this.testNotif2);
- },
- onShown: function (popup) {
- is(popup.childNodes.length, 2, "two notifications are shown");
- dismissNotification(popup);
- },
- onHidden: function () {
- this.notification1.remove();
- this.notification2.remove();
- }
- }
-];
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js
deleted file mode 100644
index 750ad82fd..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js
+++ /dev/null
@@ -1,294 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
- goNext();
-}
-
-var tests = [
- // Popup Notifications main actions should catch exceptions from callbacks
- { id: "Test#1",
- run: function () {
- this.testNotif = new ErrorNotification();
- showNotification(this.testNotif);
- },
- onShown: function (popup) {
- checkPopup(popup, this.testNotif);
- triggerMainCommand(popup);
- },
- onHidden: function (popup) {
- ok(this.testNotif.mainActionClicked, "main action has been triggered");
- }
- },
- // Popup Notifications secondary actions should catch exceptions from callbacks
- { id: "Test#2",
- run: function () {
- this.testNotif = new ErrorNotification();
- showNotification(this.testNotif);
- },
- onShown: function (popup) {
- checkPopup(popup, this.testNotif);
- triggerSecondaryCommand(popup, 0);
- },
- onHidden: function (popup) {
- ok(this.testNotif.secondaryActionClicked, "secondary action has been triggered");
- }
- },
- // Existing popup notification shouldn't disappear when adding a dismissed notification
- { id: "Test#3",
- run: function () {
- this.notifyObj1 = new BasicNotification(this.id);
- this.notifyObj1.id += "_1";
- this.notifyObj1.anchorID = "default-notification-icon";
- this.notification1 = showNotification(this.notifyObj1);
- },
- onShown: function (popup) {
- // Now show a dismissed notification, and check that it doesn't clobber
- // the showing one.
- this.notifyObj2 = new BasicNotification(this.id);
- this.notifyObj2.id += "_2";
- this.notifyObj2.anchorID = "geo-notification-icon";
- this.notifyObj2.options.dismissed = true;
- this.notification2 = showNotification(this.notifyObj2);
-
- checkPopup(popup, this.notifyObj1);
-
- // check that both anchor icons are showing
- is(document.getElementById("default-notification-icon").getAttribute("showing"), "true",
- "notification1 anchor should be visible");
- is(document.getElementById("geo-notification-icon").getAttribute("showing"), "true",
- "notification2 anchor should be visible");
-
- dismissNotification(popup);
- },
- onHidden: function(popup) {
- this.notification1.remove();
- this.notification2.remove();
- }
- },
- // Showing should be able to modify the popup data
- { id: "Test#4",
- run: function() {
- this.notifyObj = new BasicNotification(this.id);
- let normalCallback = this.notifyObj.options.eventCallback;
- this.notifyObj.options.eventCallback = function (eventName) {
- if (eventName == "showing") {
- this.mainAction.label = "Alternate Label";
- }
- normalCallback.call(this, eventName);
- };
- showNotification(this.notifyObj);
- },
- onShown: function(popup) {
- // checkPopup checks for the matching label. Note that this assumes that
- // this.notifyObj.mainAction is the same as notification.mainAction,
- // which could be a problem if we ever decided to deep-copy.
- checkPopup(popup, this.notifyObj);
- triggerMainCommand(popup);
- },
- onHidden: function() { }
- },
- // Moving a tab to a new window should remove non-swappable notifications.
- { id: "Test#5",
- run: function() {
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- let notifyObj = new BasicNotification(this.id);
- showNotification(notifyObj);
- let win = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
- whenDelayedStartupFinished(win, function() {
- let anchor = win.document.getElementById("default-notification-icon");
- win.PopupNotifications._reshowNotifications(anchor);
- ok(win.PopupNotifications.panel.childNodes.length == 0,
- "no notification displayed in new window");
- ok(notifyObj.swappingCallbackTriggered, "the swapping callback was triggered");
- ok(notifyObj.removedCallbackTriggered, "the removed callback was triggered");
- win.close();
- goNext();
- });
- }
- },
- // Moving a tab to a new window should preserve swappable notifications.
- { id: "Test#6",
- run: function* () {
- let originalBrowser = gBrowser.selectedBrowser;
- let originalWindow = window;
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- let notifyObj = new BasicNotification(this.id);
- let originalCallback = notifyObj.options.eventCallback;
- notifyObj.options.eventCallback = function (eventName) {
- originalCallback(eventName);
- return eventName == "swapping";
- };
-
- let notification = showNotification(notifyObj);
- let win = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
- yield whenDelayedStartupFinished(win);
-
- yield new Promise(resolve => {
- let originalCallback = notification.options.eventCallback;
- notification.options.eventCallback = function (eventName) {
- originalCallback(eventName);
- if (eventName == "shown") {
- resolve();
- }
- };
- info("Showing the notification again");
- notification.reshow();
- });
-
- checkPopup(win.PopupNotifications.panel, notifyObj);
- ok(notifyObj.swappingCallbackTriggered, "the swapping callback was triggered");
- yield BrowserTestUtils.closeWindow(win);
-
- // These are the same checks that PopupNotifications.jsm makes before it
- // allows a notification to open. Do not go to the next test until we are
- // sure that its attempt to display a notification will not fail.
- yield BrowserTestUtils.waitForCondition(() => originalBrowser.docShellIsActive,
- "The browser should be active");
- let fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
- yield BrowserTestUtils.waitForCondition(() => fm.activeWindow == originalWindow,
- "The window should be active")
-
- goNext();
- }
- },
- // the hideNotNow option
- { id: "Test#7",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.hideNotNow = true;
- this.notifyObj.mainAction.dismiss = true;
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- // checkPopup verifies that the Not Now item is hidden, and that no separator is added.
- checkPopup(popup, this.notifyObj);
- triggerMainCommand(popup);
- },
- onHidden: function (popup) {
- this.notification.remove();
- }
- },
- // the main action callback can keep the notification.
- { id: "Test#8",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.mainAction.dismiss = true;
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerMainCommand(popup);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered");
- ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered");
- this.notification.remove();
- }
- },
- // a secondary action callback can keep the notification.
- { id: "Test#9",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.secondaryActions[0].dismiss = true;
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- triggerSecondaryCommand(popup, 0);
- },
- onHidden: function (popup) {
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered");
- ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered");
- this.notification.remove();
- }
- },
- // returning true in the showing callback should dismiss the notification.
- { id: "Test#10",
- run: function() {
- let notifyObj = new BasicNotification(this.id);
- let originalCallback = notifyObj.options.eventCallback;
- notifyObj.options.eventCallback = function (eventName) {
- originalCallback(eventName);
- return eventName == "showing";
- };
-
- let notification = showNotification(notifyObj);
- ok(notifyObj.showingCallbackTriggered, "the showing callback was triggered");
- ok(!notifyObj.shownCallbackTriggered, "the shown callback wasn't triggered");
- notification.remove();
- goNext();
- }
- },
- // panel updates should fire the showing and shown callbacks again.
- { id: "Test#11",
- run: function() {
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
-
- this.notifyObj.showingCallbackTriggered = false;
- this.notifyObj.shownCallbackTriggered = false;
-
- // Force an update of the panel. This is typically called
- // automatically when receiving 'activate' or 'TabSelect' events,
- // but from a setTimeout, which is inconvenient for the test.
- PopupNotifications._update();
-
- checkPopup(popup, this.notifyObj);
-
- this.notification.remove();
- },
- onHidden: function() { }
- },
- // A first dismissed notification shouldn't stop _update from showing a second notification
- { id: "Test#12",
- run: function () {
- this.notifyObj1 = new BasicNotification(this.id);
- this.notifyObj1.id += "_1";
- this.notifyObj1.anchorID = "default-notification-icon";
- this.notifyObj1.options.dismissed = true;
- this.notification1 = showNotification(this.notifyObj1);
-
- this.notifyObj2 = new BasicNotification(this.id);
- this.notifyObj2.id += "_2";
- this.notifyObj2.anchorID = "geo-notification-icon";
- this.notifyObj2.options.dismissed = true;
- this.notification2 = showNotification(this.notifyObj2);
-
- this.notification2.dismissed = false;
- PopupNotifications._update();
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj2);
- this.notification1.remove();
- this.notification2.remove();
- },
- onHidden: function(popup) { }
- },
- // The anchor icon should be shown for notifications in background windows.
- { id: "Test#13",
- run: function() {
- let notifyObj = new BasicNotification(this.id);
- notifyObj.options.dismissed = true;
- let win = gBrowser.replaceTabWithWindow(gBrowser.addTab("about:blank"));
- whenDelayedStartupFinished(win, function() {
- showNotification(notifyObj);
- let anchor = document.getElementById("default-notification-icon");
- is(anchor.getAttribute("showing"), "true", "the anchor is shown");
- win.close();
- goNext();
- });
- }
- }
-];
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js
deleted file mode 100644
index bcc51fcd7..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js
+++ /dev/null
@@ -1,211 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
- goNext();
-}
-
-function checkCheckbox(checkbox, label, checked=false, hidden=false) {
- is(checkbox.label, label, "Checkbox should have the correct label");
- is(checkbox.hidden, hidden, "Checkbox should be shown");
- is(checkbox.checked, checked, "Checkbox should be checked by default");
-}
-
-function checkMainAction(notification, disabled=false) {
- let mainAction = notification.button;
- let warningLabel = document.getAnonymousElementByAttribute(notification, "class", "popup-notification-warning");
- is(warningLabel.hidden, !disabled, "Warning label should be shown");
- is(mainAction.disabled, disabled, "MainAction should be disabled");
-}
-
-function promiseElementVisible(element) {
- // HTMLElement.offsetParent is null when the element is not visisble
- // (or if the element has |position: fixed|). See:
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
- return BrowserTestUtils.waitForCondition(() => element.offsetParent !== null,
- "Waiting for element to be visible");
-}
-
-var gNotification;
-
-var tests = [
- // Test that passing the checkbox field shows the checkbox.
- { id: "show_checkbox",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.checkbox = {
- label: "This is a checkbox",
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- checkCheckbox(notification.checkbox, "This is a checkbox");
- triggerMainCommand(popup);
- },
- onHidden: function () { }
- },
-
- // Test checkbox being checked by default
- { id: "checkbox_checked",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.checkbox = {
- label: "Check this",
- checked: true,
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- checkCheckbox(notification.checkbox, "Check this", true);
- triggerMainCommand(popup);
- },
- onHidden: function () { }
- },
-
- // Test checkbox passing the checkbox state on mainAction
- { id: "checkbox_passCheckboxChecked_mainAction",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.mainAction.callback = ({checkboxChecked}) => this.mainActionChecked = checkboxChecked;
- this.notifyObj.options.checkbox = {
- label: "This is a checkbox",
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- let checkbox = notification.checkbox;
- checkCheckbox(checkbox, "This is a checkbox");
- yield promiseElementVisible(checkbox);
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- checkCheckbox(checkbox, "This is a checkbox", true);
- triggerMainCommand(popup);
- },
- onHidden: function () {
- is(this.mainActionChecked, true, "mainAction callback is passed the correct checkbox value");
- }
- },
-
- // Test checkbox passing the checkbox state on secondaryAction
- { id: "checkbox_passCheckboxChecked_secondaryAction",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.secondaryActions = [{
- label: "Test Secondary",
- accessKey: "T",
- callback: ({checkboxChecked}) => this.secondaryActionChecked = checkboxChecked,
- }];
- this.notifyObj.options.checkbox = {
- label: "This is a checkbox",
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- let checkbox = notification.checkbox;
- checkCheckbox(checkbox, "This is a checkbox");
- yield promiseElementVisible(checkbox);
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- checkCheckbox(checkbox, "This is a checkbox", true);
- triggerSecondaryCommand(popup, 0);
- },
- onHidden: function () {
- is(this.secondaryActionChecked, true, "secondaryAction callback is passed the correct checkbox value");
- }
- },
-
- // Test checkbox preserving its state through re-opening the doorhanger
- { id: "checkbox_reopen",
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.checkbox = {
- label: "This is a checkbox",
- checkedState: {
- disableMainAction: true,
- warningLabel: "Testing disable",
- },
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- let checkbox = notification.checkbox;
- checkCheckbox(checkbox, "This is a checkbox");
- yield promiseElementVisible(checkbox);
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- dismissNotification(popup);
- },
- onHidden: function* (popup) {
- let icon = document.getElementById("default-notification-icon");
- let shown = waitForNotificationPanel();
- EventUtils.synthesizeMouseAtCenter(icon, {});
- yield shown;
- let notification = popup.childNodes[0];
- let checkbox = notification.checkbox;
- checkCheckbox(checkbox, "This is a checkbox", true);
- checkMainAction(notification, true);
- gNotification.remove();
- }
- },
-];
-
-// Test checkbox disabling the main action in different combinations
-["checkedState", "uncheckedState"].forEach(function (state) {
- [true, false].forEach(function (checked) {
- tests.push(
- { id: `checkbox_disableMainAction_${state}_${checked ? 'checked' : 'unchecked'}`,
- run: function () {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.checkbox = {
- label: "This is a checkbox",
- checked: checked,
- [state]: {
- disableMainAction: true,
- warningLabel: "Testing disable",
- },
- };
- gNotification = showNotification(this.notifyObj);
- },
- onShown: function* (popup) {
- checkPopup(popup, this.notifyObj);
- let notification = popup.childNodes[0];
- let checkbox = notification.checkbox;
- let disabled = (state === "checkedState" && checked) ||
- (state === "uncheckedState" && !checked);
-
- checkCheckbox(checkbox, "This is a checkbox", checked);
- checkMainAction(notification, disabled);
- yield promiseElementVisible(checkbox);
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- checkCheckbox(checkbox, "This is a checkbox", !checked);
- checkMainAction(notification, !disabled);
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- checkCheckbox(checkbox, "This is a checkbox", checked);
- checkMainAction(notification, disabled);
-
- // Unblock the main command if it's currently disabled.
- if (disabled) {
- EventUtils.synthesizeMouseAtCenter(checkbox, {});
- }
- triggerMainCommand(popup);
- },
- onHidden: function () { }
- }
- );
- });
-});
-
diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js b/browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js
deleted file mode 100644
index 0f5b57ced..000000000
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- ok(PopupNotifications, "PopupNotifications object exists");
- ok(PopupNotifications.panel, "PopupNotifications panel exists");
-
- setup();
-}
-
-var tests = [
- // Test that for persistent notifications,
- // the secondary action is triggered by pressing the escape key.
- { id: "Test#1",
- run() {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.options.persistent = true;
- showNotification(this.notifyObj);
- },
- onShown(popup) {
- checkPopup(popup, this.notifyObj);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- },
- onHidden(popup) {
- ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked");
- ok(this.notifyObj.secondaryActionClicked, "secondaryAction was clicked");
- ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered");
- ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered");
- }
- },
- // Test that for non-persistent notifications, the escape key dismisses the notification.
- { id: "Test#2",
- *run() {
- yield waitForWindowReadyForPopupNotifications(window);
- this.notifyObj = new BasicNotification(this.id);
- this.notification = showNotification(this.notifyObj);
- },
- onShown(popup) {
- checkPopup(popup, this.notifyObj);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- },
- onHidden(popup) {
- ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked");
- ok(!this.notifyObj.secondaryActionClicked, "secondaryAction was not clicked");
- ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
- ok(!this.notifyObj.removedCallbackTriggered, "removed callback was not triggered");
- this.notification.remove();
- }
- },
- // Test that the space key on an anchor element focuses an active notification
- { id: "Test#3",
- *run() {
- this.notifyObj = new BasicNotification(this.id);
- this.notifyObj.anchorID = "geo-notification-icon";
- this.notifyObj.addOptions({
- persistent: true
- });
- this.notification = showNotification(this.notifyObj);
- },
- *onShown(popup) {
- checkPopup(popup, this.notifyObj);
- let anchor = document.getElementById(this.notifyObj.anchorID);
- anchor.focus();
- is(document.activeElement, anchor);
- EventUtils.synthesizeKey(" ", {});
- is(document.activeElement, popup.childNodes[0].button);
- this.notification.remove();
- },
- onHidden(popup) { }
- },
-];
diff --git a/browser/base/content/test/popupNotifications/browser_reshow_in_background.js b/browser/base/content/test/popupNotifications/browser_reshow_in_background.js
deleted file mode 100644
index 6f415f62e..000000000
--- a/browser/base/content/test/popupNotifications/browser_reshow_in_background.js
+++ /dev/null
@@ -1,52 +0,0 @@
-"use strict";
-
-/**
- * Tests that when PopupNotifications for background tabs are reshown, they
- * don't show up in the foreground tab, but only in the background tab that
- * they belong to.
- */
-add_task(function* test_background_notifications_dont_reshow_in_foreground() {
- // Our initial tab will be A. Let's open two more tabs B and C, but keep
- // A selected. Then, we'll trigger a PopupNotification in C, and then make
- // it reshow.
- let tabB = gBrowser.addTab("about:blank");
- let tabC = gBrowser.addTab("about:blank");
-
- let seenEvents = [];
-
- let options = {
- dismissed: false,
- eventCallback(popupEvent) {
- seenEvents.push(popupEvent);
- },
- };
-
- let notification =
- PopupNotifications.show(tabC.linkedBrowser, "test-notification",
- "", "plugins-notification-icon",
- null, null, options);
- Assert.deepEqual(seenEvents, [], "Should have seen no events yet.");
-
- yield BrowserTestUtils.switchTab(gBrowser, tabB);
- Assert.deepEqual(seenEvents, [], "Should have seen no events yet.");
-
- notification.reshow();
- Assert.deepEqual(seenEvents, [], "Should have seen no events yet.");
-
- let panelShown =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- yield BrowserTestUtils.switchTab(gBrowser, tabC);
- yield panelShown;
-
- Assert.equal(seenEvents.length, 2, "Should have seen two events.");
- Assert.equal(seenEvents[0], "showing", "Should have said popup was showing.");
- Assert.equal(seenEvents[1], "shown", "Should have said popup was shown.");
-
- let panelHidden =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- PopupNotifications.remove(notification);
- yield panelHidden;
-
- yield BrowserTestUtils.removeTab(tabB);
- yield BrowserTestUtils.removeTab(tabC);
-});
diff --git a/browser/base/content/test/popupNotifications/head.js b/browser/base/content/test/popupNotifications/head.js
deleted file mode 100644
index 4a803d6af..000000000
--- a/browser/base/content/test/popupNotifications/head.js
+++ /dev/null
@@ -1,303 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- return new Promise(resolve => {
- info("Waiting for delayed startup to finish");
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- if (aCallback) {
- executeSoon(aCallback);
- }
- resolve();
- }
- }, "browser-delayed-startup-finished", false);
- });
-}
-
-/**
- * Allows waiting for an observer notification once.
- *
- * @param topic
- * Notification topic to observe.
- *
- * @return {Promise}
- * @resolves The array [subject, data] from the observed notification.
- * @rejects Never.
- */
-function promiseTopicObserved(topic)
-{
- let deferred = Promise.defer();
- info("Waiting for observer topic " + topic);
- Services.obs.addObserver(function PTO_observe(subject, topic, data) {
- Services.obs.removeObserver(PTO_observe, topic);
- deferred.resolve([subject, data]);
- }, topic, false);
- return deferred.promise;
-}
-
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url)
-{
- let browser = tab.linkedBrowser;
-
- if (url) {
- browser.loadURI(url);
- }
-
- return BrowserTestUtils.browserLoaded(browser, false, url);
-}
-
-const PREF_SECURITY_DELAY_INITIAL = Services.prefs.getIntPref("security.notification_enable_delay");
-
-function setup() {
- // Disable transitions as they slow the test down and we want to click the
- // mouse buttons in a predictable location.
-
- registerCleanupFunction(() => {
- PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL;
- });
-}
-
-function goNext() {
- executeSoon(() => executeSoon(Task.async(runNextTest)));
-}
-
-function* runNextTest() {
- if (tests.length == 0) {
- executeSoon(finish);
- return;
- }
-
- let nextTest = tests.shift();
- if (nextTest.onShown) {
- let shownState = false;
- onPopupEvent("popupshowing", function () {
- info("[" + nextTest.id + "] popup showing");
- });
- onPopupEvent("popupshown", function () {
- shownState = true;
- info("[" + nextTest.id + "] popup shown");
- Task.spawn(() => nextTest.onShown(this))
- .then(undefined, ex => Assert.ok(false, "onShown failed: " + ex));
- });
- onPopupEvent("popuphidden", function () {
- info("[" + nextTest.id + "] popup hidden");
- Task.spawn(() => nextTest.onHidden(this))
- .then(() => goNext(), ex => Assert.ok(false, "onHidden failed: " + ex));
- }, () => shownState);
- info("[" + nextTest.id + "] added listeners; panel is open: " + PopupNotifications.isPanelOpen);
- }
-
- info("[" + nextTest.id + "] running test");
- yield nextTest.run();
-}
-
-function showNotification(notifyObj) {
- info("Showing notification " + notifyObj.id);
- return PopupNotifications.show(notifyObj.browser,
- notifyObj.id,
- notifyObj.message,
- notifyObj.anchorID,
- notifyObj.mainAction,
- notifyObj.secondaryActions,
- notifyObj.options);
-}
-
-function dismissNotification(popup) {
- info("Dismissing notification " + popup.childNodes[0].id);
- executeSoon(() => EventUtils.synthesizeKey("VK_ESCAPE", {}));
-}
-
-function BasicNotification(testId) {
- this.browser = gBrowser.selectedBrowser;
- this.id = "test-notification-" + testId;
- this.message = "This is popup notification for " + testId;
- this.anchorID = null;
- this.mainAction = {
- label: "Main Action",
- accessKey: "M",
- callback: () => this.mainActionClicked = true
- };
- this.secondaryActions = [
- {
- label: "Secondary Action",
- accessKey: "S",
- callback: () => this.secondaryActionClicked = true
- }
- ];
- this.options = {
- eventCallback: eventName => {
- switch (eventName) {
- case "dismissed":
- this.dismissalCallbackTriggered = true;
- break;
- case "showing":
- this.showingCallbackTriggered = true;
- break;
- case "shown":
- this.shownCallbackTriggered = true;
- break;
- case "removed":
- this.removedCallbackTriggered = true;
- break;
- case "swapping":
- this.swappingCallbackTriggered = true;
- break;
- }
- }
- };
-}
-
-BasicNotification.prototype.addOptions = function(options) {
- for (let [name, value] of Object.entries(options))
- this.options[name] = value;
-};
-
-function ErrorNotification() {
- this.mainAction.callback = () => {
- this.mainActionClicked = true;
- throw new Error("Oops!");
- };
- this.secondaryActions[0].callback = () => {
- this.secondaryActionClicked = true;
- throw new Error("Oops!");
- };
-}
-
-ErrorNotification.prototype = new BasicNotification();
-ErrorNotification.prototype.constructor = ErrorNotification;
-
-function checkPopup(popup, notifyObj) {
- info("Checking notification " + notifyObj.id);
-
- ok(notifyObj.showingCallbackTriggered, "showing callback was triggered");
- ok(notifyObj.shownCallbackTriggered, "shown callback was triggered");
-
- let notifications = popup.childNodes;
- is(notifications.length, 1, "one notification displayed");
- let notification = notifications[0];
- if (!notification)
- return;
- let icon = document.getAnonymousElementByAttribute(notification, "class",
- "popup-notification-icon");
- if (notifyObj.id == "geolocation") {
- isnot(icon.boxObject.width, 0, "icon for geo displayed");
- ok(popup.anchorNode.classList.contains("notification-anchor-icon"),
- "notification anchored to icon");
- }
- is(notification.getAttribute("label"), notifyObj.message, "message matches");
- is(notification.id, notifyObj.id + "-notification", "id matches");
- if (notifyObj.mainAction) {
- is(notification.getAttribute("buttonlabel"), notifyObj.mainAction.label,
- "main action label matches");
- is(notification.getAttribute("buttonaccesskey"),
- notifyObj.mainAction.accessKey, "main action accesskey matches");
- }
- let actualSecondaryActions =
- Array.filter(notification.childNodes, child => child.nodeName == "menuitem");
- let secondaryActions = notifyObj.secondaryActions || [];
- let actualSecondaryActionsCount = actualSecondaryActions.length;
- if (notifyObj.options.hideNotNow) {
- is(notification.getAttribute("hidenotnow"), "true", "'Not Now' item hidden");
- if (secondaryActions.length)
- is(notification.lastChild.tagName, "menuitem", "no menuseparator");
- }
- else if (secondaryActions.length) {
- is(notification.lastChild.tagName, "menuseparator", "menuseparator exists");
- }
- is(actualSecondaryActionsCount, secondaryActions.length,
- actualSecondaryActions.length + " secondary actions");
- secondaryActions.forEach(function (a, i) {
- is(actualSecondaryActions[i].getAttribute("label"), a.label,
- "label for secondary action " + i + " matches");
- is(actualSecondaryActions[i].getAttribute("accesskey"), a.accessKey,
- "accessKey for secondary action " + i + " matches");
- });
-}
-
-XPCOMUtils.defineLazyGetter(this, "gActiveListeners", () => {
- let listeners = new Map();
- registerCleanupFunction(() => {
- for (let [listener, eventName] of listeners) {
- PopupNotifications.panel.removeEventListener(eventName, listener, false);
- }
- });
- return listeners;
-});
-
-function onPopupEvent(eventName, callback, condition) {
- let listener = event => {
- if (event.target != PopupNotifications.panel ||
- (condition && !condition()))
- return;
- PopupNotifications.panel.removeEventListener(eventName, listener, false);
- gActiveListeners.delete(listener);
- executeSoon(() => callback.call(PopupNotifications.panel));
- }
- gActiveListeners.set(listener, eventName);
- PopupNotifications.panel.addEventListener(eventName, listener, false);
-}
-
-function waitForNotificationPanel() {
- return new Promise(resolve => {
- onPopupEvent("popupshown", function() {
- resolve(this);
- });
- });
-}
-
-function triggerMainCommand(popup) {
- let notifications = popup.childNodes;
- ok(notifications.length > 0, "at least one notification displayed");
- let notification = notifications[0];
- info("Triggering main command for notification " + notification.id);
- // 20, 10 so that the inner button is hit
- EventUtils.synthesizeMouse(notification.button, 20, 10, {});
-}
-
-function triggerSecondaryCommand(popup, index) {
- let notifications = popup.childNodes;
- ok(notifications.length > 0, "at least one notification displayed");
- let notification = notifications[0];
- info("Triggering secondary command for notification " + notification.id);
- // Cancel the arrow panel slide-in transition (bug 767133) such that
- // it won't interfere with us interacting with the dropdown.
- document.getAnonymousNodes(popup)[0].style.transition = "none";
-
- notification.button.focus();
-
- popup.addEventListener("popupshown", function handle() {
- popup.removeEventListener("popupshown", handle, false);
- info("Command popup open for notification " + notification.id);
- // Press down until the desired command is selected
- for (let i = 0; i <= index; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {});
- }
- // Activate
- EventUtils.synthesizeKey("VK_RETURN", {});
- }, false);
-
- // One down event to open the popup
- info("Open the popup to trigger secondary command for notification " + notification.id);
- EventUtils.synthesizeKey("VK_DOWN", { altKey: !navigator.platform.includes("Mac") });
-}
diff --git a/browser/base/content/test/popups/browser.ini b/browser/base/content/test/popups/browser.ini
deleted file mode 100644
index 46a32783b..000000000
--- a/browser/base/content/test/popups/browser.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[browser_popupUI.js]
-[browser_popup_blocker.js]
-support-files = popup_blocker.html
-skip-if = (os == 'linux') || (e10s && debug) # Frequent bug 1081925 and bug 1125520 failures
diff --git a/browser/base/content/test/popups/browser_popupUI.js b/browser/base/content/test/popups/browser_popupUI.js
deleted file mode 100644
index 7c6805f60..000000000
--- a/browser/base/content/test/popups/browser_popupUI.js
+++ /dev/null
@@ -1,37 +0,0 @@
-function test() {
- waitForExplicitFinish();
- SpecialPowers.pushPrefEnv({ set: [[ "dom.disable_open_during_load", false ]] });
-
- let popupOpened = BrowserTestUtils.waitForNewWindow(true, "about:blank");
- BrowserTestUtils.openNewForegroundTab(gBrowser,
- "data:text/html,<html><script>popup=open('about:blank','','width=300,height=200')</script>"
- );
- popupOpened.then((win) => testPopupUI(win));
-}
-
-function testPopupUI(win) {
- var doc = win.document;
-
- ok(win.gURLBar, "location bar exists in the popup");
- isnot(win.gURLBar.clientWidth, 0, "location bar is visible in the popup");
- ok(win.gURLBar.readOnly, "location bar is read-only in the popup");
- isnot(doc.getElementById("Browser:OpenLocation").getAttribute("disabled"), "true",
- "'open location' command is not disabled in the popup");
-
- let historyButton = doc.getAnonymousElementByAttribute(win.gURLBar, "anonid",
- "historydropmarker");
- is(historyButton.clientWidth, 0, "history dropdown button is hidden in the popup");
-
- EventUtils.synthesizeKey("t", { accelKey: true }, win);
- is(win.gBrowser.browsers.length, 1, "Accel+T doesn't open a new tab in the popup");
- is(gBrowser.browsers.length, 3, "Accel+T opened a new tab in the parent window");
- gBrowser.removeCurrentTab();
-
- EventUtils.synthesizeKey("w", { accelKey: true }, win);
- ok(win.closed, "Accel+W closes the popup");
-
- if (!win.closed)
- win.close();
- gBrowser.removeCurrentTab();
- finish();
-}
diff --git a/browser/base/content/test/popups/browser_popup_blocker.js b/browser/base/content/test/popups/browser_popup_blocker.js
deleted file mode 100644
index 8cadfea57..000000000
--- a/browser/base/content/test/popups/browser_popup_blocker.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* 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/. */
-
-const baseURL = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-
-function clearAllPermissionsByPrefix(aPrefix) {
- let perms = Services.perms.enumerator;
- while (perms.hasMoreElements()) {
- let perm = perms.getNext();
- if (perm.type.startsWith(aPrefix)) {
- Services.perms.removePermission(perm);
- }
- }
-}
-
-add_task(function* test_opening_blocked_popups() {
- // Enable the popup blocker.
- yield SpecialPowers.pushPrefEnv({set: [["dom.disable_open_during_load", true]]});
-
- // Open the test page.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, baseURL + "popup_blocker.html");
-
- // Wait for the popup-blocked notification.
- let notification;
- yield BrowserTestUtils.waitForCondition(() =>
- notification = gBrowser.getNotificationBox().getNotificationWithValue("popup-blocked"));
-
- // Show the menu.
- let popupShown = BrowserTestUtils.waitForEvent(window, "popupshown");
- let popupFilled = BrowserTestUtils.waitForMessage(gBrowser.selectedBrowser.messageManager,
- "PopupBlocking:ReplyGetBlockedPopupList");
- notification.querySelector("button").doCommand();
- let popup_event = yield popupShown;
- let menu = popup_event.target;
- is(menu.id, "blockedPopupOptions", "Blocked popup menu shown");
-
- yield popupFilled;
- // The menu is filled on the same message that we waited for, so let's ensure that it
- // had a chance of running before this test code.
- yield new Promise(resolve => executeSoon(resolve));
-
- // Check the menu contents.
- let sep = menu.querySelector("menuseparator");
- let popupCount = 0;
- for (let i = sep.nextElementSibling; i; i = i.nextElementSibling) {
- popupCount++;
- }
- is(popupCount, 2, "Two popups were blocked");
-
- // Pressing "allow" should open all blocked popups.
- let popupTabs = [];
- function onTabOpen(event) {
- popupTabs.push(event.target);
- }
- gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen);
-
- // Press the button.
- let allow = menu.querySelector("[observes='blockedPopupAllowSite']");
- allow.doCommand();
- yield BrowserTestUtils.waitForCondition(() =>
- popupTabs.length == 2 &&
- popupTabs.every(aTab => aTab.linkedBrowser.currentURI.spec != "about:blank"));
-
- gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen);
-
- is(popupTabs[0].linkedBrowser.currentURI.spec, "data:text/plain;charset=utf-8,a", "Popup a");
- is(popupTabs[1].linkedBrowser.currentURI.spec, "data:text/plain;charset=utf-8,b", "Popup b");
-
- // Clean up.
- gBrowser.removeTab(tab);
- for (let popup of popupTabs) {
- gBrowser.removeTab(popup);
- }
- clearAllPermissionsByPrefix("popup");
- // Ensure the menu closes.
- menu.hidePopup();
-});
-
-add_task(function* check_icon_hides() {
- // Enable the popup blocker.
- yield SpecialPowers.pushPrefEnv({set: [["dom.disable_open_during_load", true]]});
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, baseURL + "popup_blocker.html");
-
- let button = document.getElementById("page-report-button");
- yield BrowserTestUtils.waitForCondition(() =>
- gBrowser.getNotificationBox().getNotificationWithValue("popup-blocked"));
- ok(!button.hidden, "Button should be visible");
-
- let otherPageLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- openLinkIn(baseURL, "current", {});
- yield otherPageLoaded;
- ok(button.hidden, "Button should have hidden again after another page loaded.");
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/popups/popup_blocker.html b/browser/base/content/test/popups/popup_blocker.html
deleted file mode 100644
index 6e2b7db15..000000000
--- a/browser/base/content/test/popups/popup_blocker.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="UTF-8">
- <title>Page creating two popups</title>
- </head>
- <body>
- <script type="text/javascript">
- window.open("data:text/plain;charset=utf-8,a", "a");
- window.open("data:text/plain;charset=utf-8,b", "b");
- </script>
- </body>
-</html>
diff --git a/browser/base/content/test/referrer/.eslintrc.js b/browser/base/content/test/referrer/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/referrer/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/referrer/browser.ini b/browser/base/content/test/referrer/browser.ini
deleted file mode 100644
index 13b712850..000000000
--- a/browser/base/content/test/referrer/browser.ini
+++ /dev/null
@@ -1,24 +0,0 @@
-[DEFAULT]
-support-files =
- file_referrer_policyserver.sjs
- file_referrer_policyserver_attr.sjs
- file_referrer_testserver.sjs
- head.js
-
-[browser_referrer_middle_click.js]
-[browser_referrer_middle_click_in_container.js]
-[browser_referrer_open_link_in_private.js]
-skip-if = os == 'linux' # Bug 1145199
-[browser_referrer_open_link_in_tab.js]
-skip-if = os == 'linux' # Bug 1144816
-[browser_referrer_open_link_in_window.js]
-skip-if = os == 'linux' # Bug 1145199
-[browser_referrer_open_link_in_window_in_container.js]
-skip-if = os == 'linux' # Bug 1145199
-[browser_referrer_simple_click.js]
-[browser_referrer_open_link_in_container_tab.js]
-skip-if = os == 'linux' # Bug 1144816
-[browser_referrer_open_link_in_container_tab2.js]
-skip-if = os == 'linux' # Bug 1144816
-[browser_referrer_open_link_in_container_tab3.js]
-skip-if = os == 'linux' # Bug 1144816
diff --git a/browser/base/content/test/referrer/browser_referrer_middle_click.js b/browser/base/content/test/referrer/browser_referrer_middle_click.js
deleted file mode 100644
index e6e01c6a3..000000000
--- a/browser/base/content/test/referrer/browser_referrer_middle_click.js
+++ /dev/null
@@ -1,20 +0,0 @@
-// Tests referrer on middle-click navigation.
-// Middle-clicks on the link, which opens it in a new tab.
-
-function startMiddleClickTestCase(aTestNumber) {
- info("browser_referrer_middle_click: " +
- getReferrerTestDescription(aTestNumber));
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- BrowserTestUtils.switchTab(gTestWindow.gBrowser, aNewTab).then(() => {
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startMiddleClickTestCase);
- });
- });
-
- clickTheLink(gTestWindow, "testlink", {button: 1});
-}
-
-function test() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startMiddleClickTestCase);
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_middle_click_in_container.js b/browser/base/content/test/referrer/browser_referrer_middle_click_in_container.js
deleted file mode 100644
index e89b891f3..000000000
--- a/browser/base/content/test/referrer/browser_referrer_middle_click_in_container.js
+++ /dev/null
@@ -1,27 +0,0 @@
-// Tests referrer on middle-click navigation.
-// Middle-clicks on the link, which opens it in a new tab, same container.
-
-function startMiddleClickTestCase(aTestNumber) {
- info("browser_referrer_middle_click: " +
- getReferrerTestDescription(aTestNumber));
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- BrowserTestUtils.switchTab(gTestWindow.gBrowser, aNewTab).then(() => {
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startMiddleClickTestCase,
- { userContextId: 3 });
- });
- });
-
- clickTheLink(gTestWindow, "testlink", {button: 1});
-}
-
-function test() {
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- {set: [["privacy.userContext.enabled", true]]},
- function() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startMiddleClickTestCase, { userContextId: 3 });
- });
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab.js
deleted file mode 100644
index deaf90fb9..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// Tests referrer on context menu navigation - open link in new container tab.
-// Selects "open link in new container tab" from the context menu.
-
-function getReferrerTest(aTestNumber) {
- let test = _referrerTests[aTestNumber];
- if (test) {
- // We want all the referrer tests to fail!
- test.result = "";
- }
-
- return test;
-}
-
-function startNewTabTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_container_tab: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- gTestWindow.gBrowser.selectedTab = aNewTab;
-
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startNewTabTestCase);
- });
-
- let menu = gTestWindow.document.getElementById("context-openlinkinusercontext-menu");
-
- let menupopup = menu.menupopup;
- menu.addEventListener("popupshown", function onPopupShown() {
- menu.removeEventListener("popupshown", onPopupShown);
-
- is(menupopup.nodeType, Node.ELEMENT_NODE, "We have a menupopup.");
- ok(menupopup.firstChild, "We have a first container entry.");
-
- let firstContext = menupopup.firstChild;
- is(firstContext.nodeType, Node.ELEMENT_NODE, "We have a first container entry.");
- ok(firstContext.hasAttribute("data-usercontextid"), "We have a usercontextid value.");
-
- aContextMenu.addEventListener("popuphidden", function onPopupHidden() {
- aContextMenu.removeEventListener("popuphidden", onPopupHidden);
- firstContext.doCommand();
- });
-
- aContextMenu.hidePopup();
- });
-
- menupopup.showPopup();
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- {set: [["privacy.userContext.enabled", true]]},
- function() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewTabTestCase);
- });
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab2.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab2.js
deleted file mode 100644
index 77a5645c6..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab2.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// Tests referrer on context menu navigation - open link in new container tab.
-// Selects "open link in new container tab" from the context menu.
-
-// The test runs from a container ID 1.
-// Output: we have the correct referrer policy applied.
-
-function startNewTabTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_container_tab: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- gTestWindow.gBrowser.selectedTab = aNewTab;
-
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startNewTabTestCase, { userContextId: 1 });
- });
-
- doContextMenuCommand(gTestWindow, aContextMenu, "context-openlinkincontainertab");
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- {set: [["privacy.userContext.enabled", true]]},
- function() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewTabTestCase, { userContextId: 1 });
- });
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab3.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab3.js
deleted file mode 100644
index c0a73d828..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_container_tab3.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Tests referrer on context menu navigation - open link in new container tab.
-// Selects "open link in new container tab" from the context menu.
-
-// The test runs from a container ID 2.
-// Output: we have no referrer.
-
-function getReferrerTest(aTestNumber) {
- let test = _referrerTests[aTestNumber];
- if (test) {
- // We want all the referrer tests to fail!
- test.result = "";
- }
-
- return test;
-}
-
-function startNewTabTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_container_tab: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- gTestWindow.gBrowser.selectedTab = aNewTab;
-
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startNewTabTestCase, { userContextId: 2 });
- });
-
- let menu = gTestWindow.document.getElementById("context-openlinkinusercontext-menu");
-
- let menupopup = menu.menupopup;
- menu.addEventListener("popupshown", function onPopupShown() {
- menu.removeEventListener("popupshown", onPopupShown);
-
- is(menupopup.nodeType, Node.ELEMENT_NODE, "We have a menupopup.");
- ok(menupopup.firstChild, "We have a first container entry.");
-
- let firstContext = menupopup.firstChild;
- is(firstContext.nodeType, Node.ELEMENT_NODE, "We have a first container entry.");
- ok(firstContext.hasAttribute("data-usercontextid"), "We have a usercontextid value.");
- is("0", firstContext.getAttribute("data-usercontextid"), "We have the right usercontextid value.");
-
- aContextMenu.addEventListener("popuphidden", function onPopupHidden() {
- aContextMenu.removeEventListener("popuphidden", onPopupHidden);
- firstContext.doCommand();
- });
-
- aContextMenu.hidePopup();
- });
-
- menupopup.showPopup();
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- {set: [["privacy.userContext.enabled", true]]},
- function() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewTabTestCase, { userContextId: 2 });
- });
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_private.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_private.js
deleted file mode 100644
index 8f12e3824..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_private.js
+++ /dev/null
@@ -1,22 +0,0 @@
-// Tests referrer on context menu navigation - open link in new private window.
-// Selects "open link in new private window" from the context menu.
-
-function startNewPrivateWindowTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_private: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- newWindowOpened().then(function(aNewWindow) {
- BrowserTestUtils.firstBrowserLoaded(aNewWindow, false).then(function() {
- checkReferrerAndStartNextTest(aTestNumber, aNewWindow, null,
- startNewPrivateWindowTestCase);
- });
- });
-
- doContextMenuCommand(gTestWindow, aContextMenu, "context-openlinkprivate");
- });
-}
-
-function test() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewPrivateWindowTestCase);
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_tab.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_tab.js
deleted file mode 100644
index 03119cb57..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_tab.js
+++ /dev/null
@@ -1,21 +0,0 @@
-// Tests referrer on context menu navigation - open link in new tab.
-// Selects "open link in new tab" from the context menu.
-
-function startNewTabTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_tab: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- someTabLoaded(gTestWindow).then(function(aNewTab) {
- gTestWindow.gBrowser.selectedTab = aNewTab;
- checkReferrerAndStartNextTest(aTestNumber, null, aNewTab,
- startNewTabTestCase);
- });
-
- doContextMenuCommand(gTestWindow, aContextMenu, "context-openlinkintab");
- });
-}
-
-function test() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewTabTestCase);
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_window.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_window.js
deleted file mode 100644
index 81e7b2648..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_window.js
+++ /dev/null
@@ -1,22 +0,0 @@
-// Tests referrer on context menu navigation - open link in new window.
-// Selects "open link in new window" from the context menu.
-
-function startNewWindowTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_window: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- newWindowOpened().then(function(aNewWindow) {
- BrowserTestUtils.firstBrowserLoaded(aNewWindow, false).then(function() {
- checkReferrerAndStartNextTest(aTestNumber, aNewWindow, null,
- startNewWindowTestCase);
- });
- });
-
- doContextMenuCommand(gTestWindow, aContextMenu, "context-openlink");
- });
-}
-
-function test() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewWindowTestCase);
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_open_link_in_window_in_container.js b/browser/base/content/test/referrer/browser_referrer_open_link_in_window_in_container.js
deleted file mode 100644
index d5ce87952..000000000
--- a/browser/base/content/test/referrer/browser_referrer_open_link_in_window_in_container.js
+++ /dev/null
@@ -1,32 +0,0 @@
-// Tests referrer on context menu navigation - open link in new window.
-// Selects "open link in new window" from the context menu.
-
-// This test runs from a container tab. The new tab/window will be loaded in
-// the same container.
-
-function startNewWindowTestCase(aTestNumber) {
- info("browser_referrer_open_link_in_window: " +
- getReferrerTestDescription(aTestNumber));
- contextMenuOpened(gTestWindow, "testlink").then(function(aContextMenu) {
- newWindowOpened().then(function(aNewWindow) {
- BrowserTestUtils.firstBrowserLoaded(aNewWindow, false).then(function() {
- checkReferrerAndStartNextTest(aTestNumber, aNewWindow, null,
- startNewWindowTestCase,
- { userContextId: 1 });
- });
- });
-
- doContextMenuCommand(gTestWindow, aContextMenu, "context-openlink");
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- SpecialPowers.pushPrefEnv(
- {set: [["privacy.userContext.enabled", true]]},
- function() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startNewWindowTestCase, { userContextId: 1 });
- });
-}
diff --git a/browser/base/content/test/referrer/browser_referrer_simple_click.js b/browser/base/content/test/referrer/browser_referrer_simple_click.js
deleted file mode 100644
index 7f3784e64..000000000
--- a/browser/base/content/test/referrer/browser_referrer_simple_click.js
+++ /dev/null
@@ -1,20 +0,0 @@
-// Tests referrer on simple click navigation.
-// Clicks on the link, which opens it in the same tab.
-
-function startSimpleClickTestCase(aTestNumber) {
- info("browser_referrer_simple_click: " +
- getReferrerTestDescription(aTestNumber));
- BrowserTestUtils.browserLoaded(gTestWindow.gBrowser.selectedBrowser, false,
- (url) => url.endsWith("file_referrer_testserver.sjs"))
- .then(function() {
- checkReferrerAndStartNextTest(aTestNumber, null, null,
- startSimpleClickTestCase);
- });
-
- clickTheLink(gTestWindow, "testlink", {});
-}
-
-function test() {
- requestLongerTimeout(10); // slowwww shutdown on e10s
- startReferrerTest(startSimpleClickTestCase);
-}
diff --git a/browser/base/content/test/referrer/file_referrer_policyserver.sjs b/browser/base/content/test/referrer/file_referrer_policyserver.sjs
deleted file mode 100644
index e07965675..000000000
--- a/browser/base/content/test/referrer/file_referrer_policyserver.sjs
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Renders a link with the provided referrer policy.
- * Used in browser_referrer_*.js, bug 1113431.
- * Arguments: ?scheme=http://&policy=origin&rel=noreferrer
- */
-function handleRequest(request, response)
-{
- Components.utils.importGlobalProperties(["URLSearchParams"]);
- let query = new URLSearchParams(request.queryString);
-
- let scheme = query.get("scheme");
- let policy = query.get("policy");
- let rel = query.get("rel");
-
- let linkUrl = scheme +
- "test1.example.com/browser/browser/base/content/test/referrer/" +
- "file_referrer_testserver.sjs";
- let metaReferrerTag =
- policy ? `<meta name='referrer' content='${policy}'>` : "";
-
- let html = `<!DOCTYPE HTML>
- <html>
- <head>
- <meta charset='utf-8'>
- ${metaReferrerTag}
- <title>Test referrer</title>
- </head>
- <body>
- <a id='testlink' href='${linkUrl}' ${rel ? ` rel='${rel}'` : ""}>
- referrer test link</a>
- </body>
- </html>`;
-
- response.setHeader("Cache-Control", "no-cache", false);
- response.setHeader("Content-Type", "text/html", false);
- response.write(html);
-}
diff --git a/browser/base/content/test/referrer/file_referrer_policyserver_attr.sjs b/browser/base/content/test/referrer/file_referrer_policyserver_attr.sjs
deleted file mode 100644
index 25a58188a..000000000
--- a/browser/base/content/test/referrer/file_referrer_policyserver_attr.sjs
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Renders a link with the provided referrer policy.
- * Used in browser_referrer_*.js, bug 1113431.
- * Arguments: ?scheme=http://&policy=origin&rel=noreferrer
- */
-function handleRequest(request, response)
-{
- Components.utils.importGlobalProperties(["URLSearchParams"]);
- let query = new URLSearchParams(request.queryString);
-
- let scheme = query.get("scheme");
- let policy = query.get("policy");
- let rel = query.get("rel");
-
- let linkUrl = scheme +
- "test1.example.com/browser/browser/base/content/test/referrer/" +
- "file_referrer_testserver.sjs";
- let referrerPolicy =
- policy ? `referrerpolicy="${policy}"` : "";
-
- let html = `<!DOCTYPE HTML>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Test referrer</title>
- </head>
- <body>
- <a id='testlink' href='${linkUrl}' ${referrerPolicy} ${rel ? ` rel='${rel}'` : ""}>
- referrer test link</a>
- </body>
- </html>`;
-
- response.setHeader("Cache-Control", "no-cache", false);
- response.setHeader("Content-Type", "text/html", false);
- response.write(html);
-}
diff --git a/browser/base/content/test/referrer/file_referrer_testserver.sjs b/browser/base/content/test/referrer/file_referrer_testserver.sjs
deleted file mode 100644
index 0cfc53b2c..000000000
--- a/browser/base/content/test/referrer/file_referrer_testserver.sjs
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Renders the HTTP Referer header up to the second path slash.
- * Used in browser_referrer_*.js, bug 1113431.
- */
-function handleRequest(request, response)
-{
- let referrer = "";
- try {
- referrer = request.getHeader("referer");
- } catch (e) {
- referrer = "";
- }
-
- // Strip it past the first path slash. Makes tests easier to read.
- referrer = referrer.split("/").slice(0, 4).join("/");
-
- let html = `<!DOCTYPE HTML>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Test referrer</title>
- </head>
- <body>
- <div id='testdiv'>${referrer}</div>
- </body>
- </html>`;
-
- response.setHeader("Cache-Control", "no-cache", false);
- response.setHeader("Content-Type", "text/html", false);
- response.write(html);
-}
diff --git a/browser/base/content/test/referrer/head.js b/browser/base/content/test/referrer/head.js
deleted file mode 100644
index 1a5d5b051..000000000
--- a/browser/base/content/test/referrer/head.js
+++ /dev/null
@@ -1,265 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "BrowserTestUtils",
- "resource://testing-common/BrowserTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ContentTask",
- "resource://testing-common/ContentTask.jsm");
-
-const REFERRER_URL_BASE = "/browser/browser/base/content/test/referrer/";
-const REFERRER_POLICYSERVER_URL =
- "test1.example.com" + REFERRER_URL_BASE + "file_referrer_policyserver.sjs";
-const REFERRER_POLICYSERVER_URL_ATTRIBUTE =
- "test1.example.com" + REFERRER_URL_BASE + "file_referrer_policyserver_attr.sjs";
-
-SpecialPowers.pushPrefEnv({"set": [['network.http.enablePerElementReferrer', true]]});
-
-var gTestWindow = null;
-var rounds = 0;
-
-// We test that the UI code propagates three pieces of state - the referrer URI
-// itself, the referrer policy, and the triggering principal. After that, we
-// trust nsIWebNavigation to do the right thing with the info it's given, which
-// is covered more exhaustively by dom/base/test/test_bug704320.html (which is
-// a faster content-only test). So, here, we limit ourselves to cases that
-// would break when the UI code drops either of these pieces; we don't try to
-// duplicate the entire cross-product test in bug 704320 - that would be slow,
-// especially when we're opening a new window for each case.
-var _referrerTests = [
- // 1. Normal cases - no referrer policy, no special attributes.
- // We expect a full referrer normally, and no referrer on downgrade.
- {
- fromScheme: "http://",
- toScheme: "http://",
- result: "http://test1.example.com/browser" // full referrer
- },
- {
- fromScheme: "https://",
- toScheme: "http://",
- result: "" // no referrer when downgrade
- },
- // 2. Origin referrer policy - we expect an origin referrer,
- // even on downgrade. But rel=noreferrer trumps this.
- {
- fromScheme: "https://",
- toScheme: "http://",
- policy: "origin",
- result: "https://test1.example.com/" // origin, even on downgrade
- },
- {
- fromScheme: "https://",
- toScheme: "http://",
- policy: "origin",
- rel: "noreferrer",
- result: "" // rel=noreferrer trumps meta-referrer
- },
- // 3. XXX: using no-referrer here until we support all attribute values (bug 1178337)
- // Origin-when-cross-origin policy - this depends on the triggering
- // principal. We expect full referrer for same-origin requests,
- // and origin referrer for cross-origin requests.
- {
- fromScheme: "https://",
- toScheme: "https://",
- policy: "no-referrer",
- result: "" // same origin https://test1.example.com/browser
- },
- {
- fromScheme: "http://",
- toScheme: "https://",
- policy: "no-referrer",
- result: "" // cross origin http://test1.example.com
- },
-];
-
-/**
- * Returns the test object for a given test number.
- * @param aTestNumber The test number - 0, 1, 2, ...
- * @return The test object, or undefined if the number is out of range.
- */
-function getReferrerTest(aTestNumber) {
- return _referrerTests[aTestNumber];
-}
-
-/**
- * Returns a brief summary of the test, for logging.
- * @param aTestNumber The test number - 0, 1, 2...
- * @return The test description.
- */
-function getReferrerTestDescription(aTestNumber) {
- let test = getReferrerTest(aTestNumber);
- return "policy=[" + test.policy + "] " +
- "rel=[" + test.rel + "] " +
- test.fromScheme + " -> " + test.toScheme;
-}
-
-/**
- * Clicks the link.
- * @param aWindow The window to click the link in.
- * @param aLinkId The id of the link element.
- * @param aOptions The options for synthesizeMouseAtCenter.
- */
-function clickTheLink(aWindow, aLinkId, aOptions) {
- return BrowserTestUtils.synthesizeMouseAtCenter(
- "#" + aLinkId, aOptions, aWindow.gBrowser.selectedBrowser);
-}
-
-/**
- * Extracts the referrer result from the target window.
- * @param aWindow The window where the referrer target has loaded.
- * @return {Promise}
- * @resolves When extacted, with the text of the (trimmed) referrer.
- */
-function referrerResultExtracted(aWindow) {
- return ContentTask.spawn(aWindow.gBrowser.selectedBrowser, {}, function() {
- return content.document.getElementById("testdiv").textContent;
- });
-}
-
-/**
- * Waits for browser delayed startup to finish.
- * @param aWindow The window to wait for.
- * @return {Promise}
- * @resolves When the window is loaded.
- */
-function delayedStartupFinished(aWindow) {
- return new Promise(function(resolve) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- resolve();
- }
- }, "browser-delayed-startup-finished", false);
- });
-}
-
-/**
- * Waits for some (any) tab to load. The caller triggers the load.
- * @param aWindow The window where to wait for a tab to load.
- * @return {Promise}
- * @resolves With the tab once it's loaded.
- */
-function someTabLoaded(aWindow) {
- return BrowserTestUtils.waitForNewTab(gTestWindow.gBrowser).then((tab) => {
- return BrowserTestUtils.browserStopped(tab.linkedBrowser).then(() => tab);
- });
-}
-
-/**
- * Waits for a new window to open and load. The caller triggers the open.
- * @return {Promise}
- * @resolves With the new window once it's open and loaded.
- */
-function newWindowOpened() {
- return TestUtils.topicObserved("browser-delayed-startup-finished")
- .then(([win]) => win);
-}
-
-/**
- * Opens the context menu.
- * @param aWindow The window to open the context menu in.
- * @param aLinkId The id of the link to open the context menu on.
- * @return {Promise}
- * @resolves With the menu popup when the context menu is open.
- */
-function contextMenuOpened(aWindow, aLinkId) {
- let popupShownPromise = BrowserTestUtils.waitForEvent(aWindow.document,
- "popupshown");
- // Simulate right-click.
- clickTheLink(aWindow, aLinkId, { type: "contextmenu", button: 2 });
- return popupShownPromise.then(e => e.target);
-}
-
-/**
- * Performs a context menu command.
- * @param aWindow The window with the already open context menu.
- * @param aMenu The menu popup to hide.
- * @param aItemId The id of the menu item to activate.
- */
-function doContextMenuCommand(aWindow, aMenu, aItemId) {
- let command = aWindow.document.getElementById(aItemId);
- command.doCommand();
- aMenu.hidePopup();
-}
-
-/**
- * Loads a single test case, i.e., a source url into gTestWindow.
- * @param aTestNumber The test case number - 0, 1, 2...
- * @return {Promise}
- * @resolves When the source url for this test case is loaded.
- */
-function referrerTestCaseLoaded(aTestNumber, aParams) {
- let test = getReferrerTest(aTestNumber);
- let server = rounds == 0 ? REFERRER_POLICYSERVER_URL :
- REFERRER_POLICYSERVER_URL_ATTRIBUTE;
- let url = test.fromScheme + server +
- "?scheme=" + escape(test.toScheme) +
- "&policy=" + escape(test.policy || "") +
- "&rel=" + escape(test.rel || "");
- let browser = gTestWindow.gBrowser;
- return BrowserTestUtils.openNewForegroundTab(browser, () => {
- browser.selectedTab = browser.addTab(url, aParams);
- }, false, true);
-}
-
-/**
- * Checks the result of the referrer test, and moves on to the next test.
- * @param aTestNumber The test number - 0, 1, 2, ...
- * @param aNewWindow The new window where the referrer target opened, or null.
- * @param aNewTab The new tab where the referrer target opened, or null.
- * @param aStartTestCase The callback to start the next test, aTestNumber + 1.
- */
-function checkReferrerAndStartNextTest(aTestNumber, aNewWindow, aNewTab,
- aStartTestCase, aParams = {}) {
- referrerResultExtracted(aNewWindow || gTestWindow).then(function(result) {
- // Compare the actual result against the expected one.
- let test = getReferrerTest(aTestNumber);
- let desc = getReferrerTestDescription(aTestNumber);
- is(result, test.result, desc);
-
- // Clean up - close new tab / window, and then the source tab.
- aNewTab && (aNewWindow || gTestWindow).gBrowser.removeTab(aNewTab);
- aNewWindow && aNewWindow.close();
- is(gTestWindow.gBrowser.tabs.length, 2, "two tabs open");
- gTestWindow.gBrowser.removeTab(gTestWindow.gBrowser.tabs[1]);
-
- // Move on to the next test. Or finish if we're done.
- var nextTestNumber = aTestNumber + 1;
- if (getReferrerTest(nextTestNumber)) {
- referrerTestCaseLoaded(nextTestNumber, aParams).then(function() {
- aStartTestCase(nextTestNumber);
- });
- } else if (rounds == 0) {
- nextTestNumber = 0;
- rounds = 1;
- referrerTestCaseLoaded(nextTestNumber, aParams).then(function() {
- aStartTestCase(nextTestNumber);
- });
- } else {
- finish();
- }
- });
-}
-
-/**
- * Fires up the complete referrer test.
- * @param aStartTestCase The callback to start a single test case, called with
- * the test number - 0, 1, 2... Needs to trigger the navigation from the source
- * page, and call checkReferrerAndStartNextTest() when the target is loaded.
- */
-function startReferrerTest(aStartTestCase, params = {}) {
- waitForExplicitFinish();
-
- // Open the window where we'll load the source URLs.
- gTestWindow = openDialog(location, "", "chrome,all,dialog=no", "about:blank");
- registerCleanupFunction(function() {
- gTestWindow && gTestWindow.close();
- });
-
- // Load and start the first test.
- delayedStartupFinished(gTestWindow).then(function() {
- referrerTestCaseLoaded(0, params).then(function() {
- aStartTestCase(0);
- });
- });
-}
diff --git a/browser/base/content/test/siteIdentity/browser.ini b/browser/base/content/test/siteIdentity/browser.ini
deleted file mode 100644
index 6ad3668fd..000000000
--- a/browser/base/content/test/siteIdentity/browser.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-
-[browser_identityBlock_focus.js]
-skip-if = os == 'mac' # Bug 1334418 (try only)
-support-files = ../general/permissions.html
-[browser_identityPopup_focus.js]
diff --git a/browser/base/content/test/siteIdentity/browser_identityBlock_focus.js b/browser/base/content/test/siteIdentity/browser_identityBlock_focus.js
deleted file mode 100644
index e1e4e537a..000000000
--- a/browser/base/content/test/siteIdentity/browser_identityBlock_focus.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Tests that the identity block can be reached via keyboard
- * shortcuts and that it has the correct tab order.
- */
-
-const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "https://example.com");
-const PERMISSIONS_PAGE = TEST_PATH + "permissions.html";
-
-function synthesizeKeyAndWaitForFocus(element, keyCode, options) {
- let focused = BrowserTestUtils.waitForEvent(element, "focus");
- EventUtils.synthesizeKey(keyCode, options);
- return focused;
-}
-
-// Checks that the identity block is the next element after the urlbar
-// to be focused if there are no active notification anchors.
-add_task(function* testWithoutNotifications() {
- yield BrowserTestUtils.withNewTab("https://example.com", function*() {
- yield synthesizeKeyAndWaitForFocus(gURLBar, "l", {accelKey: true})
- is(document.activeElement, gURLBar.inputField, "urlbar should be focused");
- yield synthesizeKeyAndWaitForFocus(gIdentityHandler._identityBox, "VK_TAB", {shiftKey: true})
- is(document.activeElement, gIdentityHandler._identityBox,
- "identity block should be focused");
- });
-});
-
-// Checks that when there is a notification anchor, it will receive
-// focus before the identity block.
-add_task(function* testWithoutNotifications() {
-
- yield BrowserTestUtils.withNewTab(PERMISSIONS_PAGE, function*(browser) {
- let popupshown = BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- // Request a permission;
- BrowserTestUtils.synthesizeMouseAtCenter("#geo", {}, browser);
- yield popupshown;
-
- yield synthesizeKeyAndWaitForFocus(gURLBar, "l", {accelKey: true})
- is(document.activeElement, gURLBar.inputField, "urlbar should be focused");
- let geoIcon = document.getElementById("geo-notification-icon");
- yield synthesizeKeyAndWaitForFocus(geoIcon, "VK_TAB", {shiftKey: true})
- is(document.activeElement, geoIcon, "notification anchor should be focused");
- yield synthesizeKeyAndWaitForFocus(gIdentityHandler._identityBox, "VK_TAB", {shiftKey: true})
- is(document.activeElement, gIdentityHandler._identityBox,
- "identity block should be focused");
- });
-});
-
-// Checks that with invalid pageproxystate the identity block is ignored.
-add_task(function* testInvalidPageProxyState() {
- yield BrowserTestUtils.withNewTab("about:blank", function*(browser) {
- // Loading about:blank will automatically focus the urlbar, which, however, can
- // race with the test code. So we only send the shortcut if the urlbar isn't focused yet.
- if (document.activeElement != gURLBar.inputField) {
- yield synthesizeKeyAndWaitForFocus(gURLBar, "l", {accelKey: true})
- }
- is(document.activeElement, gURLBar.inputField, "urlbar should be focused");
- yield synthesizeKeyAndWaitForFocus(gBrowser.getTabForBrowser(browser), "VK_TAB", {shiftKey: true})
- isnot(document.activeElement, gIdentityHandler._identityBox,
- "identity block should not be focused");
- // Restore focus to the url bar.
- gURLBar.focus();
- });
-});
diff --git a/browser/base/content/test/siteIdentity/browser_identityPopup_focus.js b/browser/base/content/test/siteIdentity/browser_identityPopup_focus.js
deleted file mode 100644
index eea06f079..000000000
--- a/browser/base/content/test/siteIdentity/browser_identityPopup_focus.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Tests the focus behavior of the identity popup. */
-
-// Access the identity popup via mouseclick. Focus should not be moved inside.
-add_task(function* testIdentityPopupFocusClick() {
- yield SpecialPowers.pushPrefEnv({"set": [["accessibility.tabfocus", 7]]});
- yield BrowserTestUtils.withNewTab("https://example.com", function*() {
- let shown = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(gIdentityHandler._identityBox, {});
- yield shown;
- isnot(Services.focus.focusedElement, document.getElementById("identity-popup-security-expander"));
- });
-});
-
-// Access the identity popup via keyboard. Focus should be moved inside.
-add_task(function* testIdentityPopupFocusKeyboard() {
- yield SpecialPowers.pushPrefEnv({"set": [["accessibility.tabfocus", 7]]});
- yield BrowserTestUtils.withNewTab("https://example.com", function*() {
- let focused = BrowserTestUtils.waitForEvent(gIdentityHandler._identityBox, "focus");
- gIdentityHandler._identityBox.focus();
- yield focused;
- let shown = BrowserTestUtils.waitForEvent(gIdentityHandler._identityPopup, "popupshown");
- EventUtils.synthesizeKey(" ", {});
- yield shown;
- is(Services.focus.focusedElement, document.getElementById("identity-popup-security-expander"));
- });
-});
-
diff --git a/browser/base/content/test/siteIdentity/head.js b/browser/base/content/test/siteIdentity/head.js
deleted file mode 100644
index 12a0547ee..000000000
--- a/browser/base/content/test/siteIdentity/head.js
+++ /dev/null
@@ -1,6 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
diff --git a/browser/base/content/test/social/.eslintrc.js b/browser/base/content/test/social/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/social/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/social/blocklist.xml b/browser/base/content/test/social/blocklist.xml
deleted file mode 100644
index 2e3665c36..000000000
--- a/browser/base/content/test/social/blocklist.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">
- <emItems>
- <emItem blockID="s1" id="test1.example.com@services.mozilla.org"></emItem>
- </emItems>
-</blocklist>
diff --git a/browser/base/content/test/social/browser.ini b/browser/base/content/test/social/browser.ini
deleted file mode 100644
index 91f931602..000000000
--- a/browser/base/content/test/social/browser.ini
+++ /dev/null
@@ -1,23 +0,0 @@
-[DEFAULT]
-support-files =
- blocklist.xml
- head.js
- opengraph/og_invalid_url.html
- opengraph/opengraph.html
- opengraph/shortlink_linkrel.html
- opengraph/shorturl_link.html
- opengraph/shorturl_linkrel.html
- microformats.html
- share.html
- share_activate.html
- social_activate.html
- social_activate_basic.html
- social_activate_iframe.html
- social_postActivation.html
- !/browser/base/content/test/plugins/blockNoPlugins.xml
-
-[browser_aboutHome_activation.js]
-[browser_addons.js]
-[browser_blocklist.js]
-[browser_share.js]
-[browser_social_activation.js]
diff --git a/browser/base/content/test/social/browser_aboutHome_activation.js b/browser/base/content/test/social/browser_aboutHome_activation.js
deleted file mode 100644
index 37cca53d2..000000000
--- a/browser/base/content/test/social/browser_aboutHome_activation.js
+++ /dev/null
@@ -1,229 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AboutHomeUtils",
- "resource:///modules/AboutHome.jsm");
-
-var snippet =
-' <script>' +
-' var manifest = {' +
-' "name": "Demo Social Service",' +
-' "origin": "https://example.com",' +
-' "iconURL": "chrome://branding/content/icon16.png",' +
-' "icon32URL": "chrome://branding/content/icon32.png",' +
-' "icon64URL": "chrome://branding/content/icon64.png",' +
-' "shareURL": "https://example.com/browser/browser/base/content/test/social/social_share.html",' +
-' "postActivationURL": "https://example.com/browser/browser/base/content/test/social/social_postActivation.html",' +
-' };' +
-' function activateProvider(node) {' +
-' node.setAttribute("data-service", JSON.stringify(manifest));' +
-' var event = new CustomEvent("ActivateSocialFeature");' +
-' node.dispatchEvent(event);' +
-' }' +
-' </script>' +
-' <div id="activationSnippet" onclick="activateProvider(this)">' +
-' <img src="chrome://branding/content/icon32.png"></img>' +
-' </div>';
-
-// enable one-click activation
-var snippet2 =
-' <script>' +
-' var manifest = {' +
-' "name": "Demo Social Service",' +
-' "origin": "https://example.com",' +
-' "iconURL": "chrome://branding/content/icon16.png",' +
-' "icon32URL": "chrome://branding/content/icon32.png",' +
-' "icon64URL": "chrome://branding/content/icon64.png",' +
-' "shareURL": "https://example.com/browser/browser/base/content/test/social/social_share.html",' +
-' "postActivationURL": "https://example.com/browser/browser/base/content/test/social/social_postActivation.html",' +
-' "oneclick": true' +
-' };' +
-' function activateProvider(node) {' +
-' node.setAttribute("data-service", JSON.stringify(manifest));' +
-' var event = new CustomEvent("ActivateSocialFeature");' +
-' node.dispatchEvent(event);' +
-' }' +
-' </script>' +
-' <div id="activationSnippet" onclick="activateProvider(this)">' +
-' <img src="chrome://branding/content/icon32.png"></img>' +
-' </div>';
-
-var gTests = [
-
-{
- desc: "Test activation with enable panel",
- snippet: snippet,
- panel: true
-},
-
-{
- desc: "Test activation bypassing enable panel",
- snippet: snippet2,
- panel: false
-}
-];
-
-function test()
-{
- waitForExplicitFinish();
- requestLongerTimeout(2);
- ignoreAllUncaughtExceptions();
- PopupNotifications.panel.setAttribute("animate", "false");
- registerCleanupFunction(function () {
- PopupNotifications.panel.removeAttribute("animate");
- });
-
- Task.spawn(function* () {
- for (let test of gTests) {
- info(test.desc);
-
- // Create a tab to run the test.
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
-
- // Add an event handler to modify the snippets map once it's ready.
- let snippetsPromise = promiseSetupSnippetsMap(tab, test.snippet);
-
- // Start loading about:home and wait for it to complete, snippets should be loaded
- yield promiseTabLoadEvent(tab, "about:home", "AboutHomeLoadSnippetsCompleted");
-
- yield snippetsPromise;
-
- // ensure our activation snippet is indeed available
- yield ContentTask.spawn(tab.linkedBrowser, {}, function*(arg) {
- ok(!!content.document.getElementById("snippets"), "Found snippets element");
- ok(!!content.document.getElementById("activationSnippet"), "The snippet is present.");
- });
-
- yield new Promise(resolve => {
- activateProvider(tab, test.panel).then(() => {
- checkSocialUI();
- SocialService.uninstallProvider("https://example.com", function () {
- info("provider uninstalled");
- resolve();
- });
- });
- });
-
- // activation opened a post-activation info tab, close it.
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield BrowserTestUtils.removeTab(tab);
- }
- }).then(finish, ex => {
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
-}
-
-/**
- * Starts a load in an existing tab and waits for it to finish (via some event).
- *
- * @param aTab
- * The tab to load into.
- * @param aUrl
- * The url to load.
- * @param aEvent
- * The load event type to wait for. Defaults to "load".
- * @return {Promise} resolved when the event is handled.
- */
-function promiseTabLoadEvent(aTab, aURL, aEventType="load")
-{
- return new Promise(resolve => {
- info("Wait tab event: " + aEventType);
- aTab.linkedBrowser.addEventListener(aEventType, function load(event) {
- if (event.originalTarget != aTab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- aTab.linkedBrowser.removeEventListener(aEventType, load, true);
- info("Tab event received: " + aEventType);
- resolve();
- }, true, true);
- aTab.linkedBrowser.loadURI(aURL);
- });
-}
-
-/**
- * Cleans up snippets and ensures that by default we don't try to check for
- * remote snippets since that may cause network bustage or slowness.
- *
- * @param aTab
- * The tab containing about:home.
- * @param aSetupFn
- * The setup function to be run.
- * @return {Promise} resolved when the snippets are ready. Gets the snippets map.
- */
-function promiseSetupSnippetsMap(aTab, aSnippet)
-{
- info("Waiting for snippets map");
-
- return ContentTask.spawn(aTab.linkedBrowser,
- {snippetsVersion: AboutHomeUtils.snippetsVersion,
- snippet: aSnippet},
- function*(arg) {
- return new Promise(resolve => {
- addEventListener("AboutHomeLoadSnippets", function load(event) {
- removeEventListener("AboutHomeLoadSnippets", load, true);
-
- let cw = content.window.wrappedJSObject;
-
- // The snippets should already be ready by this point. Here we're
- // just obtaining a reference to the snippets map.
- cw.ensureSnippetsMapThen(function (aSnippetsMap) {
- aSnippetsMap = Cu.waiveXrays(aSnippetsMap);
- console.log("Got snippets map: " +
- "{ last-update: " + aSnippetsMap.get("snippets-last-update") +
- ", cached-version: " + aSnippetsMap.get("snippets-cached-version") +
- " }");
- // Don't try to update.
- aSnippetsMap.set("snippets-last-update", Date.now());
- aSnippetsMap.set("snippets-cached-version", arg.snippetsVersion);
- // Clear snippets.
- aSnippetsMap.delete("snippets");
- aSnippetsMap.set("snippets", arg.snippet);
- resolve();
- });
- }, true, true);
- });
- });
-}
-
-
-function sendActivationEvent(tab) {
- // hack Social.lastEventReceived so we don't hit the "too many events" check.
- Social.lastEventReceived = 0;
- let doc = tab.linkedBrowser.contentDocument;
- // if our test has a frame, use it
- if (doc.defaultView.frames[0])
- doc = doc.defaultView.frames[0].document;
- let button = doc.getElementById("activationSnippet");
- BrowserTestUtils.synthesizeMouseAtCenter(button, {}, tab.linkedBrowser);
-}
-
-function activateProvider(tab, expectPanel, aCallback) {
- return new Promise(resolve => {
- if (expectPanel) {
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => {
- let panel = document.getElementById("servicesInstall-notification");
- panel.button.click();
- });
- }
- waitForProviderLoad().then(() => {
- checkSocialUI();
- resolve();
- });
- sendActivationEvent(tab);
- });
-}
-
-function waitForProviderLoad(cb) {
- return Promise.all([
- promiseObserverNotified("social:provider-enabled"),
- ensureFrameLoaded(gBrowser, "https://example.com/browser/browser/base/content/test/social/social_postActivation.html"),
- ]);
-}
diff --git a/browser/base/content/test/social/browser_addons.js b/browser/base/content/test/social/browser_addons.js
deleted file mode 100644
index 5a75d1d67..000000000
--- a/browser/base/content/test/social/browser_addons.js
+++ /dev/null
@@ -1,217 +0,0 @@
-var AddonManager = Cu.import("resource://gre/modules/AddonManager.jsm", {}).AddonManager;
-var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
-var manifest = {
- name: "provider 1",
- origin: "https://example.com",
- shareURL: "https://example.com/browser/browser/base/content/test/social/social_share.html",
- iconURL: "https://example.com/browser/browser/base/content/test/general/moz.png"
-};
-var manifest2 = { // used for testing install
- name: "provider 2",
- origin: "https://test1.example.com",
- shareURL: "https://test1.example.com/browser/browser/base/content/test/social/social_share.html",
- iconURL: "https://test1.example.com/browser/browser/base/content/test/general/moz.png",
- version: "1.0"
-};
-var manifestUpgrade = { // used for testing install
- name: "provider 3",
- origin: "https://test2.example.com",
- shareURL: "https://test2.example.com/browser/browser/base/content/test/social/social_share.html",
- iconURL: "https://test2.example.com/browser/browser/base/content/test/general/moz.png",
- version: "1.0"
-};
-
-function test() {
- waitForExplicitFinish();
- PopupNotifications.panel.setAttribute("animate", "false");
- registerCleanupFunction(function () {
- PopupNotifications.panel.removeAttribute("animate");
- });
-
- let prefname = getManifestPrefname(manifest);
- // ensure that manifest2 is NOT showing as builtin
- is(SocialService.getOriginActivationType(manifest.origin), "foreign", "manifest is foreign");
- is(SocialService.getOriginActivationType(manifest2.origin), "foreign", "manifest2 is foreign");
-
- Services.prefs.setBoolPref("social.remote-install.enabled", true);
- runSocialTests(tests, undefined, undefined, function () {
- Services.prefs.clearUserPref("social.remote-install.enabled");
- ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs");
- // just in case the tests failed, clear these here as well
- Services.prefs.clearUserPref("social.directories");
- finish();
- });
-}
-
-function installListener(next, aManifest) {
- let expectEvent = "onInstalling";
- let prefname = getManifestPrefname(aManifest);
- // wait for the actual removal to call next
- SocialService.registerProviderListener(function providerListener(topic, origin, providers) {
- if (topic == "provider-disabled") {
- SocialService.unregisterProviderListener(providerListener);
- is(origin, aManifest.origin, "provider disabled");
- executeSoon(next);
- }
- });
-
- return {
- onInstalling: function(addon) {
- is(expectEvent, "onInstalling", "install started");
- is(addon.manifest.origin, aManifest.origin, "provider about to be installed");
- ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs");
- expectEvent = "onInstalled";
- },
- onInstalled: function(addon) {
- is(addon.manifest.origin, aManifest.origin, "provider installed");
- ok(addon.installDate.getTime() > 0, "addon has installDate");
- ok(addon.updateDate.getTime() > 0, "addon has updateDate");
- ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs");
- expectEvent = "onUninstalling";
- },
- onUninstalling: function(addon) {
- is(expectEvent, "onUninstalling", "uninstall started");
- is(addon.manifest.origin, aManifest.origin, "provider about to be uninstalled");
- ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs");
- expectEvent = "onUninstalled";
- },
- onUninstalled: function(addon) {
- is(expectEvent, "onUninstalled", "provider has been uninstalled");
- is(addon.manifest.origin, aManifest.origin, "provider uninstalled");
- ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs");
- AddonManager.removeAddonListener(this);
- }
- };
-}
-
-var tests = {
- testHTTPInstallFailure: function(next) {
- let installFrom = "http://example.com";
- is(SocialService.getOriginActivationType(installFrom), "foreign", "testing foriegn install");
- let data = {
- origin: installFrom,
- url: installFrom+"/activate",
- manifest: manifest,
- window: window
- }
- Social.installProvider(data, function(addonManifest) {
- ok(!addonManifest, "unable to install provider over http");
- next();
- });
- },
- testAddonEnableToggle: function(next) {
- let expectEvent;
- let prefname = getManifestPrefname(manifest);
- let listener = {
- onEnabled: function(addon) {
- is(expectEvent, "onEnabled", "provider onEnabled");
- ok(!addon.userDisabled, "provider enabled");
- executeSoon(function() {
- expectEvent = "onDisabling";
- addon.userDisabled = true;
- });
- },
- onEnabling: function(addon) {
- is(expectEvent, "onEnabling", "provider onEnabling");
- expectEvent = "onEnabled";
- },
- onDisabled: function(addon) {
- is(expectEvent, "onDisabled", "provider onDisabled");
- ok(addon.userDisabled, "provider disabled");
- AddonManager.removeAddonListener(listener);
- // clear the provider user-level pref
- Services.prefs.clearUserPref(prefname);
- executeSoon(next);
- },
- onDisabling: function(addon) {
- is(expectEvent, "onDisabling", "provider onDisabling");
- expectEvent = "onDisabled";
- }
- };
- AddonManager.addAddonListener(listener);
-
- // we're only testing enable disable, so we quickly set the user-level pref
- // for this provider and test enable/disable toggling
- setManifestPref(prefname, manifest);
- ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs");
- AddonManager.getAddonsByTypes(["service"], function(addons) {
- for (let addon of addons) {
- if (addon.userDisabled) {
- expectEvent = "onEnabling";
- addon.userDisabled = false;
- // only test with one addon
- return;
- }
- }
- ok(false, "no addons toggled");
- next();
- });
- },
- testProviderEnableToggle: function(next) {
- // enable and disabel a provider from the SocialService interface, check
- // that the addon manager is updated
-
- let expectEvent;
- let prefname = getManifestPrefname(manifest);
-
- let listener = {
- onEnabled: function(addon) {
- is(expectEvent, "onEnabled", "provider onEnabled");
- is(addon.manifest.origin, manifest.origin, "provider enabled");
- ok(!addon.userDisabled, "provider !userDisabled");
- },
- onEnabling: function(addon) {
- is(expectEvent, "onEnabling", "provider onEnabling");
- is(addon.manifest.origin, manifest.origin, "provider about to be enabled");
- expectEvent = "onEnabled";
- },
- onDisabled: function(addon) {
- is(expectEvent, "onDisabled", "provider onDisabled");
- is(addon.manifest.origin, manifest.origin, "provider disabled");
- ok(addon.userDisabled, "provider userDisabled");
- },
- onDisabling: function(addon) {
- is(expectEvent, "onDisabling", "provider onDisabling");
- is(addon.manifest.origin, manifest.origin, "provider about to be disabled");
- expectEvent = "onDisabled";
- }
- };
- AddonManager.addAddonListener(listener);
-
- expectEvent = "onEnabling";
- setManifestPref(prefname, manifest);
- SocialService.enableProvider(manifest.origin, function(provider) {
- expectEvent = "onDisabling";
- SocialService.disableProvider(provider.origin, function() {
- AddonManager.removeAddonListener(listener);
- Services.prefs.clearUserPref(prefname);
- next();
- });
- });
- },
- testDirectoryInstall: function(next) {
- AddonManager.addAddonListener(installListener(next, manifest2));
-
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => {
- let panel = document.getElementById("servicesInstall-notification");
- info("servicesInstall-notification panel opened");
- panel.button.click();
- });
-
- Services.prefs.setCharPref("social.directories", manifest2.origin);
- is(SocialService.getOriginActivationType(manifest2.origin), "directory", "testing directory install");
- let data = {
- origin: manifest2.origin,
- url: manifest2.origin + "/directory",
- manifest: manifest2,
- window: window
- }
- Social.installProvider(data, function(addonManifest) {
- Services.prefs.clearUserPref("social.directories");
- SocialService.enableProvider(addonManifest.origin, function(provider) {
- Social.uninstallProvider(addonManifest.origin);
- });
- });
- }
-}
diff --git a/browser/base/content/test/social/browser_blocklist.js b/browser/base/content/test/social/browser_blocklist.js
deleted file mode 100644
index b67d5efb3..000000000
--- a/browser/base/content/test/social/browser_blocklist.js
+++ /dev/null
@@ -1,211 +0,0 @@
-/* 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/. */
-
-// a place for miscellaneous social tests
-
-var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
-const URI_EXTENSION_BLOCKLIST_DIALOG = "chrome://mozapps/content/extensions/blocklist.xul";
-var blocklistURL = "http://example.com/browser/browser/base/content/test/social/blocklist.xml";
-
-var manifest = { // normal provider
- name: "provider ok",
- origin: "https://example.com",
- shareURL: "https://example.com/browser/browser/base/content/test/social/social_share.html",
- iconURL: "https://example.com/browser/browser/base/content/test/general/moz.png"
-};
-var manifest_bad = { // normal provider
- name: "provider blocked",
- origin: "https://test1.example.com",
- shareURL: "https://test1.example.com/browser/browser/base/content/test/social/social_share.html",
- iconURL: "https://test1.example.com/browser/browser/base/content/test/general/moz.png"
-};
-
-// blocklist testing
-function updateBlocklist() {
- var blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
- .getService(Ci.nsITimerCallback);
- let promise = promiseObserverNotified("blocklist-updated");
- blocklistNotifier.notify(null);
- return promise;
-}
-
-var _originalTestBlocklistURL = null;
-function setAndUpdateBlocklist(aURL) {
- if (!_originalTestBlocklistURL)
- _originalTestBlocklistURL = Services.prefs.getCharPref("extensions.blocklist.url");
- Services.prefs.setCharPref("extensions.blocklist.url", aURL);
- return updateBlocklist();
-}
-
-function resetBlocklist() {
- // XXX - this has "forked" from the head.js helpers in our parent directory :(
- // But let's reuse their blockNoPlugins.xml. Later, we should arrange to
- // use their head.js helpers directly
- let noBlockedURL = "http://example.com/browser/browser/base/content/test/plugins/blockNoPlugins.xml";
- return new Promise(resolve => {
- setAndUpdateBlocklist(noBlockedURL).then(() => {
- Services.prefs.setCharPref("extensions.blocklist.url", _originalTestBlocklistURL);
- resolve();
- });
- });
-}
-
-function test() {
- waitForExplicitFinish();
- // turn on logging for nsBlocklistService.js
- Services.prefs.setBoolPref("extensions.logging.enabled", true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("extensions.logging.enabled");
- });
-
- runSocialTests(tests, undefined, undefined, function () {
- resetBlocklist().then(finish); // restore to original pref
- });
-}
-
-var tests = {
- testSimpleBlocklist: function(next) {
- // this really just tests adding and clearing our blocklist for later tests
- setAndUpdateBlocklist(blocklistURL).then(() => {
- ok(Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest_bad)), "blocking 'blocked'");
- ok(!Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest)), "not blocking 'good'");
- resetBlocklist().then(() => {
- ok(!Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest_bad)), "blocklist cleared");
- next();
- });
- });
- },
- testAddingNonBlockedProvider: function(next) {
- function finishTest(isgood) {
- ok(isgood, "adding non-blocked provider ok");
- Services.prefs.clearUserPref("social.manifest.good");
- resetBlocklist().then(next);
- }
- setManifestPref("social.manifest.good", manifest);
- setAndUpdateBlocklist(blocklistURL).then(() => {
- try {
- SocialService.addProvider(manifest, function(provider) {
- try {
- SocialService.disableProvider(provider.origin, function() {
- ok(true, "added and removed provider");
- finishTest(true);
- });
- } catch (e) {
- ok(false, "SocialService.disableProvider threw exception: " + e);
- finishTest(false);
- }
- });
- } catch (e) {
- ok(false, "SocialService.addProvider threw exception: " + e);
- finishTest(false);
- }
- });
- },
- testAddingBlockedProvider: function(next) {
- function finishTest(good) {
- ok(good, "Unable to add blocklisted provider");
- Services.prefs.clearUserPref("social.manifest.blocked");
- resetBlocklist().then(next);
- }
- setManifestPref("social.manifest.blocked", manifest_bad);
- setAndUpdateBlocklist(blocklistURL).then(() => {
- try {
- SocialService.addProvider(manifest_bad, function(provider) {
- SocialService.disableProvider(provider.origin, function() {
- ok(false, "SocialService.addProvider should throw blocklist exception");
- finishTest(false);
- });
- });
- } catch (e) {
- ok(true, "SocialService.addProvider should throw blocklist exception: " + e);
- finishTest(true);
- }
- });
- },
- testInstallingBlockedProvider: function(next) {
- function finishTest(good) {
- ok(good, "Unable to install blocklisted provider");
- resetBlocklist().then(next);
- }
- let activationURL = manifest_bad.origin + "/browser/browser/base/content/test/social/social_activate.html"
- setAndUpdateBlocklist(blocklistURL).then(() => {
- try {
- // expecting an exception when attempting to install a hard blocked
- // provider
- let data = {
- origin: manifest_bad.origin,
- url: activationURL,
- manifest: manifest_bad,
- window: window
- }
- Social.installProvider(data, function(addonManifest) {
- finishTest(false);
- });
- } catch (e) {
- finishTest(true);
- }
- });
- },
- testBlockingExistingProvider: function(next) {
- let listener = {
- _window: null,
- onOpenWindow: function(aXULWindow) {
- Services.wm.removeListener(this);
- this._window = aXULWindow;
- let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-
- domwindow.addEventListener("load", function _load() {
- domwindow.removeEventListener("load", _load, false);
-
- domwindow.addEventListener("unload", function _unload() {
- domwindow.removeEventListener("unload", _unload, false);
- info("blocklist window was closed");
- Services.wm.removeListener(listener);
- next();
- }, false);
-
- is(domwindow.document.location.href, URI_EXTENSION_BLOCKLIST_DIALOG, "dialog opened and focused");
- // wait until after load to cancel so the dialog has initalized. we
- // don't want to accept here since that restarts the browser.
- executeSoon(() => {
- let cancelButton = domwindow.document.documentElement.getButton("cancel");
- info("***** hit the cancel button\n");
- cancelButton.doCommand();
- });
- }, false);
- },
- onCloseWindow: function(aXULWindow) { },
- onWindowTitleChange: function(aXULWindow, aNewTitle) { }
- };
-
- Services.wm.addListener(listener);
-
- setManifestPref("social.manifest.blocked", manifest_bad);
- try {
- SocialService.addProvider(manifest_bad, function(provider) {
- // the act of blocking should cause a 'provider-disabled' notification
- // from SocialService.
- SocialService.registerProviderListener(function providerListener(topic, origin, providers) {
- if (topic != "provider-disabled")
- return;
- SocialService.unregisterProviderListener(providerListener);
- is(origin, provider.origin, "provider disabled");
- SocialService.getProvider(provider.origin, function(p) {
- ok(p == null, "blocklisted provider disabled");
- Services.prefs.clearUserPref("social.manifest.blocked");
- resetBlocklist();
- });
- });
- // no callback - the act of updating should cause the listener above
- // to fire.
- setAndUpdateBlocklist(blocklistURL);
- });
- } catch (e) {
- ok(false, "unable to add provider " + e);
- next();
- }
- }
-}
diff --git a/browser/base/content/test/social/browser_share.js b/browser/base/content/test/social/browser_share.js
deleted file mode 100644
index 19dca519b..000000000
--- a/browser/base/content/test/social/browser_share.js
+++ /dev/null
@@ -1,396 +0,0 @@
-
-var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
-var baseURL = "https://example.com/browser/browser/base/content/test/social/";
-
-var manifest = { // normal provider
- name: "provider 1",
- origin: "https://example.com",
- iconURL: "https://example.com/browser/browser/base/content/test/general/moz.png",
- shareURL: "https://example.com/browser/browser/base/content/test/social/share.html"
-};
-var activationPage = "https://example.com/browser/browser/base/content/test/social/share_activate.html";
-
-function sendActivationEvent(subframe) {
- // hack Social.lastEventReceived so we don't hit the "too many events" check.
- Social.lastEventReceived = 0;
- let doc = subframe.contentDocument;
- // if our test has a frame, use it
- let button = doc.getElementById("activation");
- ok(!!button, "got the activation button");
- EventUtils.synthesizeMouseAtCenter(button, {}, doc.defaultView);
-}
-
-function test() {
- waitForExplicitFinish();
- Services.prefs.setCharPref("social.shareDirectory", activationPage);
-
- let frameScript = "data:,(" + function frame_script() {
- addEventListener("OpenGraphData", function (aEvent) {
- sendAsyncMessage("sharedata", aEvent.detail);
- }, true, true);
- /* bug 1042991, ensure history is available by calling history.back on close */
- addMessageListener("closeself", function(e) {
- content.history.back();
- content.close();
- }, true);
- /* if text is entered into field, onbeforeunload will cause a modal dialog
- unless dialogs have been disabled for the iframe. */
- content.onbeforeunload = function(e) {
- return 'FAIL.';
- };
- }.toString() + ")();";
- let mm = getGroupMessageManager("social");
- mm.loadFrameScript(frameScript, true);
-
- // Animation on the panel can cause intermittent failures such as bug 1115131.
- SocialShare.panel.setAttribute("animate", "false");
- registerCleanupFunction(function () {
- SocialShare.panel.removeAttribute("animate");
- mm.removeDelayedFrameScript(frameScript);
- Services.prefs.clearUserPref("social.directories");
- Services.prefs.clearUserPref("social.shareDirectory");
- Services.prefs.clearUserPref("social.share.activationPanelEnabled");
- });
- runSocialTests(tests, undefined, function(next) {
- let shareButton = SocialShare.shareButton;
- if (shareButton) {
- CustomizableUI.removeWidgetFromArea("social-share-button", CustomizableUI.AREA_NAVBAR)
- shareButton.remove();
- }
- next();
- });
-}
-
-var corpus = [
- {
- url: baseURL+"opengraph/opengraph.html",
- options: {
- // og:title
- title: ">This is my title<",
- // og:description
- description: "A test corpus file for open graph tags we care about",
- // medium: this.getPageMedium(),
- // source: this.getSourceURL(),
- // og:url
- url: "https://www.mozilla.org/",
- // shortUrl: this.getShortURL(),
- // og:image
- previews:["https://www.mozilla.org/favicon.png"],
- // og:site_name
- siteName: ">My simple test page<"
- }
- },
- {
- // tests that og:url doesn't override the page url if it is bad
- url: baseURL+"opengraph/og_invalid_url.html",
- options: {
- description: "A test corpus file for open graph tags passing a bad url",
- url: baseURL+"opengraph/og_invalid_url.html",
- previews: [],
- siteName: "Evil chrome delivering website"
- }
- },
- {
- url: baseURL+"opengraph/shorturl_link.html",
- options: {
- previews: ["http://example.com/1234/56789.jpg"],
- url: "http://www.example.com/photos/56789/",
- shortUrl: "http://imshort/p/abcde"
- }
- },
- {
- url: baseURL+"opengraph/shorturl_linkrel.html",
- options: {
- previews: ["http://example.com/1234/56789.jpg"],
- url: "http://www.example.com/photos/56789/",
- shortUrl: "http://imshort/p/abcde"
- }
- },
- {
- url: baseURL+"opengraph/shortlink_linkrel.html",
- options: {
- previews: ["http://example.com/1234/56789.jpg"],
- url: "http://www.example.com/photos/56789/",
- shortUrl: "http://imshort/p/abcde"
- }
- }
-];
-
-function hasoptions(testOptions, options) {
- for (let option in testOptions) {
- let data = testOptions[option];
- info("data: "+JSON.stringify(data));
- let message_data = options[option];
- info("message_data: "+JSON.stringify(message_data));
- if (Array.isArray(data)) {
- // the message may have more array elements than we are testing for, this
- // is ok since some of those are hard to test. So we just test that
- // anything in our test data IS in the message.
- ok(Array.every(data, function(item) { return message_data.indexOf(item) >= 0 }), "option "+option);
- } else {
- is(message_data, data, "option "+option);
- }
- }
-}
-
-var tests = {
- testShareDisabledOnActivation: function(next) {
- // starting on about:blank page, share should be visible but disabled when
- // adding provider
- is(gBrowser.currentURI.spec, "about:blank");
-
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
-
- SocialService.addProvider(manifest, function(provider) {
- is(SocialUI.enabled, true, "SocialUI is enabled");
- checkSocialUI();
- // share should not be enabled since we only have about:blank page
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- is(shareButton.getAttribute("disabled"), "true", "share button attribute is disabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
- SocialService.disableProvider(manifest.origin, next);
- });
- },
- testShareEnabledOnActivation: function(next) {
- // starting from *some* page, share should be visible and enabled when
- // activating provider
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
-
- let testData = corpus[0];
- BrowserTestUtils.openNewForegroundTab(gBrowser, testData.url).then(tab => {
- SocialService.addProvider(manifest, function(provider) {
- is(SocialUI.enabled, true, "SocialUI is enabled");
- checkSocialUI();
- // share should not be enabled since we only have about:blank page
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- ok(!shareButton.hasAttribute("disabled"), "share button is enabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
- BrowserTestUtils.removeTab(tab).then(next);
- });
- });
- },
- testSharePage: function(next) {
- let testTab;
- let testIndex = 0;
- let testData = corpus[testIndex++];
-
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
-
- let mm = getGroupMessageManager("social");
- mm.addMessageListener("sharedata", function handler(msg) {
- BrowserTestUtils.removeTab(testTab).then(() => {
- hasoptions(testData.options, JSON.parse(msg.data));
- testData = corpus[testIndex++];
- BrowserTestUtils.waitForCondition(() => { return SocialShare.currentShare == null; }, "share panel closed").then(() => {
- if (testData) {
- runOneTest();
- } else {
- mm.removeMessageListener("sharedata", handler);
- SocialService.disableProvider(manifest.origin, next);
- }
- });
- SocialShare.iframe.messageManager.sendAsyncMessage("closeself", {});
- });
- });
-
- function runOneTest() {
- BrowserTestUtils.openNewForegroundTab(gBrowser, testData.url).then(tab => {
- testTab = tab;
-
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- ok(!shareButton.hasAttribute("disabled"), "share button is enabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
-
- SocialShare.sharePage(manifest.origin);
- });
- }
- executeSoon(runOneTest);
- },
- testShareMicroformats: function(next) {
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
-
- SocialService.addProvider(manifest, function(provider) {
- let target, testTab;
-
- let expecting = JSON.stringify({
- "url": "https://example.com/browser/browser/base/content/test/social/microformats.html",
- "title": "Raspberry Pi Page",
- "previews": ["https://example.com/someimage.jpg"],
- "microformats": {
- "items": [{
- "type": ["h-product"],
- "properties": {
- "name": ["Raspberry Pi"],
- "photo": ["https://example.com/someimage.jpg"],
- "description": [{
- "value": "The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It's a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.",
- "html": "The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It's a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming."
- }
- ],
- "url": ["https://example.com/"],
- "price": ["29.95"],
- "review": [{
- "value": "4.5 out of 5",
- "type": ["h-review"],
- "properties": {
- "rating": ["4.5"]
- }
- }
- ],
- "category": ["Computer", "Education"]
- }
- }
- ],
- "rels": {
- "tag": ["https://example.com/wiki/computer", "https://example.com/wiki/education"]
- },
- "rel-urls": {
- "https://example.com/wiki/computer": {
- "text": "Computer",
- "rels": ["tag"]
- },
- "https://example.com/wiki/education": {
- "text": "Education",
- "rels": ["tag"]
- }
- }
- }
- });
-
- let mm = getGroupMessageManager("social");
- mm.addMessageListener("sharedata", function handler(msg) {
- is(msg.data, expecting, "microformats data ok");
- BrowserTestUtils.waitForCondition(() => { return SocialShare.currentShare == null; },
- "share panel closed").then(() => {
- mm.removeMessageListener("sharedata", handler);
- BrowserTestUtils.removeTab(testTab).then(() => {
- SocialService.disableProvider(manifest.origin, next);
- });
- });
- SocialShare.iframe.messageManager.sendAsyncMessage("closeself", {});
- });
-
- let url = "https://example.com/browser/browser/base/content/test/social/microformats.html"
- BrowserTestUtils.openNewForegroundTab(gBrowser, url).then(tab => {
- testTab = tab;
-
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- ok(!shareButton.hasAttribute("disabled"), "share button is enabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
-
- let doc = tab.linkedBrowser.contentDocument;
- target = doc.getElementById("simple-hcard");
- SocialShare.sharePage(manifest.origin, null, target);
- });
- });
- },
- testSharePanelActivation: function(next) {
- let testTab;
- // cleared in the cleanup function
- Services.prefs.setCharPref("social.directories", "https://example.com");
- Services.prefs.setBoolPref("social.share.activationPanelEnabled", true);
- // make the iframe so we can wait on the load
- SocialShare._createFrame();
- let iframe = SocialShare.iframe;
-
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
-
- ensureFrameLoaded(iframe).then(() => {
- let subframe = iframe.contentDocument.getElementById("activation-frame");
- ensureFrameLoaded(subframe, activationPage).then(() => {
- is(subframe.contentDocument.location.href, activationPage, "activation page loaded");
- promiseObserverNotified("social:provider-enabled").then(() => {
- let mm = getGroupMessageManager("social");
- mm.addMessageListener("sharedata", function handler(msg) {
- ok(true, "share completed");
-
- BrowserTestUtils.waitForCondition(() => { return SocialShare.currentShare == null; },
- "share panel closed").then(() => {
- BrowserTestUtils.removeTab(testTab).then(() => {
- mm.removeMessageListener("sharedata", handler);
- SocialService.uninstallProvider(manifest.origin, next);
- });
- });
- SocialShare.iframe.messageManager.sendAsyncMessage("closeself", {});
- });
- });
- sendActivationEvent(subframe);
- });
- });
- BrowserTestUtils.openNewForegroundTab(gBrowser, activationPage).then(tab => {
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- ok(!shareButton.hasAttribute("disabled"), "share button is enabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
-
- testTab = tab;
- SocialShare.sharePage();
- });
- },
- testSharePanelDialog: function(next) {
- let testTab;
- // initialize the button into the navbar
- CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR);
- // ensure correct state
- SocialUI.onCustomizeEnd(window);
- SocialShare._createFrame();
-
- SocialService.addProvider(manifest, () => {
- BrowserTestUtils.openNewForegroundTab(gBrowser, activationPage).then(tab => {
- ensureFrameLoaded(SocialShare.iframe).then(() => {
- // send keys to the input field. An unexpected failure will happen
- // if the onbeforeunload handler is fired.
- EventUtils.sendKey("f");
- EventUtils.sendKey("a");
- EventUtils.sendKey("i");
- EventUtils.sendKey("l");
-
- SocialShare.panel.addEventListener("popuphidden", function hidden(evt) {
- SocialShare.panel.removeEventListener("popuphidden", hidden);
- let topwin = Services.wm.getMostRecentWindow(null);
- is(topwin, window, "no dialog is open");
-
- BrowserTestUtils.removeTab(testTab).then(() => {
- SocialService.disableProvider(manifest.origin, next);
- });
- });
- SocialShare.iframe.messageManager.sendAsyncMessage("closeself", {});
- });
-
- let shareButton = SocialShare.shareButton;
- // verify the attribute for proper css
- ok(!shareButton.hasAttribute("disabled"), "share button is enabled");
- // button should be visible
- is(shareButton.hidden, false, "share button is visible");
-
- testTab = tab;
- SocialShare.sharePage();
- });
- });
- }
-}
diff --git a/browser/base/content/test/social/browser_social_activation.js b/browser/base/content/test/social/browser_social_activation.js
deleted file mode 100644
index 2af0d8021..000000000
--- a/browser/base/content/test/social/browser_social_activation.js
+++ /dev/null
@@ -1,270 +0,0 @@
-/* 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/. */
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: Assert is null");
-
-
-var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
-var tabsToRemove = [];
-
-function removeProvider(provider) {
- return new Promise(resolve => {
- // a full install sets the manifest into a pref, addProvider alone doesn't,
- // make sure we uninstall if the manifest was added.
- if (provider.manifest) {
- SocialService.uninstallProvider(provider.origin, resolve);
- } else {
- SocialService.disableProvider(provider.origin, resolve);
- }
- });
-}
-
-function postTestCleanup(callback) {
- Task.spawn(function* () {
- // any tabs opened by the test.
- for (let tab of tabsToRemove) {
- yield BrowserTestUtils.removeTab(tab);
- }
- tabsToRemove = [];
- // all the providers may have been added.
- while (Social.providers.length > 0) {
- yield removeProvider(Social.providers[0]);
- }
- }).then(callback);
-}
-
-function newTab(url) {
- return new Promise(resolve => {
- BrowserTestUtils.openNewForegroundTab(gBrowser, url).then(tab => {
- tabsToRemove.push(tab);
- resolve(tab);
- });
- });
-}
-
-function sendActivationEvent(tab, callback, nullManifest) {
- // hack Social.lastEventReceived so we don't hit the "too many events" check.
- Social.lastEventReceived = 0;
- BrowserTestUtils.synthesizeMouseAtCenter("#activation", {}, tab.linkedBrowser);
- executeSoon(callback);
-}
-
-function activateProvider(domain, callback, nullManifest) {
- let activationURL = domain+"/browser/browser/base/content/test/social/social_activate_basic.html"
- newTab(activationURL).then(tab => {
- sendActivationEvent(tab, callback, nullManifest);
- });
-}
-
-function activateIFrameProvider(domain, callback) {
- let activationURL = domain+"/browser/browser/base/content/test/social/social_activate_iframe.html"
- newTab(activationURL).then(tab => {
- sendActivationEvent(tab, callback, false);
- });
-}
-
-function waitForProviderLoad(origin) {
- return Promise.all([
- ensureFrameLoaded(gBrowser, origin + "/browser/browser/base/content/test/social/social_postActivation.html"),
- ]);
-}
-
-function getAddonItemInList(aId, aList) {
- var item = aList.firstChild;
- while (item) {
- if ("mAddon" in item && item.mAddon.id == aId) {
- aList.ensureElementIsVisible(item);
- return item;
- }
- item = item.nextSibling;
- }
- return null;
-}
-
-function clickAddonRemoveButton(tab, aCallback) {
- AddonManager.getAddonsByTypes(["service"], function(aAddons) {
- let addon = aAddons[0];
-
- let doc = tab.linkedBrowser.contentDocument;
- let list = doc.getElementById("addon-list");
-
- let item = getAddonItemInList(addon.id, list);
- let button = item._removeBtn;
- isnot(button, null, "Should have a remove button");
- ok(!button.disabled, "Button should not be disabled");
-
- // uninstall happens after about:addons tab is closed, so we wait on
- // disabled
- promiseObserverNotified("social:provider-disabled").then(() => {
- is(item.getAttribute("pending"), "uninstall", "Add-on should be uninstalling");
- executeSoon(function() { aCallback(addon); });
- });
-
- BrowserTestUtils.synthesizeMouseAtCenter(button, {}, tab.linkedBrowser);
- });
-}
-
-function activateOneProvider(manifest, finishActivation, aCallback) {
- info("activating provider "+manifest.name);
- let panel = document.getElementById("servicesInstall-notification");
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => {
- ok(!panel.hidden, "servicesInstall-notification panel opened");
- if (finishActivation)
- panel.button.click();
- else
- panel.closebutton.click();
- });
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden").then(() => {
- ok(panel.hidden, "servicesInstall-notification panel hidden");
- if (!finishActivation) {
- ok(panel.hidden, "activation panel is not showing");
- executeSoon(aCallback);
- } else {
- waitForProviderLoad(manifest.origin).then(() => {
- checkSocialUI();
- executeSoon(aCallback);
- });
- }
- });
-
- // the test will continue as the popup events fire...
- activateProvider(manifest.origin, function() {
- info("waiting on activation panel to open/close...");
- });
-}
-
-var gTestDomains = ["https://example.com", "https://test1.example.com", "https://test2.example.com"];
-var gProviders = [
- {
- name: "provider 1",
- origin: "https://example.com",
- shareURL: "https://example.com/browser/browser/base/content/test/social/social_share.html?provider1",
- iconURL: "chrome://branding/content/icon48.png"
- },
- {
- name: "provider 2",
- origin: "https://test1.example.com",
- shareURL: "https://test1.example.com/browser/browser/base/content/test/social/social_share.html?provider2",
- iconURL: "chrome://branding/content/icon64.png"
- },
- {
- name: "provider 3",
- origin: "https://test2.example.com",
- shareURL: "https://test2.example.com/browser/browser/base/content/test/social/social_share.html?provider2",
- iconURL: "chrome://branding/content/about-logo.png"
- }
-];
-
-
-function test() {
- PopupNotifications.panel.setAttribute("animate", "false");
- registerCleanupFunction(function () {
- PopupNotifications.panel.removeAttribute("animate");
- });
- waitForExplicitFinish();
- SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", 1]]}, () => {
- runSocialTests(tests, undefined, postTestCleanup);
- });
-}
-
-var tests = {
- testActivationWrongOrigin: function(next) {
- // At this stage none of our providers exist, so we expect failure.
- Services.prefs.setBoolPref("social.remote-install.enabled", false);
- activateProvider(gTestDomains[0], function() {
- is(SocialUI.enabled, false, "SocialUI is not enabled");
- let panel = document.getElementById("servicesInstall-notification");
- ok(panel.hidden, "activation panel still hidden");
- checkSocialUI();
- Services.prefs.clearUserPref("social.remote-install.enabled");
- next();
- });
- },
-
- testIFrameActivation: function(next) {
- activateIFrameProvider(gTestDomains[0], function() {
- is(SocialUI.enabled, false, "SocialUI is not enabled");
- let panel = document.getElementById("servicesInstall-notification");
- ok(panel.hidden, "activation panel still hidden");
- checkSocialUI();
- next();
- });
- },
-
- testActivationFirstProvider: function(next) {
- // first up we add a manifest entry for a single provider.
- activateOneProvider(gProviders[0], false, function() {
- // we deactivated leaving no providers left, so Social is disabled.
- checkSocialUI();
- next();
- });
- },
-
- testActivationMultipleProvider: function(next) {
- // The trick with this test is to make sure that Social.providers[1] is
- // the current provider when doing the undo - this makes sure that the
- // Social code doesn't fallback to Social.providers[0], which it will
- // do in some cases (but those cases do not include what this test does)
- // first enable the 2 providers
- SocialService.addProvider(gProviders[0], function() {
- SocialService.addProvider(gProviders[1], function() {
- checkSocialUI();
- // activate the last provider.
- activateOneProvider(gProviders[2], false, function() {
- // we deactivated - the first provider should be enabled.
- checkSocialUI();
- next();
- });
- });
- });
- },
-
- testAddonManagerDoubleInstall: function(next) {
- // Create a new tab and load about:addons
- let addonsTab = gBrowser.addTab();
- gBrowser.selectedTab = addonsTab;
- BrowserOpenAddonsMgr('addons://list/service');
- gBrowser.selectedBrowser.addEventListener("load", function tabLoad() {
- gBrowser.selectedBrowser.removeEventListener("load", tabLoad, true);
- is(addonsTab.linkedBrowser.currentURI.spec, "about:addons", "about:addons should load into blank tab.");
-
- activateOneProvider(gProviders[0], true, function() {
- info("first activation completed");
- is(gBrowser.contentDocument.location.href, gProviders[0].origin + "/browser/browser/base/content/test/social/social_postActivation.html", "postActivationURL loaded");
- BrowserTestUtils.removeTab(gBrowser.selectedTab).then(() => {
- is(gBrowser.contentDocument.location.href, gProviders[0].origin + "/browser/browser/base/content/test/social/social_activate_basic.html", "activation page selected");
- BrowserTestUtils.removeTab(gBrowser.selectedTab).then(() => {
- tabsToRemove.pop();
- // uninstall the provider
- clickAddonRemoveButton(addonsTab, function(addon) {
- checkSocialUI();
- activateOneProvider(gProviders[0], true, function() {
- info("second activation completed");
- is(gBrowser.contentDocument.location.href, gProviders[0].origin + "/browser/browser/base/content/test/social/social_postActivation.html", "postActivationURL loaded");
- BrowserTestUtils.removeTab(gBrowser.selectedTab).then(() => {
-
- // after closing the addons tab, verify provider is still installed
- AddonManager.getAddonsByTypes(["service"], function(aAddons) {
- is(aAddons.length, 1, "there can be only one");
-
- let doc = addonsTab.linkedBrowser.contentDocument;
- let list = doc.getElementById("addon-list");
- is(list.childNodes.length, 1, "only one addon is displayed");
-
- BrowserTestUtils.removeTab(addonsTab).then(next);
- });
- });
- });
- });
- });
- });
- });
- }, true);
- }
-}
diff --git a/browser/base/content/test/social/head.js b/browser/base/content/test/social/head.js
deleted file mode 100644
index ea175c97a..000000000
--- a/browser/base/content/test/social/head.js
+++ /dev/null
@@ -1,273 +0,0 @@
-/* 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/. */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-
-
-function promiseObserverNotified(aTopic) {
- return new Promise(resolve => {
- Services.obs.addObserver(function onNotification(aSubject, aTopic, aData) {
- dump("notification promised "+aTopic);
- Services.obs.removeObserver(onNotification, aTopic);
- TestUtils.executeSoon(() => resolve({subject: aSubject, data: aData}));
- }, aTopic, false);
- });
-}
-
-// Check that a specified (string) URL hasn't been "remembered" (ie, is not
-// in history, will not appear in about:newtab or auto-complete, etc.)
-function promiseSocialUrlNotRemembered(url) {
- return new Promise(resolve => {
- let uri = Services.io.newURI(url, null, null);
- PlacesUtils.asyncHistory.isURIVisited(uri, function(aURI, aIsVisited) {
- ok(!aIsVisited, "social URL " + url + " should not be in global history");
- resolve();
- });
- });
-}
-
-var gURLsNotRemembered = [];
-
-
-function checkProviderPrefsEmpty(isError) {
- let MANIFEST_PREFS = Services.prefs.getBranch("social.manifest.");
- let prefs = MANIFEST_PREFS.getChildList("", []);
- let c = 0;
- for (let pref of prefs) {
- if (MANIFEST_PREFS.prefHasUserValue(pref)) {
- info("provider [" + pref + "] manifest left installed from previous test");
- c++;
- }
- }
- is(c, 0, "all provider prefs uninstalled from previous test");
- is(Social.providers.length, 0, "all providers uninstalled from previous test " + Social.providers.length);
-}
-
-function defaultFinishChecks() {
- checkProviderPrefsEmpty(true);
- finish();
-}
-
-function runSocialTestWithProvider(manifest, callback, finishcallback) {
-
- let SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
-
- let manifests = Array.isArray(manifest) ? manifest : [manifest];
-
- // Check that none of the provider's content ends up in history.
- function* finishCleanUp() {
- for (let i = 0; i < manifests.length; i++) {
- let m = manifests[i];
- for (let what of ['iconURL', 'shareURL']) {
- if (m[what]) {
- yield promiseSocialUrlNotRemembered(m[what]);
- }
- }
- }
- for (let i = 0; i < gURLsNotRemembered.length; i++) {
- yield promiseSocialUrlNotRemembered(gURLsNotRemembered[i]);
- }
- gURLsNotRemembered = [];
- }
-
- info("runSocialTestWithProvider: " + manifests.toSource());
-
- let finishCount = 0;
- function finishIfDone(callFinish) {
- finishCount++;
- if (finishCount == manifests.length)
- Task.spawn(finishCleanUp).then(finishcallback || defaultFinishChecks);
- }
- function removeAddedProviders(cleanup) {
- manifests.forEach(function (m) {
- // If we're "cleaning up", don't call finish when done.
- let callback = cleanup ? function () {} : finishIfDone;
- // Similarly, if we're cleaning up, catch exceptions from removeProvider
- let removeProvider = SocialService.disableProvider.bind(SocialService);
- if (cleanup) {
- removeProvider = function (origin, cb) {
- try {
- SocialService.disableProvider(origin, cb);
- } catch (ex) {
- // Ignore "provider doesn't exist" errors.
- if (ex.message.indexOf("SocialService.disableProvider: no provider with origin") == 0)
- return;
- info("Failed to clean up provider " + origin + ": " + ex);
- }
- }
- }
- removeProvider(m.origin, callback);
- });
- }
- function finishSocialTest(cleanup) {
- removeAddedProviders(cleanup);
- }
-
- let providersAdded = 0;
-
- manifests.forEach(function (m) {
- SocialService.addProvider(m, function(provider) {
-
- providersAdded++;
- info("runSocialTestWithProvider: provider added");
-
- // we want to set the first specified provider as the UI's provider
- if (provider.origin == manifests[0].origin) {
- firstProvider = provider;
- }
-
- // If we've added all the providers we need, call the callback to start
- // the tests (and give it a callback it can call to finish them)
- if (providersAdded == manifests.length) {
- registerCleanupFunction(function () {
- finishSocialTest(true);
- });
- BrowserTestUtils.waitForCondition(() => provider.enabled,
- "providers added and enabled").then(() => {
- info("provider has been enabled");
- callback(finishSocialTest);
- });
- }
- });
- });
-}
-
-function runSocialTests(tests, cbPreTest, cbPostTest, cbFinish) {
- let testIter = (function*() {
- for (let name in tests) {
- if (tests.hasOwnProperty(name)) {
- yield [name, tests[name]];
- }
- }
- })();
- let providersAtStart = Social.providers.length;
- info("runSocialTests: start test run with " + providersAtStart + " providers");
- window.focus();
-
-
- if (cbPreTest === undefined) {
- cbPreTest = function(cb) { cb() };
- }
- if (cbPostTest === undefined) {
- cbPostTest = function(cb) { cb() };
- }
-
- function runNextTest() {
- let result = testIter.next();
- if (result.done) {
- // out of items:
- (cbFinish || defaultFinishChecks)();
- is(providersAtStart, Social.providers.length,
- "runSocialTests: finish test run with " + Social.providers.length + " providers");
- return;
- }
- let [name, func] = result.value;
- // We run on a timeout to help keep the debug messages sane.
- executeSoon(function() {
- function cleanupAndRunNextTest() {
- info("sub-test " + name + " complete");
- cbPostTest(runNextTest);
- }
- cbPreTest(function() {
- info("pre-test: starting with " + Social.providers.length + " providers");
- info("sub-test " + name + " starting");
- try {
- func.call(tests, cleanupAndRunNextTest);
- } catch (ex) {
- ok(false, "sub-test " + name + " failed: " + ex.toString() +"\n"+ex.stack);
- cleanupAndRunNextTest();
- }
- })
- });
- }
- runNextTest();
-}
-
-// A fairly large hammer which checks all aspects of the SocialUI for
-// internal consistency.
-function checkSocialUI(win) {
- let SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
- // if we have enabled providers, we should also have instances of those
- // providers
- if (SocialService.hasEnabledProviders) {
- ok(Social.providers.length > 0, "providers are enabled");
- } else {
- is(Social.providers.length, 0, "providers are not enabled");
- }
-}
-
-function setManifestPref(name, manifest) {
- let string = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- string.data = JSON.stringify(manifest);
- Services.prefs.setComplexValue(name, Ci.nsISupportsString, string);
-}
-
-function getManifestPrefname(aManifest) {
- // is same as the generated name in SocialServiceInternal.getManifestPrefname
- let originUri = Services.io.newURI(aManifest.origin, null, null);
- return "social.manifest." + originUri.hostPort.replace('.', '-');
-}
-
-function ensureFrameLoaded(frame, uri) {
- return new Promise(resolve => {
- if (frame.contentDocument && frame.contentDocument.readyState == "complete" &&
- (!uri || frame.contentDocument.location.href == uri)) {
- resolve();
- } else {
- frame.addEventListener("load", function handler() {
- if (uri && frame.contentDocument.location.href != uri)
- return;
- frame.removeEventListener("load", handler, true);
- resolve()
- }, true);
- }
- });
-}
-
-// Support for going on and offline.
-// (via browser/base/content/test/browser_bookmark_titles.js)
-var origProxyType = Services.prefs.getIntPref('network.proxy.type');
-
-function toggleOfflineStatus(goOffline) {
- // Bug 968887 fix. when going on/offline, wait for notification before continuing
- return new Promise(resolve => {
- if (!goOffline) {
- Services.prefs.setIntPref('network.proxy.type', origProxyType);
- }
- if (goOffline != Services.io.offline) {
- info("initial offline state " + Services.io.offline);
- let expect = !Services.io.offline;
- Services.obs.addObserver(function offlineChange(subject, topic, data) {
- Services.obs.removeObserver(offlineChange, "network:offline-status-changed");
- info("offline state changed to " + Services.io.offline);
- is(expect, Services.io.offline, "network:offline-status-changed successful toggle");
- resolve();
- }, "network:offline-status-changed", false);
- BrowserOffline.toggleOfflineStatus();
- } else {
- resolve();
- }
- if (goOffline) {
- Services.prefs.setIntPref('network.proxy.type', 0);
- // LOAD_FLAGS_BYPASS_CACHE isn't good enough. So clear the cache.
- Services.cache2.clear();
- }
- });
-}
-
-function goOffline() {
- // Simulate a network outage with offline mode. (Localhost is still
- // accessible in offline mode, so disable the test proxy as well.)
- return toggleOfflineStatus(true);
-}
-
-function goOnline(callback) {
- return toggleOfflineStatus(false);
-}
diff --git a/browser/base/content/test/social/microformats.html b/browser/base/content/test/social/microformats.html
deleted file mode 100644
index 1a0e4436b..000000000
--- a/browser/base/content/test/social/microformats.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html>
- <body>
- <head><title>Raspberry Pi Page</title></head>
- <div class="hproduct">
- <h2 class="fn">Raspberry Pi</h2>
- <img class="photo" src="https://example.com/someimage.jpg" />
- <p class="description">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It's a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>
- <a class="url" href="https://example.com/">More info about the Raspberry Pi</a>
- <p class="price">29.95</p>
- <p class="review hreview"><span id="test-review" class="rating">4.5</span> out of 5</p>
- <p>Categories:
- <a rel="tag" href="https://example.com/wiki/computer" class="category">Computer</a>,
- <a rel="tag" href="https://example.com/wiki/education" class="category">Education</a>
- </p>
- </div>
- </body>
-</html>
diff --git a/browser/base/content/test/social/moz.png b/browser/base/content/test/social/moz.png
deleted file mode 100644
index 769c63634..000000000
--- a/browser/base/content/test/social/moz.png
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/social/opengraph/og_invalid_url.html b/browser/base/content/test/social/opengraph/og_invalid_url.html
deleted file mode 100644
index ad1dae2be..000000000
--- a/browser/base/content/test/social/opengraph/og_invalid_url.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html xmlns:og="http://ogp.me/ns#">
-<head>
- <meta property="og:url" content="chrome://browser/content/aboutDialog.xul"/>
- <meta property="og:site_name" content="Evil chrome delivering website"/>
- <meta property="og:description"
- content="A test corpus file for open graph tags passing a bad url"/>
-</head>
-<body>
- Open Graph Test Page
-</body>
-</html>
diff --git a/browser/base/content/test/social/opengraph/opengraph.html b/browser/base/content/test/social/opengraph/opengraph.html
deleted file mode 100644
index 50b7703b8..000000000
--- a/browser/base/content/test/social/opengraph/opengraph.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<html xmlns:og="http://ogp.me/ns#">
-<head>
- <meta property="og:title" content="&gt;This is my title&lt;"/>
- <meta property="og:url" content="https://www.mozilla.org"/>
- <meta property="og:image" content="https://www.mozilla.org/favicon.png"/>
- <meta property="og:site_name" content="&#62;My simple test page&#60;"/>
- <meta property="og:description"
- content="A test corpus file for open graph tags we care about"/>
-</head>
-<body>
- Open Graph Test Page
-</body>
-</html>
diff --git a/browser/base/content/test/social/opengraph/shortlink_linkrel.html b/browser/base/content/test/social/opengraph/shortlink_linkrel.html
deleted file mode 100644
index 54c40c376..000000000
--- a/browser/base/content/test/social/opengraph/shortlink_linkrel.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
-<head>
- <link rel="image_src" href="http://example.com/1234/56789.jpg" id="image-src" />
- <link id="canonicalurl" rel="canonical" href="http://www.example.com/photos/56789/" />
- <link rel="shortlink" href="http://imshort/p/abcde" />
-</head>
-<body>
- link[rel='shortlink']
-</body>
-</html>
diff --git a/browser/base/content/test/social/opengraph/shorturl_link.html b/browser/base/content/test/social/opengraph/shorturl_link.html
deleted file mode 100644
index 667122cea..000000000
--- a/browser/base/content/test/social/opengraph/shorturl_link.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
-<head>
- <link rel="image_src" href="http://example.com/1234/56789.jpg" id="image-src" />
- <link id="canonicalurl" rel="canonical" href="http://www.example.com/photos/56789/" />
- <link id="shorturl" rev="canonical" type="text/html" href="http://imshort/p/abcde" />
-</head>
-<body>
- link id="shorturl"
-</body>
-</html>
diff --git a/browser/base/content/test/social/opengraph/shorturl_linkrel.html b/browser/base/content/test/social/opengraph/shorturl_linkrel.html
deleted file mode 100644
index 36533528e..000000000
--- a/browser/base/content/test/social/opengraph/shorturl_linkrel.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<html>
-<head>
- <title>Test Image</title>
-
- <meta name="description" content="Iron man in a tutu" />
- <meta name="title" content="Test Image" />
-
- <meta name="medium" content="image" />
- <link rel="image_src" href="http://example.com/1234/56789.jpg" id="image-src" />
- <link id="canonicalurl" rel="canonical" href="http://www.example.com/photos/56789/" />
- <link id="shorturl" href="http://imshort/p/abcde" />
-
- <meta property="og:title" content="TestImage" />
- <meta property="og:type" content="photos:photo" />
- <meta property="og:url" content="http://www.example.com/photos/56789/" />
- <meta property="og:site_name" content="My Photo Site" />
- <meta property="og:description" content="Iron man in a tutu" />
- <meta property="og:image" content="http://example.com/1234/56789.jpg" />
- <meta property="og:image:width" content="480" />
- <meta property="og:image:height" content="640" />
-</head>
-<body>
- link[rel='shorturl']
-</body>
-</html>
diff --git a/browser/base/content/test/social/share.html b/browser/base/content/test/social/share.html
deleted file mode 100644
index 55cba9844..000000000
--- a/browser/base/content/test/social/share.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
- <head>
- <meta charset="utf-8">
- </head>
- <body onload="document.getElementById('testclose').focus()">
- <p>This is a test social share window.</p>
- <input id="testclose"/>
- </body>
-</html>
diff --git a/browser/base/content/test/social/share_activate.html b/browser/base/content/test/social/share_activate.html
deleted file mode 100644
index 69707e705..000000000
--- a/browser/base/content/test/social/share_activate.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<html>
-<!-- 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/. -->
-<head>
- <title>Activation test</title>
-</head>
-<script>
-
-var data = {
- // currently required
- "name": "Demo Social Service",
- // browser_share.js serves this page from "https://example.com"
- "origin": "https://example.com",
- "iconURL": "chrome://branding/content/icon16.png",
- "icon32URL": "chrome://branding/content/favicon32.png",
- "icon64URL": "chrome://branding/content/icon64.png",
- "shareURL": "/browser/browser/base/content/test/social/share.html"
-}
-
-function activate(node) {
- node.setAttribute("data-service", JSON.stringify(data));
- var event = new CustomEvent("ActivateSocialFeature");
- node.dispatchEvent(event);
-}
-
-</script>
-<body>
-
-nothing to see here
-
-<button id="activation" onclick="activate(this, true)">Activate the share provider</button>
-
-</body>
-</html>
diff --git a/browser/base/content/test/social/social_activate.html b/browser/base/content/test/social/social_activate.html
deleted file mode 100644
index 78da597a1..000000000
--- a/browser/base/content/test/social/social_activate.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>Activation test</title>
-</head>
-<script>
-// icons from http://findicons.com/icon/158311/firefox?id=356182 by ipapun
-var data = {
- // currently required
- "name": "Demo Social Service",
- "iconURL": "chrome://branding/content/icon16.png",
- "icon32URL": "chrome://branding/content/favicon32.png",
- "icon64URL": "chrome://branding/content/icon64.png",
-
- // at least one of these must be defined
- "shareURL": "/browser/browser/base/content/test/social/social_share.html",
- "postActivationURL": "/browser/browser/base/content/test/social/social_postActivation.html",
-
- // should be available for display purposes
- "description": "A short paragraph about this provider",
- "author": "Shane Caraveo, Mozilla",
-
- // optional
- "version": "1.0"
-}
-
-function activate(node) {
- node.setAttribute("data-service", JSON.stringify(data));
- var event = new CustomEvent("ActivateSocialFeature");
- node.dispatchEvent(event);
-}
-
-</script>
-<body>
-
-nothing to see here
-
-<button id="activation" onclick="activate(this)">Activate The Demo Provider</button>
-
-</body>
-</html>
diff --git a/browser/base/content/test/social/social_activate_basic.html b/browser/base/content/test/social/social_activate_basic.html
deleted file mode 100644
index 78da597a1..000000000
--- a/browser/base/content/test/social/social_activate_basic.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>Activation test</title>
-</head>
-<script>
-// icons from http://findicons.com/icon/158311/firefox?id=356182 by ipapun
-var data = {
- // currently required
- "name": "Demo Social Service",
- "iconURL": "chrome://branding/content/icon16.png",
- "icon32URL": "chrome://branding/content/favicon32.png",
- "icon64URL": "chrome://branding/content/icon64.png",
-
- // at least one of these must be defined
- "shareURL": "/browser/browser/base/content/test/social/social_share.html",
- "postActivationURL": "/browser/browser/base/content/test/social/social_postActivation.html",
-
- // should be available for display purposes
- "description": "A short paragraph about this provider",
- "author": "Shane Caraveo, Mozilla",
-
- // optional
- "version": "1.0"
-}
-
-function activate(node) {
- node.setAttribute("data-service", JSON.stringify(data));
- var event = new CustomEvent("ActivateSocialFeature");
- node.dispatchEvent(event);
-}
-
-</script>
-<body>
-
-nothing to see here
-
-<button id="activation" onclick="activate(this)">Activate The Demo Provider</button>
-
-</body>
-</html>
diff --git a/browser/base/content/test/social/social_activate_iframe.html b/browser/base/content/test/social/social_activate_iframe.html
deleted file mode 100644
index bde884c9d..000000000
--- a/browser/base/content/test/social/social_activate_iframe.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
- <title>Activation iframe test</title>
-</head>
-
-<body>
-
-<iframe src="social_activate_basic.html"/>
-
-</body>
-</html>
diff --git a/browser/base/content/test/social/social_crash_content_helper.js b/browser/base/content/test/social/social_crash_content_helper.js
deleted file mode 100644
index 4698b6957..000000000
--- a/browser/base/content/test/social/social_crash_content_helper.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var Cu = Components.utils;
-
-// Ideally we would use CrashTestUtils.jsm, but that's only available for
-// xpcshell tests - so we just copy a ctypes crasher from it.
-Cu.import("resource://gre/modules/ctypes.jsm");
-var crash = function() { // this will crash when called.
- let zero = new ctypes.intptr_t(8);
- let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
- badptr.contents
-};
-
-
-var TestHelper = {
- init: function() {
- addMessageListener("social-test:crash", this);
- },
-
- receiveMessage: function(msg) {
- switch (msg.name) {
- case "social-test:crash":
- privateNoteIntentionalCrash();
- crash();
- break;
- }
- },
-}
-
-TestHelper.init();
diff --git a/browser/base/content/test/social/social_postActivation.html b/browser/base/content/test/social/social_postActivation.html
deleted file mode 100644
index e0a6acfdf..000000000
--- a/browser/base/content/test/social/social_postActivation.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>Post-Activation test</title>
-</head>
-
-<body>
-
-Post Activation landing page
-
-</body>
-</html>
diff --git a/browser/base/content/test/tabPrompts/.eslintrc.js b/browser/base/content/test/tabPrompts/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/tabPrompts/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/tabPrompts/browser.ini b/browser/base/content/test/tabPrompts/browser.ini
deleted file mode 100644
index 9b94f14c5..000000000
--- a/browser/base/content/test/tabPrompts/browser.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[browser_closeTabSpecificPanels.js]
-[browser_multiplePrompts.js]
-[browser_openPromptInBackgroundTab.js]
-support-files = openPromptOffTimeout.html
diff --git a/browser/base/content/test/tabPrompts/browser_closeTabSpecificPanels.js b/browser/base/content/test/tabPrompts/browser_closeTabSpecificPanels.js
deleted file mode 100644
index 30c15a56f..000000000
--- a/browser/base/content/test/tabPrompts/browser_closeTabSpecificPanels.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-/*
- * This test creates multiple panels, one that has been tagged as specific to its tab's content
- * and one that isn't. When a tab loses focus, panel specific to that tab should close.
- * The non-specific panel should remain open.
- *
- */
-
-add_task(function*() {
- let tab1 = gBrowser.addTab("http://mochi.test:8888/#0");
- let tab2 = gBrowser.addTab("http://mochi.test:8888/#1");
- let specificPanel = document.createElement("panel");
- specificPanel.setAttribute("tabspecific", "true");
- let generalPanel = document.createElement("panel");
- let anchor = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
- anchor.appendChild(specificPanel);
- anchor.appendChild(generalPanel);
- is(specificPanel.state, "closed", "specificPanel starts as closed");
- is(generalPanel.state, "closed", "generalPanel starts as closed");
-
- let specificPanelPromise = BrowserTestUtils.waitForEvent(specificPanel, "popupshown");
- specificPanel.openPopupAtScreen(210, 210);
- yield specificPanelPromise;
- is(specificPanel.state, "open", "specificPanel has been opened");
-
- let generalPanelPromise = BrowserTestUtils.waitForEvent(generalPanel, "popupshown");
- generalPanel.openPopupAtScreen(510, 510);
- yield generalPanelPromise;
- is(generalPanel.state, "open", "generalPanel has been opened");
-
- gBrowser.tabContainer.advanceSelectedTab(-1, true);
- is(specificPanel.state, "closed", "specificPanel panel is closed after its tab loses focus");
- is(generalPanel.state, "open", "generalPanel is still open after tab switch");
-
- specificPanel.remove();
- generalPanel.remove();
- gBrowser.removeTab(tab1);
- gBrowser.removeTab(tab2);
-});
diff --git a/browser/base/content/test/tabPrompts/browser_multiplePrompts.js b/browser/base/content/test/tabPrompts/browser_multiplePrompts.js
deleted file mode 100644
index c548429ea..000000000
--- a/browser/base/content/test/tabPrompts/browser_multiplePrompts.js
+++ /dev/null
@@ -1,72 +0,0 @@
-"use strict";
-
-/*
- * This test triggers multiple alerts on one single tab, because it"s possible
- * for web content to do so. The behavior is described in bug 1266353.
- *
- * We assert the presentation of the multiple alerts, ensuring we show only
- * the oldest one.
- */
-add_task(function*() {
- const PROMPTCOUNT = 5;
-
- let contentScript = function() {
- var i = 5; // contentScript has no access to PROMPTCOUNT.
- window.addEventListener("message", function() {
- i--;
- if (i) {
- window.postMessage("ping", "*");
- }
- alert("Alert countdown #" + i);
- });
- window.postMessage("ping", "*");
- };
- let url = "data:text/html,<script>(" + encodeURIComponent(contentScript.toSource()) + ")();</script>"
-
- let promptsOpenedPromise = new Promise(function(resolve) {
- let unopenedPromptCount = PROMPTCOUNT;
- Services.obs.addObserver(function observer() {
- unopenedPromptCount--;
- if (!unopenedPromptCount) {
- Services.obs.removeObserver(observer, "tabmodal-dialog-loaded");
- info("Prompts opened.");
- resolve();
- }
- }, "tabmodal-dialog-loaded", false);
- });
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, true);
- info("Tab loaded");
-
- yield promptsOpenedPromise;
-
- let promptsCount = PROMPTCOUNT;
- while (promptsCount--) {
- let prompts = tab.linkedBrowser.parentNode.querySelectorAll("tabmodalprompt");
- is(prompts.length, promptsCount + 1, "There should be " + (promptsCount + 1) + " prompt(s).");
- // The oldest should be the first.
- let i = 0;
- for (let prompt of prompts) {
- is(prompt.Dialog.args.text, "Alert countdown #" + i, "The #" + i + " alert should be labelled as such.");
- if (i !== promptsCount) {
- is(prompt.hidden, true, "This prompt should be hidden.");
- i++;
- continue;
- }
-
- is(prompt.hidden, false, "The last prompt should not be hidden.");
- prompt.onButtonClick(0);
-
- // The click is handled async; wait for an event loop turn for that to
- // happen.
- yield new Promise(function(resolve) {
- Services.tm.mainThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL);
- });
- }
- }
-
- let prompts = tab.linkedBrowser.parentNode.querySelectorAll("tabmodalprompt");
- is(prompts.length, 0, "Prompts should all be dismissed.");
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/base/content/test/tabPrompts/browser_openPromptInBackgroundTab.js b/browser/base/content/test/tabPrompts/browser_openPromptInBackgroundTab.js
deleted file mode 100644
index d244d157a..000000000
--- a/browser/base/content/test/tabPrompts/browser_openPromptInBackgroundTab.js
+++ /dev/null
@@ -1,66 +0,0 @@
-"use strict";
-
-const ROOT = getRootDirectory(gTestPath).replace("chrome://mochitests/content/", "http://example.com/");
-let pageWithAlert = ROOT + "openPromptOffTimeout.html";
-
-registerCleanupFunction(function() {
- Services.perms.removeAll(makeURI(pageWithAlert));
-});
-
-/*
- * This test opens a tab that alerts when it is hidden. We then switch away
- * from the tab, and check that by default the tab is not automatically
- * re-selected. We also check that a checkbox appears in the alert that allows
- * the user to enable this automatically re-selecting. We then check that
- * checking the checkbox does actually enable that behaviour.
- */
-add_task(function*() {
- yield SpecialPowers.pushPrefEnv({"set": [["browser.tabs.dontfocusfordialogs", true]]});
- let firstTab = gBrowser.selectedTab;
- // load page that opens prompt when page is hidden
- let openedTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, pageWithAlert, true);
- let openedTabGotAttentionPromise = BrowserTestUtils.waitForAttribute("attention", openedTab, "true");
- // switch away from that tab again - this triggers the alert.
- yield BrowserTestUtils.switchTab(gBrowser, firstTab);
- // ... but that's async on e10s...
- yield openedTabGotAttentionPromise;
- // check for attention attribute
- is(openedTab.getAttribute("attention"), "true", "Tab with alert should have 'attention' attribute.");
- ok(!openedTab.selected, "Tab with alert should not be selected");
-
- // switch tab back, and check the checkbox is displayed:
- yield BrowserTestUtils.switchTab(gBrowser, openedTab);
- // check the prompt is there, and the extra row is present
- let prompts = openedTab.linkedBrowser.parentNode.querySelectorAll("tabmodalprompt");
- is(prompts.length, 1, "There should be 1 prompt");
- let ourPrompt = prompts[0];
- let row = ourPrompt.querySelector("row");
- ok(row, "Should have found the row with our checkbox");
- let checkbox = row.querySelector("checkbox[label*='example.com']");
- ok(checkbox, "The checkbox should be there");
- ok(!checkbox.checked, "Checkbox shouldn't be checked");
- // tick box and accept dialog
- checkbox.checked = true;
- ourPrompt.onButtonClick(0);
- // Wait for that click to actually be handled completely.
- yield new Promise(function(resolve) {
- Services.tm.mainThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL);
- });
- // check permission is set
- let ps = Services.perms;
- is(ps.ALLOW_ACTION, ps.testPermission(makeURI(pageWithAlert), "focus-tab-by-prompt"),
- "Tab switching should now be allowed");
-
- let openedTabSelectedPromise = BrowserTestUtils.waitForAttribute("selected", openedTab, "true");
- // switch to other tab again
- yield BrowserTestUtils.switchTab(gBrowser, firstTab);
-
- // This is sync in non-e10s, but in e10s we need to wait for this, so yield anyway.
- // Note that the switchTab promise doesn't actually guarantee anything about *which*
- // tab ends up as selected when its event fires, so using that here wouldn't work.
- yield openedTabSelectedPromise;
- // should be switched back
- ok(openedTab.selected, "Ta-dah, the other tab should now be selected again!");
-
- yield BrowserTestUtils.removeTab(openedTab);
-});
diff --git a/browser/base/content/test/tabPrompts/openPromptOffTimeout.html b/browser/base/content/test/tabPrompts/openPromptOffTimeout.html
deleted file mode 100644
index e865c7872..000000000
--- a/browser/base/content/test/tabPrompts/openPromptOffTimeout.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<body>
-This page opens an alert box when the page is hidden.
-<script>
-document.addEventListener("visibilitychange", () => {
- if (document.hidden) {
- alert("You hid my page!");
- }
-}, false);
-</script>
-</body>
diff --git a/browser/base/content/test/tabcrashed/browser.ini b/browser/base/content/test/tabcrashed/browser.ini
deleted file mode 100644
index 051b40d9f..000000000
--- a/browser/base/content/test/tabcrashed/browser.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-[browser_shown.js]
-skip-if = !e10s || !crashreporter
-[browser_clearEmail.js]
-skip-if = !e10s || !crashreporter
-[browser_showForm.js]
-skip-if = !e10s || !crashreporter
-[browser_withoutDump.js]
-skip-if = !e10s
-[browser_autoSubmitRequest.js]
-skip-if = !e10s || !crashreporter
diff --git a/browser/base/content/test/tabcrashed/browser_autoSubmitRequest.js b/browser/base/content/test/tabcrashed/browser_autoSubmitRequest.js
deleted file mode 100644
index 778331814..000000000
--- a/browser/base/content/test/tabcrashed/browser_autoSubmitRequest.js
+++ /dev/null
@@ -1,152 +0,0 @@
-"use strict";
-
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const AUTOSUBMIT_PREF = "browser.crashReports.unsubmittedCheck.autoSubmit2";
-
-const {TabStateFlusher} =
- Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
-// On debug builds, crashing tabs results in much thinking, which
-// slows down the test and results in intermittent test timeouts,
-// so we'll pump up the expected timeout for this test.
-requestLongerTimeout(2);
-
-/**
- * Tests that if the user is not configured to autosubmit
- * backlogged crash reports, that we offer to do that, and
- * that the user can accept that offer.
- */
-add_task(function* test_show_form() {
- yield SpecialPowers.pushPrefEnv({
- set: [[AUTOSUBMIT_PREF, false]],
- })
-
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- // Make sure we've flushed the browser messages so that
- // we can restore it.
- yield TabStateFlusher.flush(browser);
-
- // Now crash the browser.
- yield BrowserTestUtils.crashBrowser(browser);
-
- let doc = browser.contentDocument;
-
- // Ensure the request is visible. We can safely reach into
- // the content since about:tabcrashed is an in-process URL.
- let requestAutoSubmit = doc.getElementById("requestAutoSubmit");
- Assert.ok(!requestAutoSubmit.hidden,
- "Request for autosubmission is visible.");
-
- // Since the pref is set to false, the checkbox should be
- // unchecked.
- let autoSubmit = doc.getElementById("autoSubmit");
- Assert.ok(!autoSubmit.checked,
- "Checkbox for autosubmission is not checked.")
-
- // Check the checkbox, and then restore the tab.
- autoSubmit.checked = true;
- let restoreButton = doc.getElementById("restoreTab");
- restoreButton.click();
-
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
-
- // The autosubmission pref should now be set.
- Assert.ok(Services.prefs.getBoolPref(AUTOSUBMIT_PREF),
- "Autosubmission pref should have been set.");
- });
-});
-
-/**
- * Tests that if the user is autosubmitting backlogged crash reports
- * that we don't make the offer again.
- */
-add_task(function* test_show_form() {
- yield SpecialPowers.pushPrefEnv({
- set: [[AUTOSUBMIT_PREF, true]],
- })
-
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- yield TabStateFlusher.flush(browser);
- // Now crash the browser.
- yield BrowserTestUtils.crashBrowser(browser);
-
- let doc = browser.contentDocument;
-
- // Ensure the request is NOT visible. We can safely reach into
- // the content since about:tabcrashed is an in-process URL.
- let requestAutoSubmit = doc.getElementById("requestAutoSubmit");
- Assert.ok(requestAutoSubmit.hidden,
- "Request for autosubmission is not visible.");
-
- // Restore the tab.
- let restoreButton = doc.getElementById("restoreTab");
- restoreButton.click();
-
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
-
- // The autosubmission pref should still be set to true.
- Assert.ok(Services.prefs.getBoolPref(AUTOSUBMIT_PREF),
- "Autosubmission pref should have been set.");
- });
-});
-
-/**
- * Tests that we properly set the autoSubmit preference if the user is
- * presented with a tabcrashed page without a crash report.
- */
-add_task(function* test_no_offer() {
- // We should default to sending the report.
- Assert.ok(TabCrashHandler.prefs.getBoolPref("sendReport"));
-
- yield SpecialPowers.pushPrefEnv({
- set: [[AUTOSUBMIT_PREF, false]],
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- yield TabStateFlusher.flush(browser);
-
- // Make it so that it seems like no dump is available for the next crash.
- prepareNoDump();
-
- // Now crash the browser.
- yield BrowserTestUtils.crashBrowser(browser);
-
- // eslint-disable-next-line mozilla/no-cpows-in-tests
- let doc = browser.contentDocument;
-
- // Ensure the request to autosubmit is invisible, since there's no report.
- let requestRect = doc.getElementById("requestAutoSubmit")
- .getBoundingClientRect();
- Assert.equal(0, requestRect.height,
- "Request for autosubmission has no height");
- Assert.equal(0, requestRect.width,
- "Request for autosubmission has no width");
-
- // Since the pref is set to false, the checkbox should be
- // unchecked.
- let autoSubmit = doc.getElementById("autoSubmit");
- Assert.ok(!autoSubmit.checked,
- "Checkbox for autosubmission is not checked.");
-
- let restoreButton = doc.getElementById("restoreTab");
- restoreButton.click();
-
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
-
- // The autosubmission pref should now be set.
- Assert.ok(!Services.prefs.getBoolPref(AUTOSUBMIT_PREF),
- "Autosubmission pref should not have changed.");
- });
-
- // We should not have changed the default value for sending the report.
- Assert.ok(TabCrashHandler.prefs.getBoolPref("sendReport"));
-});
diff --git a/browser/base/content/test/tabcrashed/browser_clearEmail.js b/browser/base/content/test/tabcrashed/browser_clearEmail.js
deleted file mode 100644
index 9ec04944f..000000000
--- a/browser/base/content/test/tabcrashed/browser_clearEmail.js
+++ /dev/null
@@ -1,85 +0,0 @@
-"use strict";
-
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const EMAIL = "foo@privacy.com";
-
-/**
- * Sets up the browser to send crash reports to the local crash report
- * testing server.
- */
-add_task(function* setup() {
- // The test harness sets MOZ_CRASHREPORTER_NO_REPORT, which disables crash
- // reports. This test needs them enabled. The test also needs a mock
- // report server, and fortunately one is already set up by toolkit/
- // crashreporter/test/Makefile.in. Assign its URL to MOZ_CRASHREPORTER_URL,
- // which CrashSubmit.jsm uses as a server override.
- let env = Cc["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- let noReport = env.get("MOZ_CRASHREPORTER_NO_REPORT");
- let serverUrl = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", "");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- // By default, requesting the email address of the user is disabled.
- // For the purposes of this test, we turn it back on.
- yield SpecialPowers.pushPrefEnv({
- set: [["browser.tabs.crashReporting.requestEmail", true]],
- });
-
- registerCleanupFunction(function() {
- env.set("MOZ_CRASHREPORTER_NO_REPORT", noReport);
- env.set("MOZ_CRASHREPORTER_URL", serverUrl);
- });
-});
-
-/**
- * Test that if we have an email address stored in prefs, and we decide
- * not to submit the email address in the next crash report, that we
- * clear the email address.
- */
-add_task(function* test_clear_email() {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- let prefs = TabCrashHandler.prefs;
- let originalSendReport = prefs.getBoolPref("sendReport");
- let originalEmailMe = prefs.getBoolPref("emailMe");
- let originalIncludeURL = prefs.getBoolPref("includeURL");
- let originalEmail = prefs.getCharPref("email");
-
- // Pretend that we stored an email address from the previous
- // crash
- prefs.setCharPref("email", EMAIL);
- prefs.setBoolPref("emailMe", true);
-
- let tab = gBrowser.getTabForBrowser(browser);
- yield BrowserTestUtils.crashBrowser(browser);
- let doc = browser.contentDocument;
-
- // Since about:tabcrashed will run in the parent process, we can safely
- // manipulate its DOM nodes directly
- let emailMe = doc.getElementById("emailMe");
- emailMe.checked = false;
-
- let crashReport = promiseCrashReport({
- Email: "",
- });
-
- let restoreTab = browser.contentDocument.getElementById("restoreTab");
- restoreTab.click();
- yield BrowserTestUtils.waitForEvent(tab, "SSTabRestored");
- yield crashReport;
-
- is(prefs.getCharPref("email"), "", "No email address should be stored");
-
- // Submitting the crash report may have set some prefs regarding how to
- // send tab crash reports. Let's reset them for the next test.
- prefs.setBoolPref("sendReport", originalSendReport);
- prefs.setBoolPref("emailMe", originalEmailMe);
- prefs.setBoolPref("includeURL", originalIncludeURL);
- prefs.setCharPref("email", originalEmail);
- });
-});
-
diff --git a/browser/base/content/test/tabcrashed/browser_showForm.js b/browser/base/content/test/tabcrashed/browser_showForm.js
deleted file mode 100644
index 780af93fb..000000000
--- a/browser/base/content/test/tabcrashed/browser_showForm.js
+++ /dev/null
@@ -1,40 +0,0 @@
-"use strict";
-
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-
-// On debug builds, crashing tabs results in much thinking, which
-// slows down the test and results in intermittent test timeouts,
-// so we'll pump up the expected timeout for this test.
-requestLongerTimeout(2);
-
-/**
- * Tests that we show the about:tabcrashed additional details form
- * if the "submit a crash report" checkbox was checked by default.
- */
-add_task(function* test_show_form() {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- // Flip the pref so that the checkbox should be checked
- // by default.
- let pref = TabCrashHandler.prefs.root + "sendReport";
- yield SpecialPowers.pushPrefEnv({
- set: [[pref, true]]
- });
-
- // Now crash the browser.
- yield BrowserTestUtils.crashBrowser(browser);
-
- let doc = browser.contentDocument;
-
- // Ensure the checkbox is checked. We can safely reach into
- // the content since about:tabcrashed is an in-process URL.
- let checkbox = doc.getElementById("sendReport");
- ok(checkbox.checked, "Send report checkbox is checked.");
-
- // Ensure the options form is displayed.
- let options = doc.getElementById("options");
- ok(!options.hidden, "Showing the crash report options form.");
- });
-});
diff --git a/browser/base/content/test/tabcrashed/browser_shown.js b/browser/base/content/test/tabcrashed/browser_shown.js
deleted file mode 100644
index d09d9438f..000000000
--- a/browser/base/content/test/tabcrashed/browser_shown.js
+++ /dev/null
@@ -1,203 +0,0 @@
-"use strict";
-
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const COMMENTS = "Here's my test comment!";
-const EMAIL = "foo@privacy.com";
-
-/**
- * Sets up the browser to send crash reports to the local crash report
- * testing server.
- */
-add_task(function* setup() {
- // The test harness sets MOZ_CRASHREPORTER_NO_REPORT, which disables crash
- // reports. This test needs them enabled. The test also needs a mock
- // report server, and fortunately one is already set up by toolkit/
- // crashreporter/test/Makefile.in. Assign its URL to MOZ_CRASHREPORTER_URL,
- // which CrashSubmit.jsm uses as a server override.
- let env = Cc["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- let noReport = env.get("MOZ_CRASHREPORTER_NO_REPORT");
- let serverUrl = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_NO_REPORT", "");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- // On debug builds, crashing tabs results in much thinking, which
- // slows down the test and results in intermittent test timeouts,
- // so we'll pump up the expected timeout for this test.
- requestLongerTimeout(2);
-
- registerCleanupFunction(function() {
- env.set("MOZ_CRASHREPORTER_NO_REPORT", noReport);
- env.set("MOZ_CRASHREPORTER_URL", serverUrl);
- });
-});
-
-/**
- * This function returns a Promise that resolves once the following
- * actions have taken place:
- *
- * 1) A new tab is opened up at PAGE
- * 2) The tab is crashed
- * 3) The about:tabcrashed page's fields are set in accordance with
- * fieldValues
- * 4) The tab is restored
- * 5) A crash report is received from the testing server
- * 6) Any tab crash prefs that were overwritten are reset
- *
- * @param fieldValues
- * An Object describing how to set the about:tabcrashed
- * fields. The following properties are accepted:
- *
- * comments (String)
- * The comments to put in the comment textarea
- * email (String)
- * The email address to put in the email address input
- * emailMe (bool)
- * The checked value of the "Email me" checkbox
- * includeURL (bool)
- * The checked value of the "Include URL" checkbox
- *
- * If any of these fields are missing, the defaults from
- * the user preferences are used.
- * @param expectedExtra
- * An Object describing the expected values that the submitted
- * crash report's extra data should contain.
- * @returns Promise
- */
-function crashTabTestHelper(fieldValues, expectedExtra) {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- let prefs = TabCrashHandler.prefs;
- let originalSendReport = prefs.getBoolPref("sendReport");
- let originalEmailMe = prefs.getBoolPref("emailMe");
- let originalIncludeURL = prefs.getBoolPref("includeURL");
- let originalEmail = prefs.getCharPref("email");
-
- let tab = gBrowser.getTabForBrowser(browser);
- yield BrowserTestUtils.crashBrowser(browser);
- let doc = browser.contentDocument;
-
- // Since about:tabcrashed will run in the parent process, we can safely
- // manipulate its DOM nodes directly
- let comments = doc.getElementById("comments");
- let email = doc.getElementById("email");
- let emailMe = doc.getElementById("emailMe");
- let includeURL = doc.getElementById("includeURL");
-
- if (fieldValues.hasOwnProperty("comments")) {
- comments.value = fieldValues.comments;
- }
-
- if (fieldValues.hasOwnProperty("email")) {
- email.value = fieldValues.email;
- }
-
- if (fieldValues.hasOwnProperty("emailMe")) {
- emailMe.checked = fieldValues.emailMe;
- }
-
- if (fieldValues.hasOwnProperty("includeURL")) {
- includeURL.checked = fieldValues.includeURL;
- }
-
- let crashReport = promiseCrashReport(expectedExtra);
- let restoreTab = browser.contentDocument.getElementById("restoreTab");
- restoreTab.click();
- yield BrowserTestUtils.waitForEvent(tab, "SSTabRestored");
- yield crashReport;
-
- // Submitting the crash report may have set some prefs regarding how to
- // send tab crash reports. Let's reset them for the next test.
- prefs.setBoolPref("sendReport", originalSendReport);
- prefs.setBoolPref("emailMe", originalEmailMe);
- prefs.setBoolPref("includeURL", originalIncludeURL);
- prefs.setCharPref("email", originalEmail);
- });
-}
-
-/**
- * Tests what we send with the crash report by default. By default, we do not
- * send any comments, the URL of the crashing page, or the email address of
- * the user.
- */
-add_task(function* test_default() {
- yield crashTabTestHelper({}, {
- "Comments": null,
- "URL": "",
- "Email": null,
- });
-});
-
-/**
- * Test just sending a comment.
- */
-add_task(function* test_just_a_comment() {
- yield crashTabTestHelper({
- comments: COMMENTS,
- }, {
- "Comments": COMMENTS,
- "URL": "",
- "Email": null,
- });
-});
-
-/**
- * Test that we don't send email if emailMe is unchecked
- */
-add_task(function* test_no_email() {
- yield crashTabTestHelper({
- email: EMAIL,
- emailMe: false,
- }, {
- "Comments": null,
- "URL": "",
- "Email": null,
- });
-});
-
-/**
- * Test that we can send an email address if emailMe is checked
- */
-add_task(function* test_yes_email() {
- yield crashTabTestHelper({
- email: EMAIL,
- emailMe: true,
- }, {
- "Comments": null,
- "URL": "",
- "Email": EMAIL,
- });
-});
-
-/**
- * Test that we will send the URL of the page if includeURL is checked.
- */
-add_task(function* test_send_URL() {
- yield crashTabTestHelper({
- includeURL: true,
- }, {
- "Comments": null,
- "URL": PAGE,
- "Email": null,
- });
-});
-
-/**
- * Test that we can send comments, the email address, and the URL
- */
-add_task(function* test_send_all() {
- yield crashTabTestHelper({
- includeURL: true,
- emailMe: true,
- email: EMAIL,
- comments: COMMENTS,
- }, {
- "Comments": COMMENTS,
- "URL": PAGE,
- "Email": EMAIL,
- });
-});
-
diff --git a/browser/base/content/test/tabcrashed/browser_withoutDump.js b/browser/base/content/test/tabcrashed/browser_withoutDump.js
deleted file mode 100644
index 62557f443..000000000
--- a/browser/base/content/test/tabcrashed/browser_withoutDump.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-
-add_task(function* setup() {
- prepareNoDump();
-});
-
-/**
- * Tests tab crash page when a dump is not available.
- */
-add_task(function* test_without_dump() {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- let tab = gBrowser.getTabForBrowser(browser);
- yield BrowserTestUtils.crashBrowser(browser);
-
- let tabRemovedPromise = BrowserTestUtils.removeTab(tab, { dontRemove: true });
-
- yield ContentTask.spawn(browser, null, function*() {
- let doc = content.document;
- Assert.ok(!doc.documentElement.classList.contains("crashDumpAvailable"),
- "doesn't have crash dump");
-
- let options = doc.getElementById("options");
- Assert.ok(options, "has crash report options");
- Assert.ok(options.hidden, "crash report options are hidden");
-
- doc.getElementById("closeTab").click();
- });
-
- yield tabRemovedPromise;
- });
-});
diff --git a/browser/base/content/test/tabcrashed/head.js b/browser/base/content/test/tabcrashed/head.js
deleted file mode 100644
index 6eee08f13..000000000
--- a/browser/base/content/test/tabcrashed/head.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * Returns a Promise that resolves once a crash report has
- * been submitted. This function will also test the crash
- * reports extra data to see if it matches expectedExtra.
- *
- * @param expectedExtra (object)
- * An Object whose key-value pairs will be compared
- * against the key-value pairs in the extra data of the
- * crash report. A test failure will occur if there is
- * a mismatch.
- *
- * If the value of the key-value pair is "null", this will
- * be interpreted as "this key should not be included in the
- * extra data", and will cause a test failure if it is detected
- * in the crash report.
- *
- * Note that this will ignore any keys that are not included
- * in expectedExtra. It's possible that the crash report
- * will contain other extra information that is not
- * compared against.
- * @returns Promise
- */
-function promiseCrashReport(expectedExtra={}) {
- return Task.spawn(function*() {
- info("Starting wait on crash-report-status");
- let [subject, ] =
- yield TestUtils.topicObserved("crash-report-status", (unused, data) => {
- return data == "success";
- });
- info("Topic observed!");
-
- if (!(subject instanceof Ci.nsIPropertyBag2)) {
- throw new Error("Subject was not a Ci.nsIPropertyBag2");
- }
-
- let remoteID = getPropertyBagValue(subject, "serverCrashID");
- if (!remoteID) {
- throw new Error("Report should have a server ID");
- }
-
- let file = Cc["@mozilla.org/file/local;1"]
- .createInstance(Ci.nsILocalFile);
- file.initWithPath(Services.crashmanager._submittedDumpsDir);
- file.append(remoteID + ".txt");
- if (!file.exists()) {
- throw new Error("Report should have been received by the server");
- }
-
- file.remove(false);
-
- let extra = getPropertyBagValue(subject, "extra");
- if (!(extra instanceof Ci.nsIPropertyBag2)) {
- throw new Error("extra was not a Ci.nsIPropertyBag2");
- }
-
- info("Iterating crash report extra keys");
- let enumerator = extra.enumerator;
- while (enumerator.hasMoreElements()) {
- let key = enumerator.getNext().QueryInterface(Ci.nsIProperty).name;
- let value = extra.getPropertyAsAString(key);
- if (key in expectedExtra) {
- if (expectedExtra[key] == null) {
- ok(false, `Got unexpected key ${key} with value ${value}`);
- } else {
- is(value, expectedExtra[key],
- `Crash report had the right extra value for ${key}`);
- }
- }
- }
- });
-}
-
-
-/**
- * For an nsIPropertyBag, returns the value for a given
- * key.
- *
- * @param bag
- * The nsIPropertyBag to retrieve the value from
- * @param key
- * The key that we want to get the value for from the
- * bag
- * @returns The value corresponding to the key from the bag,
- * or null if the value could not be retrieved (for
- * example, if no value is set at that key).
-*/
-function getPropertyBagValue(bag, key) {
- try {
- let val = bag.getProperty(key);
- return val;
- } catch (e) {
- if (e.result != Cr.NS_ERROR_FAILURE) {
- throw e;
- }
- }
-
- return null;
-}
-
-/**
- * Monkey patches TabCrashHandler.getDumpID to return null in order to test
- * about:tabcrashed when a dump is not available.
- */
-function prepareNoDump() {
- let originalGetDumpID = TabCrashHandler.getDumpID;
- TabCrashHandler.getDumpID = function(browser) { return null; };
- registerCleanupFunction(() => {
- TabCrashHandler.getDumpID = originalGetDumpID;
- });
-}
diff --git a/browser/base/content/test/tabs/.eslintrc.js b/browser/base/content/test/tabs/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/tabs/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/tabs/browser.ini b/browser/base/content/test/tabs/browser.ini
deleted file mode 100644
index 7771e0a6e..000000000
--- a/browser/base/content/test/tabs/browser.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[browser_tabSpinnerProbe.js]
-skip-if = !e10s # Tab spinner is e10s only.
-[browser_tabSwitchPrintPreview.js]
-skip-if = os == 'mac'
diff --git a/browser/base/content/test/tabs/browser_tabSpinnerProbe.js b/browser/base/content/test/tabs/browser_tabSpinnerProbe.js
deleted file mode 100644
index c3569c2b1..000000000
--- a/browser/base/content/test/tabs/browser_tabSpinnerProbe.js
+++ /dev/null
@@ -1,93 +0,0 @@
-"use strict";
-
-/**
- * Tests the FX_TAB_SWITCH_SPINNER_VISIBLE_MS and
- * FX_TAB_SWITCH_SPINNER_VISIBLE_LONG_MS telemetry probes
- */
-let gMinHangTime = 500; // ms
-let gMaxHangTime = 5 * 1000; // ms
-
-/**
- * Make a data URI for a generic webpage with a script that hangs for a given
- * amount of time.
- * @param {?Number} aHangMs Number of milliseconds that the hang should last.
- * Defaults to 0.
- * @return {String} The data URI generated.
- */
-function makeDataURI(aHangMs = 0) {
- return `data:text/html,
- <html>
- <head>
- <meta charset="utf-8"/>
- <title>Tab Spinner Test</title>
- <script>
- function hang() {
- let hangDuration = ${aHangMs};
- if (hangDuration > 0) {
- let startTime = window.performance.now();
- while(window.performance.now() - startTime < hangDuration) {}
- }
- }
- </script>
- </head>
- <body>
- <h1 id='header'>Tab Spinner Test</h1>
- </body>
- </html>`;
-}
-
-/**
- * Returns the sum of all values in an array.
- * @param {Array} aArray An array of integers
- * @return {Number} The sum of the integers in the array
- */
-function sum(aArray) {
- return aArray.reduce(function(previousValue, currentValue) {
- return previousValue + currentValue;
- });
-}
-
-/**
- * A generator intended to be run as a Task. It tests one of the tab spinner
- * telemetry probes.
- * @param {String} aProbe The probe to test. Should be one of:
- * - FX_TAB_SWITCH_SPINNER_VISIBLE_MS
- * - FX_TAB_SWITCH_SPINNER_VISIBLE_LONG_MS
- */
-function* testProbe(aProbe) {
- info(`Testing probe: ${aProbe}`);
- let histogram = Services.telemetry.getHistogramById(aProbe);
- let buckets = histogram.snapshot().ranges.filter(function(value) {
- return (value > gMinHangTime && value < gMaxHangTime);
- });
- let delayTime = buckets[0]; // Pick a bucket arbitrarily
-
- // The tab spinner does not show up instantly. We need to hang for a little
- // bit of extra time to account for the tab spinner delay.
- delayTime += gBrowser.selectedTab.linkedBrowser.getTabBrowser()._getSwitcher().TAB_SWITCH_TIMEOUT;
- let dataURI1 = makeDataURI(delayTime);
- let dataURI2 = makeDataURI();
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, dataURI1);
- histogram.clear();
- // Queue a hang in the content process when the
- // event loop breathes next.
- ContentTask.spawn(tab1.linkedBrowser, null, function*() {
- content.wrappedJSObject.hang();
- });
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, dataURI2);
- let snapshot = histogram.snapshot();
- yield BrowserTestUtils.removeTab(tab2);
- yield BrowserTestUtils.removeTab(tab1);
- ok(sum(snapshot.counts) > 0,
- `Spinner probe should now have a value in some bucket`);
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-});
-
-add_task(testProbe.bind(null, "FX_TAB_SWITCH_SPINNER_VISIBLE_MS"));
-add_task(testProbe.bind(null, "FX_TAB_SWITCH_SPINNER_VISIBLE_LONG_MS"));
diff --git a/browser/base/content/test/tabs/browser_tabSwitchPrintPreview.js b/browser/base/content/test/tabs/browser_tabSwitchPrintPreview.js
deleted file mode 100644
index 4ec36a7cc..000000000
--- a/browser/base/content/test/tabs/browser_tabSwitchPrintPreview.js
+++ /dev/null
@@ -1,29 +0,0 @@
-const kURL1 = "data:text/html,Should I stay or should I go?";
-const kURL2 = "data:text/html,I shouldn't be here!";
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-});
-
-/**
- * Verify that if we open a new tab and try to make it the selected tab while
- * print preview is up, that doesn't happen.
- */
-add_task(function* () {
- yield BrowserTestUtils.withNewTab(kURL1, function* (browser) {
- let tab = gBrowser.addTab(kURL2);
- document.getElementById("cmd_printPreview").doCommand();
- gBrowser.selectedTab = tab;
- yield BrowserTestUtils.waitForCondition(() => gInPrintPreviewMode, "should be in print preview mode");
- isnot(gBrowser.selectedTab, tab, "Selected tab should not be the tab we added");
- is(gBrowser.selectedTab, PrintPreviewListener._printPreviewTab, "Selected tab should be the print preview tab");
- gBrowser.selectedTab = tab;
- isnot(gBrowser.selectedTab, tab, "Selected tab should still not be the tab we added");
- is(gBrowser.selectedTab, PrintPreviewListener._printPreviewTab, "Selected tab should still be the print preview tab");
- PrintUtils.exitPrintPreview();
- yield BrowserTestUtils.waitForCondition(() => !gInPrintPreviewMode, "should be in print preview mode");
- yield BrowserTestUtils.removeTab(tab);
- });
-});
diff --git a/browser/base/content/test/urlbar/.eslintrc.js b/browser/base/content/test/urlbar/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/urlbar/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/urlbar/authenticate.sjs b/browser/base/content/test/urlbar/authenticate.sjs
deleted file mode 100644
index 58da655cf..000000000
--- a/browser/base/content/test/urlbar/authenticate.sjs
+++ /dev/null
@@ -1,220 +0,0 @@
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 200, "AlmostOK");
- response.write("Error handling request: " + e);
- }
-}
-
-
-function reallyHandleRequest(request, response) {
- var match;
- var requestAuth = true, requestProxyAuth = true;
-
- // Allow the caller to drive how authentication is processed via the query.
- // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
- // The extra ? allows the user/pass/realm checks to succeed if the name is
- // at the beginning of the query string.
- var query = "?" + request.queryString;
-
- var expected_user = "", expected_pass = "", realm = "mochitest";
- var proxy_expected_user = "", proxy_expected_pass = "", proxy_realm = "mochi-proxy";
- var huge = false, plugin = false, anonymous = false;
- var authHeaderCount = 1;
- // user=xxx
- match = /[^_]user=([^&]*)/.exec(query);
- if (match)
- expected_user = match[1];
-
- // pass=xxx
- match = /[^_]pass=([^&]*)/.exec(query);
- if (match)
- expected_pass = match[1];
-
- // realm=xxx
- match = /[^_]realm=([^&]*)/.exec(query);
- if (match)
- realm = match[1];
-
- // proxy_user=xxx
- match = /proxy_user=([^&]*)/.exec(query);
- if (match)
- proxy_expected_user = match[1];
-
- // proxy_pass=xxx
- match = /proxy_pass=([^&]*)/.exec(query);
- if (match)
- proxy_expected_pass = match[1];
-
- // proxy_realm=xxx
- match = /proxy_realm=([^&]*)/.exec(query);
- if (match)
- proxy_realm = match[1];
-
- // huge=1
- match = /huge=1/.exec(query);
- if (match)
- huge = true;
-
- // plugin=1
- match = /plugin=1/.exec(query);
- if (match)
- plugin = true;
-
- // multiple=1
- match = /multiple=([^&]*)/.exec(query);
- if (match)
- authHeaderCount = match[1]+0;
-
- // anonymous=1
- match = /anonymous=1/.exec(query);
- if (match)
- anonymous = true;
-
- // Look for an authentication header, if any, in the request.
- //
- // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- //
- // This test only supports Basic auth. The value sent by the client is
- // "username:password", obscured with base64 encoding.
-
- var actual_user = "", actual_pass = "", authHeader, authPresent = false;
- if (request.hasHeader("Authorization")) {
- authPresent = true;
- authHeader = request.getHeader("Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw "Couldn't parse auth header: " + authHeader;
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw "Couldn't decode auth header: " + userpass;
- actual_user = match[1];
- actual_pass = match[2];
- }
-
- var proxy_actual_user = "", proxy_actual_pass = "";
- if (request.hasHeader("Proxy-Authorization")) {
- authHeader = request.getHeader("Proxy-Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw "Couldn't parse auth header: " + authHeader;
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw "Couldn't decode auth header: " + userpass;
- proxy_actual_user = match[1];
- proxy_actual_pass = match[2];
- }
-
- // Don't request authentication if the credentials we got were what we
- // expected.
- if (expected_user == actual_user &&
- expected_pass == actual_pass) {
- requestAuth = false;
- }
- if (proxy_expected_user == proxy_actual_user &&
- proxy_expected_pass == proxy_actual_pass) {
- requestProxyAuth = false;
- }
-
- if (anonymous) {
- if (authPresent) {
- response.setStatusLine("1.0", 400, "Unexpected authorization header found");
- } else {
- response.setStatusLine("1.0", 200, "Authorization header not found");
- }
- } else {
- if (requestProxyAuth) {
- response.setStatusLine("1.0", 407, "Proxy authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("Proxy-Authenticate", "basic realm=\"" + proxy_realm + "\"", true);
- } else if (requestAuth) {
- response.setStatusLine("1.0", 401, "Authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
- } else {
- response.setStatusLine("1.0", 200, "OK");
- }
- }
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Proxy: <span id='proxy'>" + (requestProxyAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
- response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
-
- if (huge) {
- response.write("<div style='display: none'>");
- for (i = 0; i < 100000; i++) {
- response.write("123456789\n");
- }
- response.write("</div>");
- response.write("<span id='footnote'>This is a footnote after the huge content fill</span>");
- }
-
- if (plugin) {
- response.write("<embed id='embedtest' style='width: 400px; height: 100px;' " +
- "type='application/x-test'></embed>\n");
- }
-
- response.write("</html>");
-}
-
-
-// base64 decoder
-//
-// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
-// doesn't seem to exist. :-(
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
-
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/browser/base/content/test/urlbar/browser.ini b/browser/base/content/test/urlbar/browser.ini
deleted file mode 100644
index 39bc086c9..000000000
--- a/browser/base/content/test/urlbar/browser.ini
+++ /dev/null
@@ -1,101 +0,0 @@
-[DEFAULT]
-support-files =
- dummy_page.html
- head.js
-
-[browser_URLBarSetURI.js]
-skip-if = (os == "linux" || os == "mac") && debug # bug 970052, bug 970053
-[browser_action_keyword.js]
-skip-if = os == "linux" # Bug 1188154
-support-files =
- print_postdata.sjs
-[browser_action_keyword_override.js]
-[browser_action_searchengine.js]
-[browser_action_searchengine_alias.js]
-[browser_autocomplete_a11y_label.js]
-[browser_autocomplete_autoselect.js]
-[browser_autocomplete_cursor.js]
-[browser_autocomplete_edit_completed.js]
-[browser_autocomplete_enter_race.js]
-[browser_autocomplete_no_title.js]
-[browser_autocomplete_tag_star_visibility.js]
-[browser_bug1104165-switchtab-decodeuri.js]
-[browser_bug1003461-switchtab-override.js]
-[browser_bug1024133-switchtab-override-keynav.js]
-[browser_bug1025195_switchToTabHavingURI_aOpenParams.js]
-[browser_bug1070778.js]
-[browser_bug1225194-remotetab.js]
-[browser_bug304198.js]
-[browser_bug556061.js]
-subsuite = clipboard
-[browser_bug562649.js]
-[browser_bug623155.js]
-support-files =
- redirect_bug623155.sjs
-[browser_bug783614.js]
-[browser_canonizeURL.js]
-[browser_dragdropURL.js]
-[browser_locationBarCommand.js]
-[browser_locationBarExternalLoad.js]
-[browser_moz_action_link.js]
-[browser_removeUnsafeProtocolsFromURLBarPaste.js]
-subsuite = clipboard
-[browser_search_favicon.js]
-[browser_tabMatchesInAwesomebar.js]
-support-files =
- moz.png
-[browser_tabMatchesInAwesomebar_perwindowpb.js]
-skip-if = os == 'linux' # Bug 1104755
-[browser_urlbarAboutHomeLoading.js]
-[browser_urlbarAutoFillTrimURLs.js]
-[browser_urlbarCopying.js]
-subsuite = clipboard
-support-files =
- authenticate.sjs
-[browser_urlbarDecode.js]
-[browser_urlbarDelete.js]
-[browser_urlbarEnter.js]
-[browser_urlbarEnterAfterMouseOver.js]
-skip-if = os == "linux" # Bug 1073339 - Investigate autocomplete test unreliability on Linux/e10s
-[browser_urlbarFocusedCmdK.js]
-[browser_urlbarHashChangeProxyState.js]
-[browser_urlbarKeepStateAcrossTabSwitches.js]
-[browser_urlbarOneOffs.js]
-[browser_urlbarPrivateBrowsingWindowChange.js]
-[browser_urlbarRaceWithTabs.js]
-[browser_urlbarRevert.js]
-[browser_urlbarSearchSingleWordNotification.js]
-[browser_urlbarSearchSuggestions.js]
-support-files =
- searchSuggestionEngine.xml
- searchSuggestionEngine.sjs
-[browser_urlbarSearchSuggestionsNotification.js]
-support-files =
- searchSuggestionEngine.xml
- searchSuggestionEngine.sjs
-[browser_urlbarSearchTelemetry.js]
-support-files =
- searchSuggestionEngine.xml
- searchSuggestionEngine.sjs
-[browser_urlbarStop.js]
-[browser_urlbarTrimURLs.js]
-subsuite = clipboard
-[browser_urlbarUpdateForDomainCompletion.js]
-[browser_urlbar_autoFill_backspaced.js]
-[browser_urlbar_blanking.js]
-support-files =
- file_blank_but_not_blank.html
-[browser_urlbar_locationchange_urlbar_edit_dos.js]
-support-files =
- file_urlbar_edit_dos.html
-[browser_urlbar_searchsettings.js]
-[browser_urlbar_stop_pending.js]
-support-files =
- slow-page.sjs
-[browser_urlbar_remoteness_switch.js]
-run-if = e10s
-[browser_urlHighlight.js]
-[browser_wyciwyg_urlbarCopying.js]
-subsuite = clipboard
-support-files =
- test_wyciwyg_copying.html
diff --git a/browser/base/content/test/urlbar/browser_URLBarSetURI.js b/browser/base/content/test/urlbar/browser_URLBarSetURI.js
deleted file mode 100644
index ac8352f1a..000000000
--- a/browser/base/content/test/urlbar/browser_URLBarSetURI.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- // avoid prompting about phishing
- Services.prefs.setIntPref(phishyUserPassPref, 32);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(phishyUserPassPref);
- });
-
- nextTest();
-}
-
-const phishyUserPassPref = "network.http.phishy-userpass-length";
-
-function nextTest() {
- let test = tests.shift();
- if (test) {
- test(function () {
- executeSoon(nextTest);
- });
- } else {
- executeSoon(finish);
- }
-}
-
-var tests = [
- function revert(next) {
- loadTabInWindow(window, function (tab) {
- gURLBar.handleRevert();
- is(gURLBar.textValue, "example.com", "URL bar had user/pass stripped after reverting");
- gBrowser.removeTab(tab);
- next();
- });
- },
- function customize(next) {
- // Need to wait for delayedStartup for the customization part of the test,
- // since that's where BrowserToolboxCustomizeDone is set.
- BrowserTestUtils.openNewBrowserWindow().then(function(win) {
- loadTabInWindow(win, function () {
- openToolbarCustomizationUI(function () {
- closeToolbarCustomizationUI(function () {
- is(win.gURLBar.textValue, "example.com", "URL bar had user/pass stripped after customize");
- win.close();
- next();
- }, win);
- }, win);
- });
- });
- },
- function pageloaderror(next) {
- loadTabInWindow(window, function (tab) {
- // Load a new URL and then immediately stop it, to simulate a page load
- // error.
- tab.linkedBrowser.loadURI("http://test1.example.com");
- tab.linkedBrowser.stop();
- is(gURLBar.textValue, "example.com", "URL bar had user/pass stripped after load error");
- gBrowser.removeTab(tab);
- next();
- });
- }
-];
-
-function loadTabInWindow(win, callback) {
- info("Loading tab");
- let url = "http://user:pass@example.com/";
- let tab = win.gBrowser.selectedTab = win.gBrowser.addTab(url);
- BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, url).then(() => {
- info("Tab loaded");
- is(win.gURLBar.textValue, "example.com", "URL bar had user/pass stripped initially");
- callback(tab);
- }, true);
-}
-
-function openToolbarCustomizationUI(aCallback, aBrowserWin) {
- if (!aBrowserWin)
- aBrowserWin = window;
-
- aBrowserWin.gCustomizeMode.enter();
-
- aBrowserWin.gNavToolbox.addEventListener("customizationready", function UI_loaded() {
- aBrowserWin.gNavToolbox.removeEventListener("customizationready", UI_loaded);
- executeSoon(function() {
- aCallback(aBrowserWin)
- });
- });
-}
-
-function closeToolbarCustomizationUI(aCallback, aBrowserWin) {
- aBrowserWin.gNavToolbox.addEventListener("aftercustomization", function unloaded() {
- aBrowserWin.gNavToolbox.removeEventListener("aftercustomization", unloaded);
- executeSoon(aCallback);
- });
-
- aBrowserWin.gCustomizeMode.exit();
-}
-
diff --git a/browser/base/content/test/urlbar/browser_action_keyword.js b/browser/base/content/test/urlbar/browser_action_keyword.js
deleted file mode 100644
index 854a7b82f..000000000
--- a/browser/base/content/test/urlbar/browser_action_keyword.js
+++ /dev/null
@@ -1,119 +0,0 @@
-function* promise_first_result(inputText) {
- yield promiseAutocompleteResultPopup(inputText);
-
- let firstResult = gURLBar.popup.richlistbox.firstChild;
- return firstResult;
-}
-
-const TEST_URL = "http://mochi.test:8888/browser/browser/base/content/test/urlbar/print_postdata.sjs";
-
-add_task(function* setup() {
- yield PlacesUtils.keywords.insert({ keyword: "get",
- url: TEST_URL + "?q=%s" });
- yield PlacesUtils.keywords.insert({ keyword: "post",
- url: TEST_URL,
- postData: "q=%s" });
- registerCleanupFunction(function* () {
- yield PlacesUtils.keywords.remove("get");
- yield PlacesUtils.keywords.remove("post");
- while (gBrowser.tabs.length > 1) {
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
- });
-});
-
-add_task(function* get_keyword() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- let result = yield promise_first_result("get something");
- isnot(result, null, "Expect a keyword result");
-
- let types = new Set(result.getAttribute("type").split(/\s+/));
- Assert.ok(types.has("keyword"));
- is(result.getAttribute("actiontype"), "keyword", "Expect correct `actiontype` attribute");
- is(result.getAttribute("title"), "mochi.test:8888", "Expect correct title");
-
- // We need to make a real URI out of this to ensure it's normalised for
- // comparison.
- let uri = NetUtil.newURI(result.getAttribute("url"));
- is(uri.spec, PlacesUtils.mozActionURI("keyword",
- { url: TEST_URL + "?q=something",
- input: "get something"}),
- "Expect correct url");
-
- let titleHbox = result._titleText.parentNode.parentNode;
- ok(titleHbox.classList.contains("ac-title"), "Title hbox element sanity check");
- is_element_visible(titleHbox, "Title element should be visible");
- is(result._titleText.textContent, "mochi.test:8888: something",
- "Node should contain the name of the bookmark and query");
-
- let urlHbox = result._urlText.parentNode.parentNode;
- ok(urlHbox.classList.contains("ac-url"), "URL hbox element sanity check");
- is_element_hidden(urlHbox, "URL element should be hidden");
-
- let actionHbox = result._actionText.parentNode.parentNode;
- ok(actionHbox.classList.contains("ac-action"), "Action hbox element sanity check");
- is_element_visible(actionHbox, "Action element should be visible");
- is(result._actionText.textContent, "", "Action text should be empty");
-
- // Click on the result
- info("Normal click on result");
- let tabPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- EventUtils.synthesizeMouseAtCenter(result, {});
- yield tabPromise;
- is(tab.linkedBrowser.currentURI.spec, TEST_URL + "?q=something",
- "Tab should have loaded from clicking on result");
-
- // Middle-click on the result
- info("Middle-click on result");
- result = yield promise_first_result("get somethingmore");
- isnot(result, null, "Expect a keyword result");
- // We need to make a real URI out of this to ensure it's normalised for
- // comparison.
- uri = NetUtil.newURI(result.getAttribute("url"));
- is(uri.spec, PlacesUtils.mozActionURI("keyword",
- { url: TEST_URL + "?q=somethingmore",
- input: "get somethingmore" }),
- "Expect correct url");
-
- tabPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- EventUtils.synthesizeMouseAtCenter(result, {button: 1});
- let tabOpenEvent = yield tabPromise;
- let newTab = tabOpenEvent.target;
- yield BrowserTestUtils.browserLoaded(newTab.linkedBrowser);
- is(newTab.linkedBrowser.currentURI.spec,
- TEST_URL + "?q=somethingmore",
- "Tab should have loaded from middle-clicking on result");
-});
-
-
-add_task(function* post_keyword() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- let result = yield promise_first_result("post something");
- isnot(result, null, "Expect a keyword result");
-
- let types = new Set(result.getAttribute("type").split(/\s+/));
- Assert.ok(types.has("keyword"));
- is(result.getAttribute("actiontype"), "keyword", "Expect correct `actiontype` attribute");
- is(result.getAttribute("title"), "mochi.test:8888", "Expect correct title");
-
- is(result.getAttribute("url"),
- PlacesUtils.mozActionURI("keyword", { url: TEST_URL,
- input: "post something",
- "postData": "q=something" }),
- "Expect correct url");
-
- // Click on the result
- info("Normal click on result");
- let tabPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- EventUtils.synthesizeMouseAtCenter(result, {});
- yield tabPromise;
- is(tab.linkedBrowser.currentURI.spec, TEST_URL,
- "Tab should have loaded from clicking on result");
-
- let postData = yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- return content.document.body.textContent;
- });
- is(postData, "q=something", "post data was submitted correctly");
-});
diff --git a/browser/base/content/test/urlbar/browser_action_keyword_override.js b/browser/base/content/test/urlbar/browser_action_keyword_override.js
deleted file mode 100644
index f5a865678..000000000
--- a/browser/base/content/test/urlbar/browser_action_keyword_override.js
+++ /dev/null
@@ -1,40 +0,0 @@
-add_task(function*() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/?q=%s",
- title: "test" });
- yield PlacesUtils.keywords.insert({ keyword: "keyword",
- url: "http://example.com/?q=%s" })
-
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.remove(bm);
- });
-
- yield promiseAutocompleteResultPopup("keyword search");
- let result = gURLBar.popup.richlistbox.children[0];
-
- info("Before override");
- let titleHbox = result._titleText.parentNode.parentNode;
- ok(titleHbox.classList.contains("ac-title"), "Title hbox element sanity check");
- is_element_visible(titleHbox, "Title element should be visible");
-
- let urlHbox = result._urlText.parentNode.parentNode;
- ok(urlHbox.classList.contains("ac-url"), "URL hbox element sanity check");
- is_element_hidden(urlHbox, "URL element should be hidden");
-
- let actionHbox = result._actionText.parentNode.parentNode;
- ok(actionHbox.classList.contains("ac-action"), "Action hbox element sanity check");
- is_element_visible(actionHbox, "Action element should be visible");
- is(result._actionText.textContent, "", "Action text should be empty");
-
- info("During override");
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keydown" });
- is_element_visible(titleHbox, "Title element should be visible");
- is_element_hidden(urlHbox, "URL element should be hidden");
- is_element_visible(actionHbox, "Action element should be visible");
- is(result._actionText.textContent, "", "Action text should be empty");
-
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keyup" });
-
- gURLBar.popup.hidePopup();
- yield promisePopupHidden(gURLBar.popup);
-});
diff --git a/browser/base/content/test/urlbar/browser_action_searchengine.js b/browser/base/content/test/urlbar/browser_action_searchengine.js
deleted file mode 100644
index d2115abba..000000000
--- a/browser/base/content/test/urlbar/browser_action_searchengine.js
+++ /dev/null
@@ -1,36 +0,0 @@
-add_task(function* () {
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- registerCleanupFunction(() => {
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.removeEngine(engine);
-
- try {
- gBrowser.removeTab(tab);
- } catch (ex) { /* tab may have already been closed in case of failure */ }
-
- return PlacesTestUtils.clearHistory();
- });
-
- yield promiseAutocompleteResultPopup("open a search");
- let result = gURLBar.popup.richlistbox.firstChild;
-
- isnot(result, null, "Should have a result");
- is(result.getAttribute("url"),
- `moz-action:searchengine,{"engineName":"MozSearch","input":"open%20a%20search","searchQuery":"open%20a%20search"}`,
- "Result should be a moz-action: for the correct search engine");
- is(result.hasAttribute("image"), false, "Result shouldn't have an image attribute");
-
- let tabPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- result.click();
- yield tabPromise;
-
- is(gBrowser.selectedBrowser.currentURI.spec, "http://example.com/?q=open+a+search", "Correct URL should be loaded");
-});
diff --git a/browser/base/content/test/urlbar/browser_action_searchengine_alias.js b/browser/base/content/test/urlbar/browser_action_searchengine_alias.js
deleted file mode 100644
index 1967d178a..000000000
--- a/browser/base/content/test/urlbar/browser_action_searchengine_alias.js
+++ /dev/null
@@ -1,35 +0,0 @@
-add_task(function* () {
- let iconURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC";
- Services.search.addEngineWithDetails("MozSearch", iconURI, "moz", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- registerCleanupFunction(() => {
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.removeEngine(engine);
-
- try {
- gBrowser.removeTab(tab);
- } catch (ex) { /* tab may have already been closed in case of failure */ }
-
- return PlacesTestUtils.clearHistory();
- });
-
- yield promiseAutocompleteResultPopup("moz open a search");
-
- let result = gURLBar.popup.richlistbox.children[0];
- ok(result.hasAttribute("image"), "Result should have an image attribute");
- ok(result.getAttribute("image") === engine.iconURI.spec,
- "Image attribute should have the search engine's icon");
-
- let tabPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- EventUtils.synthesizeKey("VK_RETURN", { });
- yield tabPromise;
-
- is(gBrowser.selectedBrowser.currentURI.spec, "http://example.com/?q=open+a+search");
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js b/browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js
deleted file mode 100644
index a27f9672e..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_a11y_label.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const SUGGEST_ALL_PREF = "browser.search.suggest.enabled";
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-add_task(function* switchToTab() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:about");
-
- yield promiseAutocompleteResultPopup("% about");
-
- ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results");
- let result = gURLBar.popup.richlistbox.children[1];
- is(result.getAttribute("type"), "switchtab", "Expect right type attribute");
- is(result.label, "about:about about:about Tab", "Result a11y label should be: <title> <url> Tab");
-
- gURLBar.popup.hidePopup();
- yield promisePopupHidden(gURLBar.popup);
- gBrowser.removeTab(tab);
-});
-
-add_task(function* searchSuggestions() {
- let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- let oldCurrentEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
- registerCleanupFunction(function () {
- Services.search.currentEngine = oldCurrentEngine;
- Services.prefs.clearUserPref(SUGGEST_ALL_PREF);
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
- });
-
- yield promiseAutocompleteResultPopup("foo");
- // Don't assume that the search doesn't match history or bookmarks left around
- // by earlier tests.
- Assert.ok(gURLBar.popup.richlistbox.children.length >= 3,
- "Should get at least heuristic result + two search suggestions");
- // The first expected search is the search term itself since the heuristic
- // result will come before the search suggestions.
- let expectedSearches = [
- "foo",
- "foofoo",
- "foobar",
- ];
- for (let child of gURLBar.popup.richlistbox.children) {
- if (child.getAttribute("type").split(/\s+/).indexOf("searchengine") >= 0) {
- Assert.ok(expectedSearches.length > 0);
- let suggestion = expectedSearches.shift();
- Assert.equal(child.label, suggestion + " browser_searchSuggestionEngine searchSuggestionEngine.xml Search",
- "Result label should be: <search term> <engine name> Search");
- }
- }
- Assert.ok(expectedSearches.length == 0);
- gURLBar.closePopup();
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_autoselect.js b/browser/base/content/test/urlbar/browser_autocomplete_autoselect.js
deleted file mode 100644
index e4e0daa8e..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_autoselect.js
+++ /dev/null
@@ -1,92 +0,0 @@
-const ONEOFF_URLBAR_PREF = "browser.urlbar.oneOffSearches";
-
-function repeat(limit, func) {
- for (let i = 0; i < limit; i++) {
- func(i);
- }
-}
-
-function is_selected(index) {
- is(gURLBar.popup.richlistbox.selectedIndex, index, `Item ${index + 1} should be selected`);
-
- // This is true because although both the listbox and the one-offs can have
- // selections, the test doesn't check that.
- is(gURLBar.popup.oneOffSearchButtons.selectedButton, null,
- "A result is selected, so the one-offs should not have a selection");
-}
-
-function is_selected_one_off(index) {
- is(gURLBar.popup.oneOffSearchButtons.selectedButtonIndex, index,
- "Expected one-off button should be selected");
-
- // This is true because although both the listbox and the one-offs can have
- // selections, the test doesn't check that.
- is(gURLBar.popup.richlistbox.selectedIndex, -1,
- "A one-off is selected, so the listbox should not have a selection");
-}
-
-add_task(function*() {
- let maxResults = Services.prefs.getIntPref("browser.urlbar.maxRichResults");
-
- Services.prefs.setBoolPref(ONEOFF_URLBAR_PREF, true);
- registerCleanupFunction(function* () {
- yield PlacesTestUtils.clearHistory();
- Services.prefs.clearUserPref(ONEOFF_URLBAR_PREF);
- });
-
- let visits = [];
- repeat(maxResults, i => {
- visits.push({
- uri: makeURI("http://example.com/autocomplete/?" + i),
- });
- });
- yield PlacesTestUtils.addVisits(visits);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
- yield promiseAutocompleteResultPopup("example.com/autocomplete");
-
- let popup = gURLBar.popup;
- let results = popup.richlistbox.children;
- is(results.length, maxResults,
- "Should get maxResults=" + maxResults + " results");
- is_selected(0);
-
- info("Key Down to select the next item");
- EventUtils.synthesizeKey("VK_DOWN", {});
- is_selected(1);
-
- info("Key Down maxResults-1 times should select the first one-off");
- repeat(maxResults - 1, () => EventUtils.synthesizeKey("VK_DOWN", {}));
- is_selected_one_off(0);
-
- info("Key Down numButtons-1 should select the last one-off");
- let numButtons =
- gURLBar.popup.oneOffSearchButtons.getSelectableButtons(true).length;
- repeat(numButtons - 1, () => EventUtils.synthesizeKey("VK_DOWN", {}));
- is_selected_one_off(numButtons - 1);
-
- info("Key Down twice more should select the second result");
- repeat(2, () => EventUtils.synthesizeKey("VK_DOWN", {}));
- is_selected(1);
-
- info("Key Down maxResults + numButtons times should wrap around");
- repeat(maxResults + numButtons,
- () => EventUtils.synthesizeKey("VK_DOWN", {}));
- is_selected(1);
-
- info("Key Up maxResults + numButtons times should wrap around the other way");
- repeat(maxResults + numButtons, () => EventUtils.synthesizeKey("VK_UP", {}));
- is_selected(1);
-
- info("Page Up will go up the list, but not wrap");
- EventUtils.synthesizeKey("VK_PAGE_UP", {})
- is_selected(0);
-
- info("Page Up again will wrap around to the end of the list");
- EventUtils.synthesizeKey("VK_PAGE_UP", {})
- is_selected(maxResults - 1);
-
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promisePopupHidden(gURLBar.popup);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_cursor.js b/browser/base/content/test/urlbar/browser_autocomplete_cursor.js
deleted file mode 100644
index 9cc2c6eac..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_cursor.js
+++ /dev/null
@@ -1,17 +0,0 @@
-add_task(function*() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
- yield promiseAutocompleteResultPopup("www.mozilla.org");
-
- gURLBar.selectTextRange(4, 4);
-
- is(gURLBar.popup.state, "open", "Popup should be open");
- is(gURLBar.popup.richlistbox.selectedIndex, 0, "Should have selected something");
-
- EventUtils.synthesizeKey("VK_RIGHT", {});
- yield promisePopupHidden(gURLBar.popup);
-
- is(gURLBar.selectionStart, 5, "Should have moved the cursor");
- is(gURLBar.selectionEnd, 5, "And not selected anything");
-
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_edit_completed.js b/browser/base/content/test/urlbar/browser_autocomplete_edit_completed.js
deleted file mode 100644
index 19db1a368..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_edit_completed.js
+++ /dev/null
@@ -1,48 +0,0 @@
-add_task(function*() {
- yield PlacesTestUtils.clearHistory();
-
- yield PlacesTestUtils.addVisits([
- { uri: makeURI("http://example.com/foo") },
- { uri: makeURI("http://example.com/foo/bar") },
- ]);
-
- registerCleanupFunction(function* () {
- yield PlacesTestUtils.clearHistory();
- });
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- gURLBar.focus();
-
- yield promiseAutocompleteResultPopup("http://example.com");
-
- let popup = gURLBar.popup;
- let list = popup.richlistbox;
- let initialIndex = list.selectedIndex;
-
- info("Key Down to select the next item.");
- EventUtils.synthesizeKey("VK_DOWN", {});
-
- let nextIndex = initialIndex + 1;
- let nextValue = gURLBar.controller.getFinalCompleteValueAt(nextIndex);
- is(list.selectedIndex, nextIndex, "The next item is selected.");
- is(gURLBar.value, nextValue, "The selected URL is completed.");
-
- info("Press backspace");
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- yield promiseSearchComplete();
-
- let editedValue = gURLBar.textValue;
- is(list.selectedIndex, initialIndex, "The initial index is selected again.");
- isnot(editedValue, nextValue, "The URL has changed.");
-
- let docLoad = waitForDocLoadAndStopIt("http://" + editedValue);
-
- info("Press return to load edited URL.");
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield Promise.all([
- promisePopupHidden(gURLBar.popup),
- docLoad,
- ]);
-
- gBrowser.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_enter_race.js b/browser/base/content/test/urlbar/browser_autocomplete_enter_race.js
deleted file mode 100644
index 4e3c8943c..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_enter_race.js
+++ /dev/null
@@ -1,122 +0,0 @@
-// The order of these tests matters!
-
-add_task(function* setup () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/?q=%s",
- title: "test" });
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.remove(bm);
- yield BrowserTestUtils.removeTab(tab);
- });
- yield PlacesUtils.keywords.insert({ keyword: "keyword",
- url: "http://example.com/?q=%s" });
- // Needs at least one success.
- ok(true, "Setup complete");
-});
-
-add_task(function* test_keyword() {
- yield promiseAutocompleteResultPopup("keyword bear");
- gURLBar.focus();
- EventUtils.synthesizeKey("d", {});
- EventUtils.synthesizeKey("VK_RETURN", {});
- info("wait for the page to load");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedTab.linkedBrowser,
- false, "http://example.com/?q=beard");
-});
-
-add_task(function* test_sametext() {
- yield promiseAutocompleteResultPopup("example.com", window, true);
-
- // Simulate re-entering the same text searched the last time. This may happen
- // through a copy paste, but clipboard handling is not much reliable, so just
- // fire an input event.
- info("synthesize input event");
- let event = document.createEvent("Events");
- event.initEvent("input", true, true);
- gURLBar.dispatchEvent(event);
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- info("wait for the page to load");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedTab.linkedBrowser,
- false, "http://example.com/");
-});
-
-add_task(function* test_after_empty_search() {
- yield promiseAutocompleteResultPopup("");
- gURLBar.focus();
- gURLBar.value = "e";
- EventUtils.synthesizeKey("x", {});
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- info("wait for the page to load");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedTab.linkedBrowser,
- false, "http://example.com/");
-});
-
-add_task(function* test_disabled_ac() {
- // Disable autocomplete.
- let suggestHistory = Preferences.get("browser.urlbar.suggest.history");
- Preferences.set("browser.urlbar.suggest.history", false);
- let suggestBookmarks = Preferences.get("browser.urlbar.suggest.bookmark");
- Preferences.set("browser.urlbar.suggest.bookmark", false);
- let suggestOpenPages = Preferences.get("browser.urlbar.suggest.openpage");
- Preferences.set("browser.urlbar.suggest.openpages", false);
-
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- let engine = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- function* cleanup() {
- Preferences.set("browser.urlbar.suggest.history", suggestHistory);
- Preferences.set("browser.urlbar.suggest.bookmark", suggestBookmarks);
- Preferences.set("browser.urlbar.suggest.openpage", suggestOpenPages);
-
- Services.search.currentEngine = originalEngine;
- let engine = Services.search.getEngineByName("MozSearch");
- if (engine) {
- Services.search.removeEngine(engine);
- }
- }
- registerCleanupFunction(cleanup);
-
- gURLBar.focus();
- gURLBar.value = "e";
- EventUtils.synthesizeKey("x", {});
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- info("wait for the page to load");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedTab.linkedBrowser,
- false, "http://example.com/?q=ex");
- yield cleanup();
-});
-
-add_task(function* test_delay() {
- const TIMEOUT = 10000;
- // Set a large delay.
- let delay = Preferences.get("browser.urlbar.delay");
- Preferences.set("browser.urlbar.delay", TIMEOUT);
-
- registerCleanupFunction(function* () {
- Preferences.set("browser.urlbar.delay", delay);
- });
-
- // This is needed to clear the current value, otherwise autocomplete may think
- // the user removed text from the end.
- let start = Date.now();
- yield promiseAutocompleteResultPopup("");
- Assert.ok((Date.now() - start) < TIMEOUT);
-
- start = Date.now();
- gURLBar.closePopup();
- gURLBar.focus();
- gURLBar.value = "e";
- EventUtils.synthesizeKey("x", {});
- EventUtils.synthesizeKey("VK_RETURN", {});
- info("wait for the page to load");
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedTab.linkedBrowser,
- false, "http://example.com/");
- Assert.ok((Date.now() - start) < TIMEOUT);
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js
deleted file mode 100644
index 8d608550b..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js
+++ /dev/null
@@ -1,15 +0,0 @@
-add_task(function*() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- let uri = NetUtil.newURI("http://bug1060642.example.com/beards/are/pretty/great");
- yield PlacesTestUtils.addVisits([{uri: uri, title: ""}]);
-
- yield promiseAutocompleteResultPopup("bug1060642");
- ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results");
- let result = gURLBar.popup.richlistbox.children[1];
- is(result._titleText.textContent, "bug1060642.example.com", "Result title should be as expected");
-
- gURLBar.popup.hidePopup();
- yield promisePopupHidden(gURLBar.popup);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js
deleted file mode 100644
index 8a69b4b44..000000000
--- a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js
+++ /dev/null
@@ -1,102 +0,0 @@
-add_task(function*() {
- registerCleanupFunction(() => {
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- });
-
- function* addTagItem(tagName) {
- let uri = NetUtil.newURI(`http://example.com/this/is/tagged/${tagName}`);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- `test ${tagName}`);
- PlacesUtils.tagging.tagURI(uri, [tagName]);
- yield PlacesTestUtils.addVisits([{uri: uri, title: `Test page with tag ${tagName}`}]);
- }
-
- // We use different tags for each part of the test, as otherwise the
- // autocomplete code tries to be smart by using the previously cached element
- // without updating it (since all parameters it knows about are the same).
-
- let testcases = [{
- description: "Test with suggest.bookmark=true",
- tagName: "tagtest1",
- prefs: {
- "suggest.bookmark": true,
- },
- input: "tagtest1",
- expected: {
- type: "bookmark",
- typeImageVisible: true,
- },
- }, {
- description: "Test with suggest.bookmark=false",
- tagName: "tagtest2",
- prefs: {
- "suggest.bookmark": false,
- },
- input: "tagtest2",
- expected: {
- type: "tag",
- typeImageVisible: false,
- },
- }, {
- description: "Test with suggest.bookmark=true (again)",
- tagName: "tagtest3",
- prefs: {
- "suggest.bookmark": true,
- },
- input: "tagtest3",
- expected: {
- type: "bookmark",
- typeImageVisible: true,
- },
- }, {
- description: "Test with bookmark restriction token",
- tagName: "tagtest4",
- prefs: {
- "suggest.bookmark": true,
- },
- input: "* tagtest4",
- expected: {
- type: "bookmark",
- typeImageVisible: true,
- },
- }, {
- description: "Test with history restriction token",
- tagName: "tagtest5",
- prefs: {
- "suggest.bookmark": true,
- },
- input: "^ tagtest5",
- expected: {
- type: "tag",
- typeImageVisible: false,
- },
- }];
-
- for (let testcase of testcases) {
- info(`Test case: ${testcase.description}`);
-
- yield addTagItem(testcase.tagName);
- for (let prefName of Object.keys(testcase.prefs)) {
- Services.prefs.setBoolPref(`browser.urlbar.${prefName}`, testcase.prefs[prefName]);
- }
-
- yield promiseAutocompleteResultPopup(testcase.input);
- let result = gURLBar.popup.richlistbox.children[1];
- ok(result && !result.collasped, "Should have result");
-
- is(result.getAttribute("type"), testcase.expected.type, "Result should have expected type");
-
- let typeIconStyle = window.getComputedStyle(result._typeIcon);
- let imageURL = typeIconStyle.listStyleImage;
- if (testcase.expected.typeImageVisible) {
- ok(/^url\(.+\)$/.test(imageURL), "Type image should be visible");
- } else {
- is(imageURL, "none", "Type image should be hidden");
- }
-
- gURLBar.popup.hidePopup();
- yield promisePopupHidden(gURLBar.popup);
- }
-});
diff --git a/browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js b/browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js
deleted file mode 100644
index 89f604491..000000000
--- a/browser/base/content/test/urlbar/browser_bug1003461-switchtab-override.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* 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/. */
-
-add_task(function* test_switchtab_override() {
- let testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-
- info("Opening first tab");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testURL);
-
- info("Opening and selecting second tab");
- let secondTab = gBrowser.selectedTab = gBrowser.addTab();
- registerCleanupFunction(() => {
- try {
- gBrowser.removeTab(tab);
- gBrowser.removeTab(secondTab);
- } catch (ex) { /* tabs may have already been closed in case of failure */ }
- });
-
- info("Wait for autocomplete")
- let deferred = Promise.defer();
- let onSearchComplete = gURLBar.onSearchComplete;
- registerCleanupFunction(() => {
- gURLBar.onSearchComplete = onSearchComplete;
- });
- gURLBar.onSearchComplete = function () {
- ok(gURLBar.popupOpen, "The autocomplete popup is correctly open");
- onSearchComplete.apply(gURLBar);
- deferred.resolve();
- }
-
- gURLBar.focus();
- gURLBar.value = "dummy_pag";
- EventUtils.synthesizeKey("e", {});
- yield deferred.promise;
-
- info("Select second autocomplete popup entry");
- EventUtils.synthesizeKey("VK_DOWN", {});
- ok(/moz-action:switchtab/.test(gURLBar.value), "switch to tab entry found");
-
- info("Override switch-to-tab");
- deferred = Promise.defer();
- // In case of failure this would switch tab.
- let onTabSelect = event => {
- deferred.reject(new Error("Should have overridden switch to tab"));
- };
- gBrowser.tabContainer.addEventListener("TabSelect", onTabSelect, false);
- registerCleanupFunction(() => {
- gBrowser.tabContainer.removeEventListener("TabSelect", onTabSelect, false);
- });
- // Otherwise it would load the page.
- BrowserTestUtils.browserLoaded(secondTab.linkedBrowser).then(deferred.resolve);
-
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keydown" });
- EventUtils.synthesizeKey("VK_RETURN", { });
- info(`gURLBar.value = ${gURLBar.value}`);
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keyup" });
- yield deferred.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js b/browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js
deleted file mode 100644
index 2d97ea07b..000000000
--- a/browser/base/content/test/urlbar/browser_bug1024133-switchtab-override-keynav.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* 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/. */
-
-add_task(function* test_switchtab_override_keynav() {
- let testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-
- info("Opening first tab");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testURL);
-
- info("Opening and selecting second tab");
- let secondTab = gBrowser.selectedTab = gBrowser.addTab();
- registerCleanupFunction(() => {
- try {
- gBrowser.removeTab(tab);
- gBrowser.removeTab(secondTab);
- } catch (ex) { /* tabs may have already been closed in case of failure */ }
- return PlacesTestUtils.clearHistory();
- });
-
- gURLBar.focus();
- gURLBar.value = "dummy_pag";
- EventUtils.synthesizeKey("e", {});
- yield promiseSearchComplete();
-
- info("Select second autocomplete popup entry");
- EventUtils.synthesizeKey("VK_DOWN", {});
- ok(/moz-action:switchtab/.test(gURLBar.value), "switch to tab entry found");
-
- info("Shift+left on switch-to-tab entry");
-
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keydown" });
- EventUtils.synthesizeKey("VK_LEFT", { shiftKey: true });
- EventUtils.synthesizeKey("VK_SHIFT", { type: "keyup" });
-
- ok(!/moz-action:switchtab/.test(gURLBar.inputField.value), "switch to tab should be hidden");
-});
diff --git a/browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js b/browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js
deleted file mode 100644
index 9e779ade1..000000000
--- a/browser/base/content/test/urlbar/browser_bug1025195_switchToTabHavingURI_aOpenParams.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* 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/. */
-
-add_task(function* test_ignoreFragment() {
- let tabRefAboutHome =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home#1");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
- let numTabsAtStart = gBrowser.tabs.length;
-
- switchTab("about:home#1", true);
- switchTab("about:mozilla", true);
-
- let hashChangePromise = ContentTask.spawn(tabRefAboutHome.linkedBrowser, null, function* () {
- yield ContentTaskUtils.waitForEvent(this, "hashchange", false);
- });
- switchTab("about:home#2", true, { ignoreFragment: "whenComparingAndReplace" });
- is(tabRefAboutHome, gBrowser.selectedTab, "The same about:home tab should be switched to");
- yield hashChangePromise;
- is(gBrowser.currentURI.ref, "2", "The ref should be updated to the new ref");
- switchTab("about:mozilla", true);
- switchTab("about:home#3", true, { ignoreFragment: "whenComparing" });
- is(tabRefAboutHome, gBrowser.selectedTab, "The same about:home tab should be switched to");
- is(gBrowser.currentURI.ref, "2", "The ref should be unchanged since the fragment is only ignored when comparing");
- switchTab("about:mozilla", true);
- switchTab("about:home#1", false);
- isnot(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should not be initial about:blank tab");
- is(gBrowser.tabs.length, numTabsAtStart + 1, "Should have one new tab opened");
- switchTab("about:mozilla", true);
- switchTab("about:home", true, {ignoreFragment: "whenComparingAndReplace"});
- yield BrowserTestUtils.waitForCondition(function() {
- return tabRefAboutHome.linkedBrowser.currentURI.spec == "about:home";
- });
- is(tabRefAboutHome.linkedBrowser.currentURI.spec, "about:home", "about:home shouldn't have hash");
- switchTab("about:about", false, { ignoreFragment: "whenComparingAndReplace" });
- cleanupTestTabs();
-});
-
-add_task(function* test_ignoreQueryString() {
- let tabRefAboutHome =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- switchTab("about:home?hello=firefox", true);
- switchTab("about:home?hello=firefoxos", false);
- // Remove the last opened tab to test ignoreQueryString option.
- gBrowser.removeCurrentTab();
- switchTab("about:home?hello=firefoxos", true, { ignoreQueryString: true });
- is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
- is(gBrowser.currentURI.spec, "about:home?hello=firefox", "The spec should NOT be updated to the new query string");
- cleanupTestTabs();
-});
-
-add_task(function* test_replaceQueryString() {
- let tabRefAboutHome =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- switchTab("about:home", false);
- switchTab("about:home?hello=firefox", true);
- switchTab("about:home?hello=firefoxos", false);
- // Remove the last opened tab to test replaceQueryString option.
- gBrowser.removeCurrentTab();
- switchTab("about:home?hello=firefoxos", true, { replaceQueryString: true });
- is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
- // Wait for the tab to load the new URI spec.
- yield BrowserTestUtils.browserLoaded(tabRefAboutHome.linkedBrowser);
- is(gBrowser.currentURI.spec, "about:home?hello=firefoxos", "The spec should be updated to the new spec");
- cleanupTestTabs();
-});
-
-add_task(function* test_replaceQueryStringAndFragment() {
- let tabRefAboutHome =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox#aaa");
- let tabRefAboutMozilla =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla?hello=firefoxos#aaa");
-
- switchTab("about:home", false);
- gBrowser.removeCurrentTab();
- switchTab("about:home?hello=firefox#aaa", true);
- is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
- switchTab("about:mozilla?hello=firefox#bbb", true, { replaceQueryString: true, ignoreFragment: "whenComparingAndReplace" });
- is(tabRefAboutMozilla, gBrowser.selectedTab, "Selected tab should be the initial about:mozilla tab");
- switchTab("about:home?hello=firefoxos#bbb", true, { ignoreQueryString: true, ignoreFragment: "whenComparingAndReplace" });
- is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
- cleanupTestTabs();
-});
-
-add_task(function* test_ignoreQueryStringIgnoresFragment() {
- let tabRefAboutHome =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home?hello=firefox#aaa");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla?hello=firefoxos#aaa");
-
- switchTab("about:home?hello=firefox#bbb", false, { ignoreQueryString: true });
- gBrowser.removeCurrentTab();
- switchTab("about:home?hello=firefoxos#aaa", true, { ignoreQueryString: true });
- is(tabRefAboutHome, gBrowser.selectedTab, "Selected tab should be the initial about:home tab");
- cleanupTestTabs();
-});
-
-// Begin helpers
-
-function cleanupTestTabs() {
- while (gBrowser.tabs.length > 1)
- gBrowser.removeCurrentTab();
-}
-
-function switchTab(aURI, aShouldFindExistingTab, aOpenParams = {}) {
- // Build the description before switchToTabHavingURI deletes the object properties.
- let msg = `Should switch to existing ${aURI} tab if one existed, ` +
- `${(aOpenParams.ignoreFragment ? "ignoring" : "including")} fragment portion, `;
- if (aOpenParams.replaceQueryString) {
- msg += "replacing";
- } else if (aOpenParams.ignoreQueryString) {
- msg += "ignoring";
- } else {
- msg += "including";
- }
- msg += " query string.";
- let tabFound = switchToTabHavingURI(aURI, true, aOpenParams);
- is(tabFound, aShouldFindExistingTab, msg);
-}
-
-registerCleanupFunction(cleanupTestTabs);
diff --git a/browser/base/content/test/urlbar/browser_bug1070778.js b/browser/base/content/test/urlbar/browser_bug1070778.js
deleted file mode 100644
index ab88d04d8..000000000
--- a/browser/base/content/test/urlbar/browser_bug1070778.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function is_selected(index) {
- is(gURLBar.popup.richlistbox.selectedIndex, index, `Item ${index + 1} should be selected`);
-}
-
-add_task(function*() {
- let bookmarks = [];
- bookmarks.push((yield PlacesUtils.bookmarks
- .insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/?q=%s",
- title: "test" })));
- yield PlacesUtils.keywords.insert({ keyword: "keyword",
- url: "http://example.com/?q=%s" });
-
- // This item only needed so we can select the keyword item, select something
- // else, then select the keyword item again.
- bookmarks.push((yield PlacesUtils.bookmarks
- .insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/keyword",
- title: "keyword abc" })));
-
- registerCleanupFunction(function* () {
- for (let bm of bookmarks) {
- yield PlacesUtils.bookmarks.remove(bm);
- }
- });
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
- yield promiseAutocompleteResultPopup("keyword a");
-
- // First item should already be selected
- is_selected(0);
- // Select next one (important!)
- EventUtils.synthesizeKey("VK_DOWN", {});
- is_selected(1);
- // Re-select keyword item
- EventUtils.synthesizeKey("VK_UP", {});
- is_selected(0);
-
- EventUtils.synthesizeKey("b", {});
- yield promiseSearchComplete();
-
- is(gURLBar.textValue, "keyword ab", "urlbar should have expected input");
-
- let result = gURLBar.popup.richlistbox.firstChild;
- isnot(result, null, "Should have first item");
- let uri = NetUtil.newURI(result.getAttribute("url"));
- is(uri.spec, PlacesUtils.mozActionURI("keyword", {url: "http://example.com/?q=ab", input: "keyword ab"}), "Expect correct url");
-
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promisePopupHidden(gURLBar.popup);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js b/browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js
deleted file mode 100644
index d165d7304..000000000
--- a/browser/base/content/test/urlbar/browser_bug1104165-switchtab-decodeuri.js
+++ /dev/null
@@ -1,29 +0,0 @@
-add_task(function* test_switchtab_decodeuri() {
- info("Opening first tab");
- const TEST_URL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html#test%7C1";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
-
- info("Opening and selecting second tab");
- gBrowser.selectedTab = gBrowser.addTab();
-
- info("Wait for autocomplete")
- yield promiseAutocompleteResultPopup("dummy_page");
-
- info("Select autocomplete popup entry");
- EventUtils.synthesizeKey("VK_DOWN", {});
- ok(gURLBar.value.startsWith("moz-action:switchtab"), "switch to tab entry found");
-
- info("switch-to-tab");
- yield new Promise((resolve, reject) => {
- // In case of success it should switch tab.
- gBrowser.tabContainer.addEventListener("TabSelect", function select() {
- gBrowser.tabContainer.removeEventListener("TabSelect", select, false);
- is(gBrowser.selectedTab, tab, "Should have switched to the right tab");
- resolve();
- }, false);
- EventUtils.synthesizeKey("VK_RETURN", { });
- });
-
- gBrowser.removeCurrentTab();
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/browser/base/content/test/urlbar/browser_bug1225194-remotetab.js b/browser/base/content/test/urlbar/browser_bug1225194-remotetab.js
deleted file mode 100644
index 3b4a44e76..000000000
--- a/browser/base/content/test/urlbar/browser_bug1225194-remotetab.js
+++ /dev/null
@@ -1,16 +0,0 @@
-add_task(function* test_remotetab_opens() {
- const url = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
- yield BrowserTestUtils.withNewTab({url: "about:robots", gBrowser}, function* () {
- // Set the urlbar to include the moz-action
- gURLBar.value = "moz-action:remotetab," + JSON.stringify({ url });
- // Focus the urlbar so we can press enter
- gURLBar.focus();
-
- // The URL is going to open in the current tab as it is currently about:blank
- let promiseTabLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield promiseTabLoaded;
-
- Assert.equal(gBrowser.selectedTab.linkedBrowser.currentURI.spec, url, "correct URL loaded");
- });
-});
diff --git a/browser/base/content/test/urlbar/browser_bug304198.js b/browser/base/content/test/urlbar/browser_bug304198.js
deleted file mode 100644
index dc8d39fae..000000000
--- a/browser/base/content/test/urlbar/browser_bug304198.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/* 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/. */
-
-add_task(function* () {
- let charsToDelete, deletedURLTab, fullURLTab, partialURLTab, testPartialURL, testURL;
-
- charsToDelete = 5;
- deletedURLTab = gBrowser.addTab();
- fullURLTab = gBrowser.addTab();
- partialURLTab = gBrowser.addTab();
- testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-
- let loaded1 = BrowserTestUtils.browserLoaded(deletedURLTab.linkedBrowser, testURL);
- let loaded2 = BrowserTestUtils.browserLoaded(fullURLTab.linkedBrowser, testURL);
- let loaded3 = BrowserTestUtils.browserLoaded(partialURLTab.linkedBrowser, testURL);
- deletedURLTab.linkedBrowser.loadURI(testURL);
- fullURLTab.linkedBrowser.loadURI(testURL);
- partialURLTab.linkedBrowser.loadURI(testURL);
- yield Promise.all([loaded1, loaded2, loaded3]);
-
- testURL = gURLBar.trimValue(testURL);
- testPartialURL = testURL.substr(0, (testURL.length - charsToDelete));
-
- function cleanUp() {
- gBrowser.removeTab(fullURLTab);
- gBrowser.removeTab(partialURLTab);
- gBrowser.removeTab(deletedURLTab);
- }
-
- function* cycleTabs() {
- yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after switching back to fullURLTab');
-
- yield BrowserTestUtils.switchTab(gBrowser, partialURLTab);
- is(gURLBar.textValue, testPartialURL, 'gURLBar.textValue should be testPartialURL after switching back to partialURLTab');
- yield BrowserTestUtils.switchTab(gBrowser, deletedURLTab);
- is(gURLBar.textValue, '', 'gURLBar.textValue should be "" after switching back to deletedURLTab');
-
- yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after switching back to fullURLTab');
- }
-
- function urlbarBackspace() {
- return new Promise((resolve, reject) => {
- gBrowser.selectedBrowser.focus();
- gURLBar.addEventListener("input", function () {
- gURLBar.removeEventListener("input", arguments.callee, false);
- resolve();
- }, false);
- gURLBar.focus();
- if (gURLBar.selectionStart == gURLBar.selectionEnd) {
- gURLBar.selectionStart = gURLBar.selectionEnd = gURLBar.textValue.length;
- }
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- });
- }
-
- function* prepareDeletedURLTab() {
- yield BrowserTestUtils.switchTab(gBrowser, deletedURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to deletedURLTab');
-
- // simulate the user removing the whole url from the location bar
- gPrefService.setBoolPref("browser.urlbar.clickSelectsAll", true);
-
- yield urlbarBackspace();
- is(gURLBar.textValue, "", 'gURLBar.textValue should be "" (just set)');
- if (gPrefService.prefHasUserValue("browser.urlbar.clickSelectsAll")) {
- gPrefService.clearUserPref("browser.urlbar.clickSelectsAll");
- }
- }
-
- function* prepareFullURLTab() {
- yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to fullURLTab');
- }
-
- function* preparePartialURLTab() {
- yield BrowserTestUtils.switchTab(gBrowser, partialURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to partialURLTab');
-
- // simulate the user removing part of the url from the location bar
- gPrefService.setBoolPref("browser.urlbar.clickSelectsAll", false);
-
- let deleted = 0;
- while (deleted < charsToDelete) {
- yield urlbarBackspace(arguments.callee);
- deleted++;
- }
-
- is(gURLBar.textValue, testPartialURL, "gURLBar.textValue should be testPartialURL (just set)");
- if (gPrefService.prefHasUserValue("browser.urlbar.clickSelectsAll")) {
- gPrefService.clearUserPref("browser.urlbar.clickSelectsAll");
- }
- }
-
- // prepare the three tabs required by this test
-
- // First tab
- yield* prepareFullURLTab();
- yield* preparePartialURLTab();
- yield* prepareDeletedURLTab();
-
- // now cycle the tabs and make sure everything looks good
- yield* cycleTabs();
- cleanUp();
-});
-
-
diff --git a/browser/base/content/test/urlbar/browser_bug556061.js b/browser/base/content/test/urlbar/browser_bug556061.js
deleted file mode 100644
index 4c6ac5bf5..000000000
--- a/browser/base/content/test/urlbar/browser_bug556061.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* 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/. */
-
-var testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-var testActionURL = "moz-action:switchtab," + JSON.stringify({url: testURL});
-testURL = gURLBar.trimValue(testURL);
-var testTab;
-
-function runNextTest() {
- if (tests.length) {
- let t = tests.shift();
- waitForClipboard(t.expected, t.setup, function() {
- t.success();
- runNextTest();
- }, cleanup);
- }
- else {
- cleanup();
- }
-}
-
-function cleanup() {
- gBrowser.removeTab(testTab);
- finish();
-}
-
-var tests = [
- {
- expected: testURL,
- setup: function() {
- gURLBar.value = testActionURL;
- gURLBar.valueIsTyped = true;
- is(gURLBar.value, testActionURL, "gURLBar starts with the correct real value");
- is(gURLBar.textValue, testURL, "gURLBar starts with the correct display value");
-
- // Focus the urlbar so we can select it all & copy
- gURLBar.focus();
- gURLBar.select();
- goDoCommand("cmd_copy");
- },
- success: function() {
- is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying");
- }
- },
- {
- expected: testURL.substring(0, 10),
- setup: function() {
- // Set selectionStart/End manually and make sure it matches the substring
- gURLBar.selectionStart = 0;
- gURLBar.selectionEnd = 10;
- goDoCommand("cmd_copy");
- },
- success: function() {
- is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying");
- }
- },
- {
- expected: testURL,
- setup: function() {
- // Setup for cut test...
- // Select all
- gURLBar.select();
- goDoCommand("cmd_cut");
- },
- success: function() {
- is(gURLBar.value, "", "gURLBar.value is now empty");
- }
- },
- {
- expected: testURL.substring(testURL.length - 10, testURL.length),
- setup: function() {
- // Reset urlbar value
- gURLBar.value = testActionURL;
- gURLBar.valueIsTyped = true;
- // Sanity check that we have the right value
- is(gURLBar.value, testActionURL, "gURLBar starts with the correct real value");
- is(gURLBar.textValue, testURL, "gURLBar starts with the correct display value");
-
- // Now just select part of the value & cut that.
- gURLBar.selectionStart = testURL.length - 10;
- gURLBar.selectionEnd = testURL.length;
- goDoCommand("cmd_cut");
- },
- success: function() {
- is(gURLBar.value, testURL.substring(0, testURL.length - 10), "gURLBar.value has the correct value");
- }
- }
-];
-
-function test() {
- waitForExplicitFinish();
- testTab = gBrowser.addTab();
- gBrowser.selectedTab = testTab;
-
- // Kick off the testing
- runNextTest();
-}
diff --git a/browser/base/content/test/urlbar/browser_bug562649.js b/browser/base/content/test/urlbar/browser_bug562649.js
deleted file mode 100644
index f56e430ee..000000000
--- a/browser/base/content/test/urlbar/browser_bug562649.js
+++ /dev/null
@@ -1,24 +0,0 @@
-function test() {
- const URI = "data:text/plain,bug562649";
- browserDOMWindow.openURI(makeURI(URI),
- null,
- Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
- Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
-
- is(gBrowser.userTypedValue, URI, "userTypedValue matches test URI");
- is(gURLBar.value, URI, "location bar value matches test URI");
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.removeCurrentTab({ skipPermitUnload: true });
- is(gBrowser.userTypedValue, URI, "userTypedValue matches test URI after switching tabs");
- is(gURLBar.value, URI, "location bar value matches test URI after switching tabs");
-
- waitForExplicitFinish();
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => {
- is(gBrowser.userTypedValue, null, "userTypedValue is null as the page has loaded");
- is(gURLBar.value, URI, "location bar value matches test URI as the page has loaded");
-
- gBrowser.removeCurrentTab({ skipPermitUnload: true });
- finish();
- });
-}
diff --git a/browser/base/content/test/urlbar/browser_bug623155.js b/browser/base/content/test/urlbar/browser_bug623155.js
deleted file mode 100644
index dd6ff8c85..000000000
--- a/browser/base/content/test/urlbar/browser_bug623155.js
+++ /dev/null
@@ -1,137 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const REDIRECT_FROM = "https://example.com/browser/browser/base/content/test/urlbar/" +
- "redirect_bug623155.sjs";
-
-const REDIRECT_TO = "https://www.bank1.com/"; // Bad-cert host.
-
-function isRedirectedURISpec(aURISpec) {
- return isRedirectedURI(Services.io.newURI(aURISpec, null, null));
-}
-
-function isRedirectedURI(aURI) {
- // Compare only their before-hash portion.
- return Services.io.newURI(REDIRECT_TO, null, null)
- .equalsExceptRef(aURI);
-}
-
-/*
- Test.
-
-1. Load
-https://example.com/browser/browser/base/content/test/urlbar/redirect_bug623155.sjs#BG
- in a background tab.
-
-2. The redirected URI is <https://www.bank1.com/#BG>, which displayes a cert
- error page.
-
-3. Switch the tab to foreground.
-
-4. Check the URLbar's value, expecting <https://www.bank1.com/#BG>
-
-5. Load
-https://example.com/browser/browser/base/content/test/urlbar/redirect_bug623155.sjs#FG
- in the foreground tab.
-
-6. The redirected URI is <https://www.bank1.com/#FG>. And this is also
- a cert-error page.
-
-7. Check the URLbar's value, expecting <https://www.bank1.com/#FG>
-
-8. End.
-
- */
-
-var gNewTab;
-
-function test() {
- waitForExplicitFinish();
-
- // Load a URI in the background.
- gNewTab = gBrowser.addTab(REDIRECT_FROM + "#BG");
- gBrowser.getBrowserForTab(gNewTab)
- .webProgress
- .addProgressListener(gWebProgressListener,
- Components.interfaces.nsIWebProgress
- .NOTIFY_LOCATION);
-}
-
-var gWebProgressListener = {
- QueryInterface: function(aIID) {
- if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
- aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
- aIID.equals(Components.interfaces.nsISupports))
- return this;
- throw Components.results.NS_NOINTERFACE;
- },
-
- // ---------------------------------------------------------------------------
- // NOTIFY_LOCATION mode should work fine without these methods.
- //
- // onStateChange: function() {},
- // onStatusChange: function() {},
- // onProgressChange: function() {},
- // onSecurityChange: function() {},
- // ----------------------------------------------------------------------------
-
- onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
- if (!aRequest) {
- // This is bug 673752, or maybe initial "about:blank".
- return;
- }
-
- ok(gNewTab, "There is a new tab.");
- ok(isRedirectedURI(aLocation),
- "onLocationChange catches only redirected URI.");
-
- if (aLocation.ref == "BG") {
- // This is background tab's request.
- isnot(gNewTab, gBrowser.selectedTab, "This is a background tab.");
- } else if (aLocation.ref == "FG") {
- // This is foreground tab's request.
- is(gNewTab, gBrowser.selectedTab, "This is a foreground tab.");
- }
- else {
- // We shonuld not reach here.
- ok(false, "This URI hash is not expected:" + aLocation.ref);
- }
-
- let isSelectedTab = gNewTab.selected;
- setTimeout(delayed, 0, isSelectedTab);
- }
-};
-
-function delayed(aIsSelectedTab) {
- // Switch tab and confirm URL bar.
- if (!aIsSelectedTab) {
- gBrowser.selectedTab = gNewTab;
- }
-
- let currentURI = gBrowser.selectedBrowser.currentURI.spec;
- ok(isRedirectedURISpec(currentURI),
- "The content area is redirected. aIsSelectedTab:" + aIsSelectedTab);
- is(gURLBar.value, currentURI,
- "The URL bar shows the content URI. aIsSelectedTab:" + aIsSelectedTab);
-
- if (!aIsSelectedTab) {
- // If this was a background request, go on a foreground request.
- gBrowser.selectedBrowser.loadURI(REDIRECT_FROM + "#FG");
- }
- else {
- // Othrewise, nothing to do remains.
- finish();
- }
-}
-
-/* Cleanup */
-registerCleanupFunction(function() {
- if (gNewTab) {
- gBrowser.getBrowserForTab(gNewTab)
- .webProgress
- .removeProgressListener(gWebProgressListener);
-
- gBrowser.removeTab(gNewTab);
- }
- gNewTab = null;
-});
diff --git a/browser/base/content/test/urlbar/browser_bug783614.js b/browser/base/content/test/urlbar/browser_bug783614.js
deleted file mode 100644
index ebc62e8fa..000000000
--- a/browser/base/content/test/urlbar/browser_bug783614.js
+++ /dev/null
@@ -1,13 +0,0 @@
-/* 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/. */
-
-function test() {
- gURLBar.focus();
- gURLBar.inputField.value = "https://example.com/";
- gURLBar.selectionStart = 4;
- gURLBar.selectionEnd = 5;
- goDoCommand("cmd_cut");
- is(gURLBar.inputField.value, "http://example.com/", "location bar value after cutting 's' from https");
- gURLBar.handleRevert();
-}
diff --git a/browser/base/content/test/urlbar/browser_canonizeURL.js b/browser/base/content/test/urlbar/browser_canonizeURL.js
deleted file mode 100644
index 59ab54ca0..000000000
--- a/browser/base/content/test/urlbar/browser_canonizeURL.js
+++ /dev/null
@@ -1,42 +0,0 @@
-add_task(function*() {
- let testcases = [
- ["example", "http://www.example.net/", { shiftKey: true }],
- // Check that a direct load is not overwritten by a previous canonization.
- ["http://example.com/test/", "http://example.com/test/", {}],
- ["ex-ample", "http://www.ex-ample.net/", { shiftKey: true }],
- [" example ", "http://www.example.net/", { shiftKey: true }],
- [" example/foo ", "http://www.example.net/foo", { shiftKey: true }],
- [" example/foo bar ", "http://www.example.net/foo%20bar", { shiftKey: true }],
- ["example.net", "http://example.net/", { shiftKey: true }],
- ["http://example", "http://example/", { shiftKey: true }],
- ["example:8080", "http://example:8080/", { shiftKey: true }],
- ["ex-ample.foo", "http://ex-ample.foo/", { shiftKey: true }],
- ["example.foo/bar ", "http://example.foo/bar", { shiftKey: true }],
- ["1.1.1.1", "http://1.1.1.1/", { shiftKey: true }],
- ["ftp://example", "ftp://example/", { shiftKey: true }],
- ["ftp.example.bar", "http://ftp.example.bar/", { shiftKey: true }],
- ["ex ample", Services.search.defaultEngine.getSubmission("ex ample", null, "keyword").uri.spec, { shiftKey: true }],
- ];
-
- // Disable autoFill for this test, since it could mess up the results.
- let autoFill = Preferences.get("browser.urlbar.autoFill");
- Preferences.set("browser.urlbar.autoFill", false);
- registerCleanupFunction(() => {
- Preferences.set("browser.urlbar.autoFill", autoFill);
- });
-
- for (let [inputValue, expectedURL, options] of testcases) {
- let promiseLoad = waitForDocLoadAndStopIt(expectedURL);
- gURLBar.focus();
- if (Object.keys(options).length > 0) {
- gURLBar.selectionStart = gURLBar.selectionEnd =
- gURLBar.inputField.value.length;
- gURLBar.inputField.value = inputValue.slice(0, -1);
- EventUtils.synthesizeKey(inputValue.slice(-1), {});
- } else {
- gURLBar.textValue = inputValue;
- }
- EventUtils.synthesizeKey("VK_RETURN", options);
- yield promiseLoad;
- }
-});
diff --git a/browser/base/content/test/urlbar/browser_dragdropURL.js b/browser/base/content/test/urlbar/browser_dragdropURL.js
deleted file mode 100644
index ec2906700..000000000
--- a/browser/base/content/test/urlbar/browser_dragdropURL.js
+++ /dev/null
@@ -1,15 +0,0 @@
-"use strict";
-
-const TEST_URL = "data:text/html,a test page";
-const DRAG_URL = "http://www.example.com/";
-
-add_task(function* checkURLBarUpdateForDrag() {
- yield BrowserTestUtils.withNewTab(TEST_URL, function* (browser) {
- // Have to use something other than the URL bar as a source, so picking the
- // downloads button somewhat arbitrarily:
- EventUtils.synthesizeDrop(document.getElementById("downloads-button"), gURLBar,
- [[{type: "text/plain", data: DRAG_URL}]], "copy", window);
- is(gURLBar.value, TEST_URL, "URL bar value should not have changed");
- is(gBrowser.selectedBrowser.userTypedValue, null, "Stored URL bar value should not have changed");
- });
-});
diff --git a/browser/base/content/test/urlbar/browser_locationBarCommand.js b/browser/base/content/test/urlbar/browser_locationBarCommand.js
deleted file mode 100644
index 935bdf758..000000000
--- a/browser/base/content/test/urlbar/browser_locationBarCommand.js
+++ /dev/null
@@ -1,218 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const TEST_VALUE = "example.com";
-const START_VALUE = "example.org";
-
-add_task(function* setup() {
- Services.prefs.setBoolPref("browser.altClickSave", true);
-
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.altClickSave");
- });
-});
-
-add_task(function* alt_left_click_test() {
- info("Running test: Alt left click");
-
- // Monkey patch saveURL() to avoid dealing with file save code paths.
- let oldSaveURL = saveURL;
- let saveURLPromise = new Promise(resolve => {
- saveURL = () => {
- // Restore old saveURL() value.
- saveURL = oldSaveURL;
- resolve();
- };
- });
-
- triggerCommand(true, {altKey: true});
-
- yield saveURLPromise;
- ok(true, "SaveURL was called");
- is(gURLBar.value, "", "Urlbar reverted to original value");
-});
-
-add_task(function* shift_left_click_test() {
- info("Running test: Shift left click");
-
- let newWindowPromise = BrowserTestUtils.waitForNewWindow();
- triggerCommand(true, {shiftKey: true});
- let win = yield newWindowPromise;
-
- // Wait for the initial browser to load.
- let browser = win.gBrowser.selectedBrowser;
- let destinationURL = "http://" + TEST_VALUE + "/";
- yield Promise.all([
- BrowserTestUtils.browserLoaded(browser),
- BrowserTestUtils.waitForLocationChange(win.gBrowser, destinationURL)
- ]);
-
- info("URL should be loaded in a new window");
- is(gURLBar.value, "", "Urlbar reverted to original value");
- yield promiseCheckChildNoFocusedElement(gBrowser.selectedBrowser);
- is(document.activeElement, gBrowser.selectedBrowser, "Content window should be focused");
- is(win.gURLBar.textValue, TEST_VALUE, "New URL is loaded in new window");
-
- // Cleanup.
- yield BrowserTestUtils.closeWindow(win);
-});
-
-add_task(function* right_click_test() {
- info("Running test: Right click on go button");
-
- // Add a new tab.
- yield* promiseOpenNewTab();
-
- triggerCommand(true, {button: 2});
-
- // Right click should do nothing (context menu will be shown).
- is(gURLBar.value, TEST_VALUE, "Urlbar still has the value we entered");
-
- // Cleanup.
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* shift_accel_left_click_test() {
- info("Running test: Shift+Ctrl/Cmd left click on go button");
-
- // Add a new tab.
- let tab = yield* promiseOpenNewTab();
-
- let loadStartedPromise = promiseLoadStarted();
- triggerCommand(true, {accelKey: true, shiftKey: true});
- yield loadStartedPromise;
-
- // Check the load occurred in a new background tab.
- info("URL should be loaded in a new background tab");
- is(gURLBar.value, "", "Urlbar reverted to original value");
- ok(!gURLBar.focused, "Urlbar is no longer focused after urlbar command");
- is(gBrowser.selectedTab, tab, "Focus did not change to the new tab");
-
- // Select the new background tab
- gBrowser.selectedTab = gBrowser.selectedTab.nextSibling;
- is(gURLBar.value, TEST_VALUE, "New URL is loaded in new tab");
-
- // Cleanup.
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* load_in_current_tab_test() {
- let tests = [
- {desc: "Simple return keypress"},
- {desc: "Left click on go button", click: true},
- {desc: "Ctrl/Cmd+Return keypress", event: {accelKey: true}},
- {desc: "Alt+Return keypress in a blank tab", event: {altKey: true}}
- ];
-
- for (let test of tests) {
- info(`Running test: ${test.desc}`);
-
- // Add a new tab.
- let tab = yield* promiseOpenNewTab();
-
- // Trigger a load and check it occurs in the current tab.
- let loadStartedPromise = promiseLoadStarted();
- triggerCommand(test.click || false, test.event || {});
- yield loadStartedPromise;
-
- info("URL should be loaded in the current tab");
- is(gURLBar.value, TEST_VALUE, "Urlbar still has the value we entered");
- yield promiseCheckChildNoFocusedElement(gBrowser.selectedBrowser);
- is(document.activeElement, gBrowser.selectedBrowser, "Content window should be focused");
- is(gBrowser.selectedTab, tab, "New URL was loaded in the current tab");
-
- // Cleanup.
- gBrowser.removeCurrentTab();
- }
-});
-
-add_task(function* load_in_new_tab_test() {
- let tests = [
- {desc: "Ctrl/Cmd left click on go button", click: true, event: {accelKey: true}},
- {desc: "Alt+Return keypress in a dirty tab", event: {altKey: true}, url: START_VALUE}
- ];
-
- for (let test of tests) {
- info(`Running test: ${test.desc}`);
-
- // Add a new tab.
- let tab = yield* promiseOpenNewTab(test.url || "about:blank");
-
- // Trigger a load and check it occurs in the current tab.
- let tabSwitchedPromise = promiseNewTabSwitched();
- triggerCommand(test.click || false, test.event || {});
- yield tabSwitchedPromise;
-
- // Check the load occurred in a new tab.
- info("URL should be loaded in a new focused tab");
- is(gURLBar.inputField.value, TEST_VALUE, "Urlbar still has the value we entered");
- yield promiseCheckChildNoFocusedElement(gBrowser.selectedBrowser);
- is(document.activeElement, gBrowser.selectedBrowser, "Content window should be focused");
- isnot(gBrowser.selectedTab, tab, "New URL was loaded in a new tab");
-
- // Cleanup.
- gBrowser.removeCurrentTab();
- gBrowser.removeCurrentTab();
- }
-});
-
-function triggerCommand(shouldClick, event) {
- gURLBar.value = TEST_VALUE;
- gURLBar.focus();
-
- if (shouldClick) {
- is(gURLBar.getAttribute("pageproxystate"), "invalid",
- "page proxy state must be invalid for go button to be visible");
-
- let goButton = document.getElementById("urlbar-go-button");
- EventUtils.synthesizeMouseAtCenter(goButton, event);
- } else {
- EventUtils.synthesizeKey("VK_RETURN", event);
- }
-}
-
-function promiseLoadStarted() {
- return new Promise(resolve => {
- gBrowser.addTabsProgressListener({
- onStateChange(browser, webProgress, req, flags, status) {
- if (flags & Ci.nsIWebProgressListener.STATE_START) {
- gBrowser.removeTabsProgressListener(this);
- resolve();
- }
- }
- });
- });
-}
-
-function* promiseOpenNewTab(url = "about:blank") {
- let tab = gBrowser.addTab(url);
- let tabSwitchPromise = promiseNewTabSwitched(tab);
- gBrowser.selectedTab = tab;
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- yield tabSwitchPromise;
- return tab;
-}
-
-function promiseNewTabSwitched() {
- return new Promise(resolve => {
- gBrowser.addEventListener("TabSwitchDone", function onSwitch() {
- gBrowser.removeEventListener("TabSwitchDone", onSwitch);
- executeSoon(resolve);
- });
- });
-}
-
-function promiseCheckChildNoFocusedElement(browser)
-{
- if (!gMultiProcessBrowser) {
- Assert.equal(Services.focus.focusedElement, null, "There should be no focused element");
- return null;
- }
-
- return ContentTask.spawn(browser, { }, function* () {
- const fm = Components.classes["@mozilla.org/focus-manager;1"].
- getService(Components.interfaces.nsIFocusManager);
- Assert.equal(fm.focusedElement, null, "There should be no focused element");
- });
-}
diff --git a/browser/base/content/test/urlbar/browser_locationBarExternalLoad.js b/browser/base/content/test/urlbar/browser_locationBarExternalLoad.js
deleted file mode 100644
index 31fc84768..000000000
--- a/browser/base/content/test/urlbar/browser_locationBarExternalLoad.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const url = "data:text/html,<body>hi";
-
-add_task(function*() {
- yield* testURL(url, urlEnter);
- yield* testURL(url, urlClick);
-});
-
-function urlEnter(url) {
- gURLBar.value = url;
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
-}
-
-function urlClick(url) {
- gURLBar.value = url;
- gURLBar.focus();
- let goButton = document.getElementById("urlbar-go-button");
- EventUtils.synthesizeMouseAtCenter(goButton, {});
-}
-
-function promiseNewTabSwitched() {
- return new Promise(resolve => {
- gBrowser.addEventListener("TabSwitchDone", function onSwitch() {
- gBrowser.removeEventListener("TabSwitchDone", onSwitch);
- executeSoon(resolve);
- });
- });
-}
-
-function* testURL(url, loadFunc, endFunc) {
- let tabSwitchedPromise = promiseNewTabSwitched();
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
-
- let pageshowPromise = BrowserTestUtils.waitForContentEvent(browser, "pageshow");
-
- yield tabSwitchedPromise;
- yield pageshowPromise;
-
- let pagePrincipal = gBrowser.contentPrincipal;
- loadFunc(url);
-
- yield BrowserTestUtils.waitForContentEvent(browser, "pageshow");
-
- yield ContentTask.spawn(browser, { isRemote: gMultiProcessBrowser },
- function* (arg) {
- const fm = Components.classes["@mozilla.org/focus-manager;1"].
- getService(Components.interfaces.nsIFocusManager);
- Assert.equal(fm.focusedElement, null, "focusedElement not null");
-
- if (arg.isRemote) {
- Assert.equal(fm.activeWindow, content, "activeWindow not correct");
- }
- });
-
- is(document.activeElement, browser, "content window should be focused");
-
- ok(!gBrowser.contentPrincipal.equals(pagePrincipal),
- "load of " + url + " by " + loadFunc.name + " should produce a page with a different principal");
-
- gBrowser.removeTab(tab);
-}
diff --git a/browser/base/content/test/urlbar/browser_moz_action_link.js b/browser/base/content/test/urlbar/browser_moz_action_link.js
deleted file mode 100644
index ed2d36ee5..000000000
--- a/browser/base/content/test/urlbar/browser_moz_action_link.js
+++ /dev/null
@@ -1,31 +0,0 @@
-"use strict";
-
-const kURIs = [
- "moz-action:foo,",
- "moz-action:foo",
-];
-
-add_task(function*() {
- for (let uri of kURIs) {
- let dataURI = `data:text/html,<a id=a href="${uri}" target=_blank>Link</a>`;
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, dataURI);
-
- let tabSwitchPromise = BrowserTestUtils.switchTab(gBrowser, function() {});
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- content.document.getElementById("a").click();
- });
- yield tabSwitchPromise;
- isnot(gBrowser.selectedTab, tab, "Switched to new tab!");
- is(gURLBar.value, "about:blank", "URL bar should be displaying about:blank");
- let newTab = gBrowser.selectedTab;
- yield BrowserTestUtils.switchTab(gBrowser, tab);
- yield BrowserTestUtils.switchTab(gBrowser, newTab);
- is(gBrowser.selectedTab, newTab, "Switched to new tab again!");
- is(gURLBar.value, "about:blank", "URL bar should be displaying about:blank after tab switch");
- // Finally, check that directly setting it produces the right results, too:
- URLBarSetURI(makeURI(uri));
- is(gURLBar.value, "about:blank", "URL bar should still be displaying about:blank");
- yield BrowserTestUtils.removeTab(newTab);
- yield BrowserTestUtils.removeTab(tab);
- }
-});
diff --git a/browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js b/browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js
deleted file mode 100644
index e9ba8d989..000000000
--- a/browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js
+++ /dev/null
@@ -1,49 +0,0 @@
-function test() {
- waitForExplicitFinish();
- testNext();
-}
-
-var pairs = [
- ["javascript:", ""],
- ["javascript:1+1", "1+1"],
- ["javascript:document.domain", "document.domain"],
- ["data:text/html,<body>hi</body>", "data:text/html,<body>hi</body>"],
- // Nested things get confusing because some things don't parse as URIs:
- ["javascript:javascript:alert('hi!')", "alert('hi!')"],
- ["data:data:text/html,<body>hi</body>", "data:data:text/html,<body>hi</body>"],
- ["javascript:data:javascript:alert('hi!')", "data:javascript:alert('hi!')"],
- ["javascript:data:text/html,javascript:alert('hi!')", "data:text/html,javascript:alert('hi!')"],
- ["data:data:text/html,javascript:alert('hi!')", "data:data:text/html,javascript:alert('hi!')"],
-];
-
-var clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
-
-function paste(input, cb) {
- waitForClipboard(input, function() {
- clipboardHelper.copyString(input);
- }, function() {
- document.commandDispatcher.getControllerForCommand("cmd_paste").doCommand("cmd_paste");
- cb();
- }, function() {
- ok(false, "Failed to copy string '" + input + "' to clipboard");
- cb();
- });
-}
-
-function testNext() {
- gURLBar.value = '';
- if (!pairs.length) {
- finish();
- return;
- }
-
- let [inputValue, expectedURL] = pairs.shift();
-
- gURLBar.focus();
- paste(inputValue, function() {
- is(gURLBar.textValue, expectedURL, "entering '" + inputValue + "' strips relevant bits.");
-
- setTimeout(testNext, 0);
- });
-}
-
diff --git a/browser/base/content/test/urlbar/browser_search_favicon.js b/browser/base/content/test/urlbar/browser_search_favicon.js
deleted file mode 100644
index a8e6dbbcd..000000000
--- a/browser/base/content/test/urlbar/browser_search_favicon.js
+++ /dev/null
@@ -1,52 +0,0 @@
-var gOriginalEngine;
-var gEngine;
-var gRestyleSearchesPref = "browser.urlbar.restyleSearches";
-
-registerCleanupFunction(() => {
- Services.prefs.clearUserPref(gRestyleSearchesPref);
- Services.search.currentEngine = gOriginalEngine;
- Services.search.removeEngine(gEngine);
- return PlacesTestUtils.clearHistory();
-});
-
-add_task(function*() {
- Services.prefs.setBoolPref(gRestyleSearchesPref, true);
-});
-
-add_task(function*() {
-
- Services.search.addEngineWithDetails("SearchEngine", "", "", "",
- "GET", "http://s.example.com/search");
- gEngine = Services.search.getEngineByName("SearchEngine");
- gEngine.addParam("q", "{searchTerms}", null);
- gOriginalEngine = Services.search.currentEngine;
- Services.search.currentEngine = gEngine;
-
- let uri = NetUtil.newURI("http://s.example.com/search?q=foo&client=1");
- yield PlacesTestUtils.addVisits({ uri: uri, title: "Foo - SearchEngine Search" });
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla");
-
- // The first autocomplete result has the action searchengine, while
- // the second result is the "search favicon" element.
- yield promiseAutocompleteResultPopup("foo");
- let result = gURLBar.popup.richlistbox.children[1];
-
- isnot(result, null, "Expect a search result");
- is(result.getAttribute("type"), "searchengine", "Expect correct `type` attribute");
-
- let titleHbox = result._titleText.parentNode.parentNode;
- ok(titleHbox.classList.contains("ac-title"), "Title hbox sanity check");
- is_element_visible(titleHbox, "Title element should be visible");
-
- let urlHbox = result._urlText.parentNode.parentNode;
- ok(urlHbox.classList.contains("ac-url"), "URL hbox sanity check");
- is_element_hidden(urlHbox, "URL element should be hidden");
-
- let actionHbox = result._actionText.parentNode.parentNode;
- ok(actionHbox.classList.contains("ac-action"), "Action hbox sanity check");
- is_element_hidden(actionHbox, "Action element should be hidden because it is not selected");
- is(result._actionText.textContent, "Search with SearchEngine", "Action text should be as expected");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js
deleted file mode 100644
index d207092d4..000000000
--- a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js
+++ /dev/null
@@ -1,216 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * 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/. */
-
-requestLongerTimeout(2);
-
-const TEST_URL_BASES = [
- "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html#tabmatch",
- "http://example.org/browser/browser/base/content/test/urlbar/moz.png#tabmatch"
-];
-
-var gController = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
-var gTabCounter = 0;
-
-add_task(function* step_1() {
- info("Running step 1");
- let maxResults = Services.prefs.getIntPref("browser.urlbar.maxRichResults");
- let promises = [];
- for (let i = 0; i < maxResults - 1; i++) {
- let tab = gBrowser.addTab();
- promises.push(loadTab(tab, TEST_URL_BASES[0] + (++gTabCounter)));
- }
-
- yield Promise.all(promises);
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_2() {
- info("Running step 2");
- gBrowser.selectTabAtIndex(1);
- gBrowser.removeCurrentTab();
- gBrowser.selectTabAtIndex(1);
- gBrowser.removeCurrentTab();
-
- let promises = [];
- for (let i = 1; i < gBrowser.tabs.length; i++)
- promises.push(loadTab(gBrowser.tabs[i], TEST_URL_BASES[1] + (++gTabCounter)));
-
- yield Promise.all(promises);
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_3() {
- info("Running step 3");
- let promises = [];
- for (let i = 1; i < gBrowser.tabs.length; i++)
- promises.push(loadTab(gBrowser.tabs[i], TEST_URL_BASES[0] + gTabCounter));
-
- yield Promise.all(promises);
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_4() {
- info("Running step 4 - ensure we don't register subframes as open pages");
- let tab = gBrowser.addTab();
- tab.linkedBrowser.loadURI('data:text/html,<body><iframe src=""></iframe></body>');
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- let iframe_loaded = ContentTaskUtils.waitForEvent(content.document, "load", true);
- content.document.querySelector("iframe").src = "http://test2.example.org/";
- yield iframe_loaded;
- });
-
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_5() {
- info("Running step 5 - remove tab immediately");
- let tab = gBrowser.addTab("about:logo");
- yield BrowserTestUtils.removeTab(tab);
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_6() {
- info("Running step 6 - check swapBrowsersAndCloseOther preserves registered switch-to-tab result");
- let tabToKeep = gBrowser.addTab();
- let tab = gBrowser.addTab();
- tab.linkedBrowser.loadURI("about:mozilla");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- gBrowser.updateBrowserRemoteness(tabToKeep.linkedBrowser, tab.linkedBrowser.isRemoteBrowser);
- gBrowser.swapBrowsersAndCloseOther(tabToKeep, tab);
-
- yield ensure_opentabs_match_db()
-
- yield BrowserTestUtils.removeTab(tabToKeep);
-
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* step_7() {
- info("Running step 7 - close all tabs");
-
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
-
- gBrowser.addTab("about:blank", {skipAnimation: true});
- while (gBrowser.tabs.length > 1) {
- info("Removing tab: " + gBrowser.tabs[0].linkedBrowser.currentURI.spec);
- gBrowser.selectTabAtIndex(0);
- gBrowser.removeCurrentTab();
- }
-
- yield ensure_opentabs_match_db();
-});
-
-add_task(function* cleanup() {
- info("Cleaning up");
-
- yield PlacesTestUtils.clearHistory();
-});
-
-function loadTab(tab, url) {
- // Because adding visits is async, we will not be notified immediately.
- let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- let visited = new Promise(resolve => {
- Services.obs.addObserver(
- function observer(aSubject, aTopic, aData) {
- if (url != aSubject.QueryInterface(Ci.nsIURI).spec)
- return;
- Services.obs.removeObserver(observer, aTopic);
- resolve();
- },
- "uri-visit-saved",
- false
- );
- });
-
- info("Loading page: " + url);
- tab.linkedBrowser.loadURI(url);
- return Promise.all([ loaded, visited ]);
-}
-
-function ensure_opentabs_match_db() {
- var tabs = {};
-
- var winEnum = Services.wm.getEnumerator("navigator:browser");
- while (winEnum.hasMoreElements()) {
- let browserWin = winEnum.getNext();
- // skip closed-but-not-destroyed windows
- if (browserWin.closed)
- continue;
-
- for (let i = 0; i < browserWin.gBrowser.tabContainer.childElementCount; i++) {
- let browser = browserWin.gBrowser.getBrowserAtIndex(i);
- let url = browser.currentURI.spec;
- if (browserWin.isBlankPageURL(url))
- continue;
- if (!(url in tabs))
- tabs[url] = 1;
- else
- tabs[url]++;
- }
- }
-
- return new Promise(resolve => {
- checkAutocompleteResults(tabs, resolve);
- });
-}
-
-function checkAutocompleteResults(aExpected, aCallback)
-{
- gController.input = {
- timeout: 10,
- textValue: "",
- searches: ["unifiedcomplete"],
- searchParam: "enable-actions",
- popupOpen: false,
- minResultsForPopup: 0,
- invalidate: function() {},
- disableAutoComplete: false,
- completeDefaultIndex: false,
- get popup() { return this; },
- onSearchBegin: function() {},
- onSearchComplete: function ()
- {
- info("Found " + gController.matchCount + " matches.");
- // Check to see the expected uris and titles match up (in any order)
- for (let i = 0; i < gController.matchCount; i++) {
- if (gController.getStyleAt(i).includes("heuristic")) {
- info("Skip heuristic match");
- continue;
- }
- let action = gURLBar.popup.input._parseActionUrl(gController.getValueAt(i));
- let uri = action.params.url;
-
- info("Search for '" + uri + "' in open tabs.");
- let expected = uri in aExpected;
- ok(expected, uri + " was found in autocomplete, was " + (expected ? "" : "not ") + "expected");
- // Remove the found entry from expected results.
- delete aExpected[uri];
- }
-
- // Make sure there is no reported open page that is not open.
- for (let entry in aExpected) {
- ok(false, "'" + entry + "' should be found in autocomplete");
- }
-
- executeSoon(aCallback);
- },
- setSelectedIndex: function() {},
- get searchCount() { return this.searches.length; },
- getSearchAt: function(aIndex) { return this.searches[aIndex]; },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- ])
- };
-
- info("Searching open pages.");
- gController.startSearch(Services.prefs.getCharPref("browser.urlbar.restrict.openpage"));
-}
diff --git a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar_perwindowpb.js b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar_perwindowpb.js
deleted file mode 100644
index 08a18b38a..000000000
--- a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar_perwindowpb.js
+++ /dev/null
@@ -1,84 +0,0 @@
-let testURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-
-add_task(function*() {
- let normalWindow = yield BrowserTestUtils.openNewBrowserWindow();
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield runTest(normalWindow, privateWindow, false);
- yield BrowserTestUtils.closeWindow(normalWindow);
- yield BrowserTestUtils.closeWindow(privateWindow);
-
- normalWindow = yield BrowserTestUtils.openNewBrowserWindow();
- privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield runTest(privateWindow, normalWindow, false);
- yield BrowserTestUtils.closeWindow(normalWindow);
- yield BrowserTestUtils.closeWindow(privateWindow);
-
- privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield runTest(privateWindow, privateWindow, false);
- yield BrowserTestUtils.closeWindow(privateWindow);
-
- normalWindow = yield BrowserTestUtils.openNewBrowserWindow();
- yield runTest(normalWindow, normalWindow, true);
- yield BrowserTestUtils.closeWindow(normalWindow);
-});
-
-function* runTest(aSourceWindow, aDestWindow, aExpectSwitch, aCallback) {
- yield BrowserTestUtils.openNewForegroundTab(aSourceWindow.gBrowser, testURL);
- let testTab = yield BrowserTestUtils.openNewForegroundTab(aDestWindow.gBrowser);
-
- info("waiting for focus on the window");
- yield SimpleTest.promiseFocus(aDestWindow);
- info("got focus on the window");
-
- // Select the testTab
- aDestWindow.gBrowser.selectedTab = testTab;
-
- // Ensure that this tab has no history entries
- let sessionHistoryCount = yield new Promise(resolve => {
- SessionStore.getSessionHistory(gBrowser.selectedTab, function(sessionHistory) {
- resolve(sessionHistory.entries.length);
- });
- });
-
- ok(sessionHistoryCount < 2,
- `The test tab has 1 or fewer history entries. sessionHistoryCount=${sessionHistoryCount}`);
- // Ensure that this tab is on about:blank
- is(testTab.linkedBrowser.currentURI.spec, "about:blank",
- "The test tab is on about:blank");
- // Ensure that this tab's document has no child nodes
- yield ContentTask.spawn(testTab.linkedBrowser, null, function*() {
- ok(!content.document.body.hasChildNodes(),
- "The test tab has no child nodes");
- });
- ok(!testTab.hasAttribute("busy"),
- "The test tab doesn't have the busy attribute");
-
- // Wait for the Awesomebar popup to appear.
- yield promiseAutocompleteResultPopup(testURL, aDestWindow);
-
- info(`awesomebar popup appeared. aExpectSwitch: ${aExpectSwitch}`);
- // Make sure the last match is selected.
- let {controller, popup} = aDestWindow.gURLBar;
- while (popup.selectedIndex < controller.matchCount - 1) {
- info("handling key navigation for DOM_VK_DOWN key");
- controller.handleKeyNavigation(KeyEvent.DOM_VK_DOWN);
- }
-
- let awaitTabSwitch;
- if (aExpectSwitch) {
- awaitTabSwitch = BrowserTestUtils.removeTab(testTab, {dontRemove: true})
- }
-
- // Execute the selected action.
- controller.handleEnter(true);
- info("sent Enter command to the controller");
-
- if (aExpectSwitch) {
- // If we expect a tab switch then the current tab
- // will be closed and we switch to the other tab.
- yield awaitTabSwitch;
- } else {
- // If we don't expect a tab switch then wait for the tab to load.
- yield BrowserTestUtils.browserLoaded(testTab.linkedBrowser);
- }
-}
diff --git a/browser/base/content/test/urlbar/browser_urlHighlight.js b/browser/base/content/test/urlbar/browser_urlHighlight.js
deleted file mode 100644
index ba1537d91..000000000
--- a/browser/base/content/test/urlbar/browser_urlHighlight.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function testVal(aExpected) {
- gURLBar.value = aExpected.replace(/[<>]/g, "");
-
- let selectionController = gURLBar.editor.selectionController;
- let selection = selectionController.getSelection(selectionController.SELECTION_URLSECONDARY);
- let value = gURLBar.editor.rootElement.textContent;
- let result = "";
- for (let i = 0; i < selection.rangeCount; i++) {
- let range = selection.getRangeAt(i).toString();
- let pos = value.indexOf(range);
- result += value.substring(0, pos) + "<" + range + ">";
- value = value.substring(pos + range.length);
- }
- result += value;
- is(result, aExpected,
- "Correct part of the urlbar contents is highlighted");
-}
-
-function test() {
- const prefname = "browser.urlbar.formatting.enabled";
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(prefname);
- URLBarSetURI();
- });
-
- Services.prefs.setBoolPref(prefname, true);
-
- gURLBar.focus();
-
- testVal("https://mozilla.org");
-
- gBrowser.selectedBrowser.focus();
-
- testVal("<https://>mozilla.org");
- testVal("<https://>mözilla.org");
- testVal("<https://>mozilla.imaginatory");
-
- testVal("<https://www.>mozilla.org");
- testVal("<https://sub.>mozilla.org");
- testVal("<https://sub1.sub2.sub3.>mozilla.org");
- testVal("<www.>mozilla.org");
- testVal("<sub.>mozilla.org");
- testVal("<sub1.sub2.sub3.>mozilla.org");
- testVal("<mozilla.com.>mozilla.com");
- testVal("<https://mozilla.com:mozilla.com@>mozilla.com");
- testVal("<mozilla.com:mozilla.com@>mozilla.com");
-
- testVal("<ftp.>mozilla.org");
- testVal("<ftp://ftp.>mozilla.org");
-
- testVal("<https://sub.>mozilla.org");
- testVal("<https://sub1.sub2.sub3.>mozilla.org");
- testVal("<https://user:pass@sub1.sub2.sub3.>mozilla.org");
- testVal("<https://user:pass@>mozilla.org");
- testVal("<user:pass@sub1.sub2.sub3.>mozilla.org");
- testVal("<user:pass@>mozilla.org");
-
- testVal("<https://>mozilla.org< >");
- testVal("mozilla.org< >");
-
- testVal("<https://>mozilla.org</file.ext>");
- testVal("<https://>mozilla.org</sub/file.ext>");
- testVal("<https://>mozilla.org</sub/file.ext?foo>");
- testVal("<https://>mozilla.org</sub/file.ext?foo&bar>");
- testVal("<https://>mozilla.org</sub/file.ext?foo&bar#top>");
- testVal("<https://>mozilla.org</sub/file.ext?foo&bar#top>");
- testVal("foo.bar<?q=test>");
- testVal("foo.bar<#mozilla.org>");
- testVal("foo.bar<?somewhere.mozilla.org>");
- testVal("foo.bar<?@mozilla.org>");
- testVal("foo.bar<#x@mozilla.org>");
- testVal("foo.bar<#@x@mozilla.org>");
- testVal("foo.bar<?x@mozilla.org>");
- testVal("foo.bar<?@x@mozilla.org>");
- testVal("<foo.bar@x@>mozilla.org");
- testVal("<foo.bar@:baz@>mozilla.org");
- testVal("<foo.bar:@baz@>mozilla.org");
- testVal("<foo.bar@:ba:z@>mozilla.org");
- testVal("<foo.:bar:@baz@>mozilla.org");
-
- testVal("<https://sub.>mozilla.org<:666/file.ext>");
- testVal("<sub.>mozilla.org<:666/file.ext>");
- testVal("localhost<:666/file.ext>");
-
- let IPs = ["192.168.1.1",
- "[::]",
- "[::1]",
- "[1::]",
- "[::]",
- "[::1]",
- "[1::]",
- "[1:2:3:4:5:6:7::]",
- "[::1:2:3:4:5:6:7]",
- "[1:2:a:B:c:D:e:F]",
- "[1::8]",
- "[1:2::8]",
- "[fe80::222:19ff:fe11:8c76]",
- "[0000:0123:4567:89AB:CDEF:abcd:ef00:0000]",
- "[::192.168.1.1]",
- "[1::0.0.0.0]",
- "[1:2::255.255.255.255]",
- "[1:2:3::255.255.255.255]",
- "[1:2:3:4::255.255.255.255]",
- "[1:2:3:4:5::255.255.255.255]",
- "[1:2:3:4:5:6:255.255.255.255]"];
- IPs.forEach(function (IP) {
- testVal(IP);
- testVal(IP + "</file.ext>");
- testVal(IP + "<:666/file.ext>");
- testVal("<https://>" + IP);
- testVal("<https://>" + IP + "</file.ext>");
- testVal("<https://user:pass@>" + IP + "<:666/file.ext>");
- testVal("<user:pass@>" + IP + "<:666/file.ext>");
- });
-
- testVal("mailto:admin@mozilla.org");
- testVal("gopher://mozilla.org/");
- testVal("about:config");
- testVal("jar:http://mozilla.org/example.jar!/");
- testVal("view-source:http://mozilla.org/");
- testVal("foo9://mozilla.org/");
- testVal("foo+://mozilla.org/");
- testVal("foo.://mozilla.org/");
- testVal("foo-://mozilla.org/");
-
- Services.prefs.setBoolPref(prefname, false);
-
- testVal("https://mozilla.org");
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js b/browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js
deleted file mode 100644
index 792826eb1..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js
+++ /dev/null
@@ -1,104 +0,0 @@
-"use strict";
-
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
-/**
- * Test what happens if loading a URL that should clear the
- * location bar after a parent process URL.
- */
-add_task(function* clearURLBarAfterParentProcessURL() {
- let tab = yield new Promise(resolve => {
- gBrowser.selectedTab = gBrowser.addTab("about:preferences");
- let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
- newTabBrowser.addEventListener("Initialized", function onInit() {
- newTabBrowser.removeEventListener("Initialized", onInit, true);
- resolve(gBrowser.selectedTab);
- }, true);
- });
- document.getElementById("home-button").click();
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- is(gURLBar.value, "", "URL bar should be empty");
- is(tab.linkedBrowser.userTypedValue, null, "The browser should have no recorded userTypedValue");
- yield BrowserTestUtils.removeTab(tab);
-});
-
-/**
- * Same as above, but open the tab without passing the URL immediately
- * which changes behaviour in tabbrowser.xml.
- */
-add_task(function* clearURLBarAfterParentProcessURLInExistingTab() {
- let tab = yield new Promise(resolve => {
- gBrowser.selectedTab = gBrowser.addTab();
- let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
- newTabBrowser.addEventListener("Initialized", function onInit() {
- newTabBrowser.removeEventListener("Initialized", onInit, true);
- resolve(gBrowser.selectedTab);
- }, true);
- newTabBrowser.loadURI("about:preferences");
- });
- document.getElementById("home-button").click();
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- is(gURLBar.value, "", "URL bar should be empty");
- is(tab.linkedBrowser.userTypedValue, null, "The browser should have no recorded userTypedValue");
- yield BrowserTestUtils.removeTab(tab);
-});
-
-/**
- * Load about:home directly from an about:newtab page. Because it is an
- * 'initial' page, we need to treat this specially if the user actually
- * loads a page like this from the URL bar.
- */
-add_task(function* clearURLBarAfterManuallyLoadingAboutHome() {
- let promiseTabOpenedAndSwitchedTo = BrowserTestUtils.switchTab(gBrowser, () => {});
- // This opens about:newtab:
- BrowserOpenTab();
- let tab = yield promiseTabOpenedAndSwitchedTo;
- is(gURLBar.value, "", "URL bar should be empty");
- is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null");
-
- gURLBar.value = "about:home";
- gURLBar.select();
- let aboutHomeLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:home");
- EventUtils.sendKey("return");
- yield aboutHomeLoaded;
-
- is(gURLBar.value, "", "URL bar should be empty");
- is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null");
- yield BrowserTestUtils.removeTab(tab);
-});
-
-/**
- * Ensure we don't show 'about:home' in the URL bar temporarily in new tabs
- * while we're switching remoteness (when the URL we're loading and the
- * default content principal are different).
- */
-add_task(function* dontTemporarilyShowAboutHome() {
- yield SpecialPowers.pushPrefEnv({set: [["browser.startup.page", 1]]});
- let windowOpenedPromise = BrowserTestUtils.waitForNewWindow();
- let win = OpenBrowserWindow();
- yield windowOpenedPromise;
- let promiseTabSwitch = BrowserTestUtils.switchTab(win.gBrowser, () => {});
- win.BrowserOpenTab();
- yield promiseTabSwitch;
- yield TabStateFlusher.flush(win.gBrowser.selectedBrowser);
- yield BrowserTestUtils.closeWindow(win);
- ok(SessionStore.getClosedWindowCount(), "Should have a closed window");
-
- windowOpenedPromise = BrowserTestUtils.waitForNewWindow();
- win = SessionStore.undoCloseWindow(0);
- yield windowOpenedPromise;
- let wpl = {
- onLocationChange(wpl, request, location, flags) {
- is(win.gURLBar.value, "", "URL bar value should stay empty.");
- },
- };
- win.gBrowser.addProgressListener(wpl);
- let otherTab = win.gBrowser.selectedTab.previousSibling;
- let tabLoaded = BrowserTestUtils.browserLoaded(otherTab.linkedBrowser, false, "about:home");
- yield BrowserTestUtils.switchTab(win.gBrowser, otherTab);
- yield tabLoaded;
- win.gBrowser.removeProgressListener(wpl);
- is(win.gURLBar.value, "", "URL bar value should be empty.");
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js b/browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js
deleted file mode 100644
index 8101c101d..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js
+++ /dev/null
@@ -1,49 +0,0 @@
-// This test ensures that autoFilled values are not trimmed, unless the user
-// selects from the autocomplete popup.
-
-add_task(function* setup() {
- const PREF_TRIMURL = "browser.urlbar.trimURLs";
- const PREF_AUTOFILL = "browser.urlbar.autoFill";
-
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref(PREF_TRIMURL);
- Services.prefs.clearUserPref(PREF_AUTOFILL);
- yield PlacesTestUtils.clearHistory();
- gURLBar.handleRevert();
- });
- Services.prefs.setBoolPref(PREF_TRIMURL, true);
- Services.prefs.setBoolPref(PREF_AUTOFILL, true);
-
- // Adding a tab would hit switch-to-tab, so it's safer to just add a visit.
- yield PlacesTestUtils.addVisits({
- uri: "http://www.autofilltrimurl.com/whatever",
- transition: Ci.nsINavHistoryService.TRANSITION_TYPED,
- });
-});
-
-function* promiseSearch(searchtext) {
- gURLBar.focus();
- gURLBar.inputField.value = searchtext.substr(0, searchtext.length -1);
- EventUtils.synthesizeKey(searchtext.substr(-1, 1), {});
- yield promiseSearchComplete();
-}
-
-add_task(function* () {
- yield promiseSearch("http://");
- is(gURLBar.inputField.value, "http://", "Autofilled value is as expected");
-});
-
-add_task(function* () {
- yield promiseSearch("http://au");
- is(gURLBar.inputField.value, "http://autofilltrimurl.com/", "Autofilled value is as expected");
-});
-
-add_task(function* () {
- yield promiseSearch("http://www.autofilltrimurl.com");
- is(gURLBar.inputField.value, "http://www.autofilltrimurl.com/", "Autofilled value is as expected");
-
- // Now ensure selecting from the popup correctly trims.
- is(gURLBar.controller.matchCount, 2, "Found the expected number of matches");
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(gURLBar.inputField.value, "www.autofilltrimurl.com/whatever", "trim was applied correctly");
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarCopying.js b/browser/base/content/test/urlbar/browser_urlbarCopying.js
deleted file mode 100644
index 8d5562b61..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarCopying.js
+++ /dev/null
@@ -1,232 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const trimPref = "browser.urlbar.trimURLs";
-const phishyUserPassPref = "network.http.phishy-userpass-length";
-
-function toUnicode(input) {
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
-
- return converter.ConvertToUnicode(input);
-}
-
-function test() {
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- registerCleanupFunction(function () {
- gBrowser.removeTab(tab);
- Services.prefs.clearUserPref(trimPref);
- Services.prefs.clearUserPref(phishyUserPassPref);
- URLBarSetURI();
- });
-
- Services.prefs.setBoolPref(trimPref, true);
- Services.prefs.setIntPref(phishyUserPassPref, 32); // avoid prompting about phishing
-
- waitForExplicitFinish();
-
- nextTest();
-}
-
-var tests = [
- // pageproxystate="invalid"
- {
- setURL: "http://example.com/",
- expectedURL: "example.com",
- copyExpected: "example.com"
- },
- {
- copyVal: "<e>xample.com",
- copyExpected: "e"
- },
-
- // pageproxystate="valid" from this point on (due to the load)
- {
- loadURL: "http://example.com/",
- expectedURL: "example.com",
- copyExpected: "http://example.com/"
- },
- {
- copyVal: "<example.co>m",
- copyExpected: "example.co"
- },
- {
- copyVal: "e<x>ample.com",
- copyExpected: "x"
- },
- {
- copyVal: "<e>xample.com",
- copyExpected: "e"
- },
-
- {
- loadURL: "http://example.com/foo",
- expectedURL: "example.com/foo",
- copyExpected: "http://example.com/foo"
- },
- {
- copyVal: "<example.com>/foo",
- copyExpected: "http://example.com"
- },
- {
- copyVal: "<example>.com/foo",
- copyExpected: "example"
- },
-
- // Test that userPass is stripped out
- {
- loadURL: "http://user:pass@mochi.test:8888/browser/browser/base/content/test/urlbar/authenticate.sjs?user=user&pass=pass",
- expectedURL: "mochi.test:8888/browser/browser/base/content/test/urlbar/authenticate.sjs?user=user&pass=pass",
- copyExpected: "http://mochi.test:8888/browser/browser/base/content/test/urlbar/authenticate.sjs?user=user&pass=pass"
- },
-
- // Test escaping
- {
- loadURL: "http://example.com/()%28%29%C3%A9",
- expectedURL: "example.com/()()\xe9",
- copyExpected: "http://example.com/()%28%29%C3%A9"
- },
- {
- copyVal: "<example.com/(>)()\xe9",
- copyExpected: "http://example.com/("
- },
- {
- copyVal: "e<xample.com/(>)()\xe9",
- copyExpected: "xample.com/("
- },
-
- {
- loadURL: "http://example.com/%C3%A9%C3%A9",
- expectedURL: "example.com/\xe9\xe9",
- copyExpected: "http://example.com/%C3%A9%C3%A9"
- },
- {
- copyVal: "e<xample.com/\xe9>\xe9",
- copyExpected: "xample.com/\xe9"
- },
- {
- copyVal: "<example.com/\xe9>\xe9",
- copyExpected: "http://example.com/\xe9"
- },
-
- {
- loadURL: "http://example.com/?%C3%B7%C3%B7",
- expectedURL: "example.com/?\xf7\xf7",
- copyExpected: "http://example.com/?%C3%B7%C3%B7"
- },
- {
- copyVal: "e<xample.com/?\xf7>\xf7",
- copyExpected: "xample.com/?\xf7"
- },
- {
- copyVal: "<example.com/?\xf7>\xf7",
- copyExpected: "http://example.com/?\xf7"
- },
- {
- loadURL: "http://example.com/a%20test",
- expectedURL: "example.com/a test",
- copyExpected: "http://example.com/a%20test"
- },
- {
- loadURL: "http://example.com/a%E3%80%80test",
- expectedURL: toUnicode("example.com/a test"),
- copyExpected: "http://example.com/a%E3%80%80test"
- },
- {
- loadURL: "http://example.com/a%20%C2%A0test",
- expectedURL: "example.com/a%20%C2%A0test",
- copyExpected: "http://example.com/a%20%C2%A0test"
- },
- {
- loadURL: "http://example.com/%20%20%20",
- expectedURL: "example.com/%20%20%20",
- copyExpected: "http://example.com/%20%20%20"
- },
- {
- loadURL: "http://example.com/%E3%80%80%E3%80%80",
- expectedURL: "example.com/%E3%80%80%E3%80%80",
- copyExpected: "http://example.com/%E3%80%80%E3%80%80"
- },
-
- // data: and javsacript: URIs shouldn't be encoded
- {
- loadURL: "javascript:('%C3%A9%20%25%50')",
- expectedURL: "javascript:('%C3%A9 %25P')",
- copyExpected: "javascript:('%C3%A9 %25P')"
- },
- {
- copyVal: "<javascript:(>'%C3%A9 %25P')",
- copyExpected: "javascript:("
- },
-
- {
- loadURL: "data:text/html,(%C3%A9%20%25%50)",
- expectedURL: "data:text/html,(%C3%A9 %25P)",
- copyExpected: "data:text/html,(%C3%A9 %25P)",
- },
- {
- copyVal: "<data:text/html,(>%C3%A9 %25P)",
- copyExpected: "data:text/html,("
- },
- {
- copyVal: "<data:text/html,(%C3%A9 %25P>)",
- copyExpected: "data:text/html,(%C3%A9 %25P",
- }
-];
-
-function nextTest() {
- let test = tests.shift();
- if (tests.length == 0)
- runTest(test, finish);
- else
- runTest(test, nextTest);
-}
-
-function runTest(test, cb) {
- function doCheck() {
- if (test.setURL || test.loadURL) {
- gURLBar.valueIsTyped = !!test.setURL;
- is(gURLBar.textValue, test.expectedURL, "url bar value set");
- }
-
- testCopy(test.copyVal, test.copyExpected, cb);
- }
-
- if (test.loadURL) {
- loadURL(test.loadURL, doCheck);
- } else {
- if (test.setURL)
- gURLBar.value = test.setURL;
- doCheck();
- }
-}
-
-function testCopy(copyVal, targetValue, cb) {
- info("Expecting copy of: " + targetValue);
- waitForClipboard(targetValue, function () {
- gURLBar.focus();
- if (copyVal) {
- let startBracket = copyVal.indexOf("<");
- let endBracket = copyVal.indexOf(">");
- if (startBracket == -1 || endBracket == -1 ||
- startBracket > endBracket ||
- copyVal.replace("<", "").replace(">", "") != gURLBar.textValue) {
- ok(false, "invalid copyVal: " + copyVal);
- }
- gURLBar.selectionStart = startBracket;
- gURLBar.selectionEnd = endBracket - 1;
- } else {
- gURLBar.select();
- }
-
- goDoCommand("cmd_copy");
- }, cb, cb);
-}
-
-function loadURL(aURL, aCB) {
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, aURL);
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, aURL).then(aCB);
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarDecode.js b/browser/base/content/test/urlbar/browser_urlbarDecode.js
deleted file mode 100644
index 6a2c421ef..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarDecode.js
+++ /dev/null
@@ -1,97 +0,0 @@
-"use strict";
-
-// This test makes sure (1) you can't break the urlbar by typing particular JSON
-// or JS fragments into it, (2) urlbar.textValue shows URLs unescaped, and (3)
-// the urlbar also shows the URLs embedded in action URIs unescaped. See bug
-// 1233672.
-
-add_task(function* injectJSON() {
- let inputStrs = [
- 'http://example.com/ ", "url": "bar',
- 'http://example.com/\\',
- 'http://example.com/"',
- 'http://example.com/","url":"evil.com',
- 'http://mozilla.org/\\u0020',
- 'http://www.mozilla.org/","url":1e6,"some-key":"foo',
- 'http://www.mozilla.org/","url":null,"some-key":"foo',
- 'http://www.mozilla.org/","url":["foo","bar"],"some-key":"foo',
- ];
- for (let inputStr of inputStrs) {
- yield checkInput(inputStr);
- }
- gURLBar.value = "";
- gURLBar.handleRevert();
- gURLBar.blur();
-});
-
-add_task(function losslessDecode() {
- let urlNoScheme = "example.com/\u30a2\u30a4\u30a6\u30a8\u30aa";
- let url = "http://" + urlNoScheme;
- gURLBar.textValue = url;
- // Since this is directly setting textValue, it is expected to be trimmed.
- Assert.equal(gURLBar.inputField.value, urlNoScheme,
- "The string displayed in the textbox should not be escaped");
- gURLBar.value = "";
- gURLBar.handleRevert();
- gURLBar.blur();
-});
-
-add_task(function* actionURILosslessDecode() {
- let urlNoScheme = "example.com/\u30a2\u30a4\u30a6\u30a8\u30aa";
- let url = "http://" + urlNoScheme;
- yield promiseAutocompleteResultPopup(url);
-
- // At this point the heuristic result is selected but the urlbar's value is
- // simply `url`. Key down and back around until the heuristic result is
- // selected again, and at that point the urlbar's value should be a visiturl
- // moz-action.
-
- do {
- gURLBar.controller.handleKeyNavigation(KeyEvent.DOM_VK_DOWN);
- } while (gURLBar.popup.selectedIndex != 0);
-
- let [, type, ] = gURLBar.value.match(/^moz-action:([^,]+),(.*)$/);
- Assert.equal(type, "visiturl",
- "visiturl action URI should be in the urlbar");
-
- Assert.equal(gURLBar.inputField.value, urlNoScheme,
- "The string displayed in the textbox should not be escaped");
-
- gURLBar.value = "";
- gURLBar.handleRevert();
- gURLBar.blur();
-});
-
-function* checkInput(inputStr) {
- yield promiseAutocompleteResultPopup(inputStr);
-
- let item = gURLBar.popup.richlistbox.firstChild;
- Assert.ok(item, "Should have a result");
-
- // visiturl matches have their param.urls fixed up.
- let fixupInfo = Services.uriFixup.getFixupURIInfo(inputStr,
- Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |
- Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP
- );
- let expectedVisitURL = fixupInfo.fixedURI.spec;
-
- let type = "visiturl";
- let params = {
- url: expectedVisitURL,
- input: inputStr,
- };
- for (let key in params) {
- params[key] = encodeURIComponent(params[key]);
- }
- let expectedURL = "moz-action:" + type + "," + JSON.stringify(params);
- Assert.equal(item.getAttribute("url"), expectedURL, "url");
-
- Assert.equal(item.getAttribute("title"), inputStr.replace("\\", "/"), "title");
- Assert.equal(item.getAttribute("text"), inputStr, "text");
-
- let itemType = item.getAttribute("type");
- Assert.equal(itemType, "visiturl");
-
- Assert.equal(item._titleText.textContent, inputStr.replace("\\", "/"), "Visible title");
- Assert.equal(item._actionText.textContent, "Visit", "Visible action");
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarDelete.js b/browser/base/content/test/urlbar/browser_urlbarDelete.js
deleted file mode 100644
index d4eb6c856..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarDelete.js
+++ /dev/null
@@ -1,39 +0,0 @@
-add_task(function*() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://bug1105244.example.com/",
- title: "test" });
-
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.remove(bm);
- });
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, testDelete);
-});
-
-function sendHome() {
- // unclear why VK_HOME doesn't work on Mac, but it doesn't...
- if (Services.appinfo.OS == "Darwin") {
- EventUtils.synthesizeKey("VK_LEFT", { altKey: true });
- } else {
- EventUtils.synthesizeKey("VK_HOME", {});
- }
-}
-
-function sendDelete() {
- EventUtils.synthesizeKey("VK_DELETE", {});
-}
-
-function* testDelete() {
- yield promiseAutocompleteResultPopup("bug1105244");
-
- // move to the start.
- sendHome();
- // delete the first few chars - each delete should operate on the input field.
- sendDelete();
- Assert.equal(gURLBar.inputField.value, "ug1105244");
-
- yield promisePopupShown(gURLBar.popup);
-
- sendDelete();
- Assert.equal(gURLBar.inputField.value, "g1105244");
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarEnter.js b/browser/base/content/test/urlbar/browser_urlbarEnter.js
deleted file mode 100644
index 32cbaf2be..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarEnter.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const TEST_VALUE = "example.com/\xF7?\xF7";
-const START_VALUE = "example.com/%C3%B7?%C3%B7";
-
-add_task(function* () {
- info("Simple return keypress");
- let tab = gBrowser.selectedTab = gBrowser.addTab(START_VALUE);
-
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
-
- // Check url bar and selected tab.
- is(gURLBar.textValue, TEST_VALUE, "Urlbar should preserve the value on return keypress");
- is(gBrowser.selectedTab, tab, "New URL was loaded in the current tab");
-
- // Cleanup.
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_task(function* () {
- info("Alt+Return keypress");
- // due to bug 691608, we must wait for the load event, else isTabEmpty() will
- // return true on e10s for this tab, so it will be reused even with altKey.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, START_VALUE);
-
- let tabOpenPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {altKey: true});
-
- // wait for the new tab to appear.
- yield tabOpenPromise;
-
- // Check url bar and selected tab.
- is(gURLBar.textValue, TEST_VALUE, "Urlbar should preserve the value on return keypress");
- isnot(gBrowser.selectedTab, tab, "New URL was loaded in a new tab");
-
- // Cleanup.
- yield BrowserTestUtils.removeTab(tab);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarEnterAfterMouseOver.js b/browser/base/content/test/urlbar/browser_urlbarEnterAfterMouseOver.js
deleted file mode 100644
index 22e336f91..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarEnterAfterMouseOver.js
+++ /dev/null
@@ -1,69 +0,0 @@
-function repeat(limit, func) {
- for (let i = 0; i < limit; i++) {
- func(i);
- }
-}
-
-function* promiseAutoComplete(inputText) {
- gURLBar.focus();
- gURLBar.value = inputText.slice(0, -1);
- EventUtils.synthesizeKey(inputText.slice(-1), {});
- yield promiseSearchComplete();
-}
-
-function is_selected(index) {
- is(gURLBar.popup.richlistbox.selectedIndex, index, `Item ${index + 1} should be selected`);
-}
-
-let gMaxResults;
-
-add_task(function*() {
- registerCleanupFunction(function* () {
- yield PlacesTestUtils.clearHistory();
- });
-
- yield PlacesTestUtils.clearHistory();
-
- gMaxResults = Services.prefs.getIntPref("browser.urlbar.maxRichResults");
-
- let visits = [];
- repeat(gMaxResults, i => {
- visits.push({
- uri: makeURI("http://example.com/autocomplete/?" + i),
- });
- });
- yield PlacesTestUtils.addVisits(visits);
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield promiseAutoComplete("http://example.com/autocomplete/");
-
- let popup = gURLBar.popup;
- let results = popup.richlistbox.children;
- is(results.length, gMaxResults,
- "Should get gMaxResults=" + gMaxResults + " results");
-
- let initiallySelected = gURLBar.popup.richlistbox.selectedIndex;
-
- info("Key Down to select the next item");
- EventUtils.synthesizeKey("VK_DOWN", {});
- is_selected(initiallySelected + 1);
- let expectedURL = gURLBar.controller.getFinalCompleteValueAt(initiallySelected + 1);
-
- is(gURLBar.value, gURLBar.controller.getValueAt(initiallySelected + 1),
- "Value in the URL bar should be updated by keyboard selection");
-
- // Verify that what we're about to do changes the selectedIndex:
- isnot(initiallySelected + 1, 3, "Shouldn't be changing the selectedIndex to the same index we keyboard-selected.");
-
- // Would love to use a synthetic mousemove event here, but that doesn't seem to do anything.
- // EventUtils.synthesizeMouseAtCenter(results[3], {type: "mousemove"});
- gURLBar.popup.richlistbox.selectedIndex = 3;
- is_selected(3);
-
- let autocompletePopupHidden = promisePopupHidden(gURLBar.popup);
- let openedExpectedPage = waitForDocLoadAndStopIt(expectedURL);
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield Promise.all([autocompletePopupHidden, openedExpectedPage]);
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarFocusedCmdK.js b/browser/base/content/test/urlbar/browser_urlbarFocusedCmdK.js
deleted file mode 100644
index 8c9e2c9f2..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarFocusedCmdK.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function*() {
- // Remove the search bar from toolbar
- CustomizableUI.removeWidgetFromArea("search-container");
-
- // Test that Ctrl/Cmd + K will focus the url bar
- let focusPromise = BrowserTestUtils.waitForEvent(gURLBar, "focus");
- EventUtils.synthesizeKey("k", { accelKey: true });
- yield focusPromise;
- Assert.equal(document.activeElement, gURLBar.inputField, "URL Bar should be focused");
-
- // Reset changes made to toolbar
- CustomizableUI.reset();
-});
-
diff --git a/browser/base/content/test/urlbar/browser_urlbarHashChangeProxyState.js b/browser/base/content/test/urlbar/browser_urlbarHashChangeProxyState.js
deleted file mode 100644
index 152106dad..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarHashChangeProxyState.js
+++ /dev/null
@@ -1,111 +0,0 @@
-"use strict";
-
-/**
- * Check that navigating through both the URL bar and using in-page hash- or ref-
- * based links and back or forward navigation updates the URL bar and identity block correctly.
- */
-add_task(function* () {
- let baseURL = "https://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
- let url = baseURL + "#foo";
- yield BrowserTestUtils.withNewTab({ gBrowser, url }, function*(browser) {
- let identityBox = document.getElementById("identity-box");
- let expectedURL = url;
-
- let verifyURLBarState = testType => {
- is(gURLBar.textValue, expectedURL, "URL bar visible value should be correct " + testType);
- is(gURLBar.value, expectedURL, "URL bar value should be correct " + testType);
- ok(identityBox.classList.contains("verifiedDomain"), "Identity box should know we're doing SSL " + testType);
- is(gURLBar.getAttribute("pageproxystate"), "valid", "URL bar is in valid page proxy state");
- };
-
- verifyURLBarState("at the beginning");
-
- let locationChangePromise;
- let resolveLocationChangePromise;
- let expectURL = url => {
- expectedURL = url;
- locationChangePromise = new Promise(r => resolveLocationChangePromise = r);
- };
- let wpl = {
- onLocationChange(wpl, request, location, flags) {
- is(location.spec, expectedURL, "Got the expected URL");
- resolveLocationChangePromise();
- },
- };
- gBrowser.addProgressListener(wpl);
-
- expectURL(baseURL + "#foo");
- gURLBar.select();
- EventUtils.sendKey("return");
-
- yield locationChangePromise;
- verifyURLBarState("after hitting enter on the same URL a second time");
-
- expectURL(baseURL + "#bar");
- gURLBar.value = expectedURL;
- gURLBar.select();
- EventUtils.sendKey("return");
-
- yield locationChangePromise;
- verifyURLBarState("after a URL bar hash navigation");
-
- expectURL(baseURL + "#foo");
- yield ContentTask.spawn(browser, null, function() {
- let a = content.document.createElement("a");
- a.href = "#foo";
- a.textContent = "Foo Link";
- content.document.body.appendChild(a);
- a.click();
- });
-
- yield locationChangePromise;
- verifyURLBarState("after a page link hash navigation");
-
- expectURL(baseURL + "#bar");
- gBrowser.goBack();
-
- yield locationChangePromise;
- verifyURLBarState("after going back");
-
- expectURL(baseURL + "#foo");
- gBrowser.goForward();
-
- yield locationChangePromise;
- verifyURLBarState("after going forward");
-
- expectURL(baseURL + "#foo");
- gURLBar.select();
- EventUtils.sendKey("return");
-
- yield locationChangePromise;
- verifyURLBarState("after hitting enter on the same URL");
-
- gBrowser.removeProgressListener(wpl);
- });
-});
-
-/**
- * Check that initial secure loads that swap remoteness
- * get the correct page icon when finished.
- */
-add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab", false);
- // NB: CPOW usage because new tab pages can be preloaded, in which case no
- // load events fire.
- yield BrowserTestUtils.waitForCondition(() => !tab.linkedBrowser.contentDocument.hidden)
- let url = "https://example.org/browser/browser/base/content/test/urlbar/dummy_page.html#foo";
- gURLBar.value = url;
- gURLBar.select();
- EventUtils.sendKey("return");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- is(gURLBar.textValue, url, "URL bar visible value should be correct when the page loads from about:newtab");
- is(gURLBar.value, url, "URL bar value should be correct when the page loads from about:newtab");
- let identityBox = document.getElementById("identity-box");
- ok(identityBox.classList.contains("verifiedDomain"),
- "Identity box should know we're doing SSL when the page loads from about:newtab");
- is(gURLBar.getAttribute("pageproxystate"), "valid",
- "URL bar is in valid page proxy state when SSL page with hash loads from about:newtab");
- yield BrowserTestUtils.removeTab(tab);
-});
-
diff --git a/browser/base/content/test/urlbar/browser_urlbarKeepStateAcrossTabSwitches.js b/browser/base/content/test/urlbar/browser_urlbarKeepStateAcrossTabSwitches.js
deleted file mode 100644
index 9c8996059..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarKeepStateAcrossTabSwitches.js
+++ /dev/null
@@ -1,49 +0,0 @@
-"use strict";
-
-/**
- * Verify user typed text remains in the URL bar when tab switching, even when
- * loads fail.
- */
-add_task(function* () {
- let input = "i-definitely-dont-exist.example.com";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab", false);
- // NB: CPOW usage because new tab pages can be preloaded, in which case no
- // load events fire.
- yield BrowserTestUtils.waitForCondition(() => !tab.linkedBrowser.contentDocument.hidden)
- let errorPageLoaded = BrowserTestUtils.waitForErrorPage(tab.linkedBrowser);
- gURLBar.value = input;
- gURLBar.select();
- EventUtils.sendKey("return");
- yield errorPageLoaded;
- is(gURLBar.textValue, input, "Text is still in URL bar");
- yield BrowserTestUtils.switchTab(gBrowser, tab.previousSibling);
- yield BrowserTestUtils.switchTab(gBrowser, tab);
- is(gURLBar.textValue, input, "Text is still in URL bar after tab switch");
- yield BrowserTestUtils.removeTab(tab);
-});
-
-/**
- * Invalid URIs fail differently (that is, immediately, in the loadURI call)
- * if keyword searches are turned off. Test that this works, too.
- */
-add_task(function* () {
- let input = "To be or not to be-that is the question";
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({set: [["keyword.enabled", false]]}, resolve));
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab", false);
- // NB: CPOW usage because new tab pages can be preloaded, in which case no
- // load events fire.
- yield BrowserTestUtils.waitForCondition(() => !tab.linkedBrowser.contentDocument.hidden)
- let errorPageLoaded = BrowserTestUtils.waitForErrorPage(tab.linkedBrowser);
- gURLBar.value = input;
- gURLBar.select();
- EventUtils.sendKey("return");
- yield errorPageLoaded;
- is(gURLBar.textValue, input, "Text is still in URL bar");
- is(tab.linkedBrowser.userTypedValue, input, "Text still stored on browser");
- yield BrowserTestUtils.switchTab(gBrowser, tab.previousSibling);
- yield BrowserTestUtils.switchTab(gBrowser, tab);
- is(gURLBar.textValue, input, "Text is still in URL bar after tab switch");
- is(tab.linkedBrowser.userTypedValue, input, "Text still stored on browser");
- yield BrowserTestUtils.removeTab(tab);
-});
-
diff --git a/browser/base/content/test/urlbar/browser_urlbarOneOffs.js b/browser/base/content/test/urlbar/browser_urlbarOneOffs.js
deleted file mode 100644
index 1f58b8edd..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarOneOffs.js
+++ /dev/null
@@ -1,232 +0,0 @@
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-let gMaxResults;
-
-add_task(function* init() {
- Services.prefs.setBoolPref("browser.urlbar.oneOffSearches", true);
- gMaxResults = Services.prefs.getIntPref("browser.urlbar.maxRichResults");
-
- // Add a search suggestion engine and move it to the front so that it appears
- // as the first one-off.
- let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- Services.search.moveEngine(engine, 0);
-
- registerCleanupFunction(function* () {
- yield hidePopup();
- yield PlacesTestUtils.clearHistory();
- });
-
- yield PlacesTestUtils.clearHistory();
-
- let visits = [];
- for (let i = 0; i < gMaxResults; i++) {
- visits.push({
- uri: makeURI("http://example.com/browser_urlbarOneOffs.js/?" + i),
- // TYPED so that the visit shows up when the urlbar's drop-down arrow is
- // pressed.
- transition: Ci.nsINavHistoryService.TRANSITION_TYPED,
- });
- }
- yield PlacesTestUtils.addVisits(visits);
-});
-
-// Keys up and down through the history panel, i.e., the panel that's shown when
-// there's no text in the textbox.
-add_task(function* history() {
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_DOWN", {})
- yield promisePopupShown(gURLBar.popup);
-
- assertState(-1, -1, "");
-
- // Key down through each result.
- for (let i = 0; i < gMaxResults; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(i, -1,
- "example.com/browser_urlbarOneOffs.js/?" + (gMaxResults - i - 1));
- }
-
- // Key down through each one-off.
- let numButtons =
- gURLBar.popup.oneOffSearchButtons.getSelectableButtons(true).length;
- for (let i = 0; i < numButtons; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(-1, i, "");
- }
-
- // Key down once more. Nothing should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(-1, -1, "");
-
- // Once more. The first result should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(0, -1,
- "example.com/browser_urlbarOneOffs.js/?" + (gMaxResults - 1));
-
- // Now key up. Nothing should be selected again.
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(-1, -1, "");
-
- // Key up through each one-off.
- for (let i = numButtons - 1; i >= 0; i--) {
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(-1, i, "");
- }
-
- // Key up through each result.
- for (let i = gMaxResults - 1; i >= 0; i--) {
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(i, -1,
- "example.com/browser_urlbarOneOffs.js/?" + (gMaxResults - i - 1));
- }
-
- // Key up once more. Nothing should be selected.
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(-1, -1, "");
-
- yield hidePopup();
-});
-
-// Keys up and down through the non-history panel, i.e., the panel that's shown
-// when you type something in the textbox.
-add_task(function* typedValue() {
- // Use a typed value that returns the visits added above but that doesn't
- // trigger autofill since that would complicate the test.
- let typedValue = "browser_urlbarOneOffs";
- yield promiseAutocompleteResultPopup(typedValue, window, true);
-
- assertState(0, -1, typedValue);
-
- // Key down through each result. The first result is already selected, which
- // is why gMaxResults - 1 is the correct number of times to do this.
- for (let i = 0; i < gMaxResults - 1; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {})
- // i starts at zero so that the textValue passed to assertState is correct.
- // But that means that i + 1 is the expected selected index, since initially
- // (when this loop starts) the first result is selected.
- assertState(i + 1, -1,
- "example.com/browser_urlbarOneOffs.js/?" + (gMaxResults - i - 1));
- }
-
- // Key down through each one-off.
- let numButtons =
- gURLBar.popup.oneOffSearchButtons.getSelectableButtons(true).length;
- for (let i = 0; i < numButtons; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(-1, i, typedValue);
- }
-
- // Key down once more. The selection should wrap around to the first result.
- EventUtils.synthesizeKey("VK_DOWN", {})
- assertState(0, -1, typedValue);
-
- // Now key up. The selection should wrap back around to the one-offs. Key
- // up through all the one-offs.
- for (let i = numButtons - 1; i >= 0; i--) {
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(-1, i, typedValue);
- }
-
- // Key up through each non-heuristic result.
- for (let i = gMaxResults - 2; i >= 0; i--) {
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(i + 1, -1,
- "example.com/browser_urlbarOneOffs.js/?" + (gMaxResults - i - 1));
- }
-
- // Key up once more. The heuristic result should be selected.
- EventUtils.synthesizeKey("VK_UP", {})
- assertState(0, -1, typedValue);
-
- yield hidePopup();
-});
-
-// Checks that "Search with Current Search Engine" items are updated to "Search
-// with One-Off Engine" when a one-off is selected.
-add_task(function* searchWith() {
- let typedValue = "foo";
- yield promiseAutocompleteResultPopup(typedValue);
-
- assertState(0, -1, typedValue);
-
- let item = gURLBar.popup.richlistbox.firstChild;
- Assert.equal(item._actionText.textContent,
- "Search with " + Services.search.currentEngine.name,
- "Sanity check: first result's action text");
-
- // Alt+Down to the first one-off. Now the first result and the first one-off
- // should both be selected.
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true })
- assertState(0, 0, typedValue);
-
- let engineName = gURLBar.popup.oneOffSearchButtons.selectedButton.engine.name;
- Assert.notEqual(engineName, Services.search.currentEngine.name,
- "Sanity check: First one-off engine should not be " +
- "the current engine");
- Assert.equal(item._actionText.textContent,
- "Search with " + engineName,
- "First result's action text should be updated");
-
- yield hidePopup();
-});
-
-// Clicks a one-off.
-add_task(function* oneOffClick() {
- gBrowser.selectedTab = gBrowser.addTab();
-
- // We are explicitly using something that looks like a url, to make the test
- // stricter. Even if it looks like a url, we should search.
- let typedValue = "foo.bar";
- yield promiseAutocompleteResultPopup(typedValue);
-
- assertState(0, -1, typedValue);
-
- let oneOffs = gURLBar.popup.oneOffSearchButtons.getSelectableButtons(true);
- let resultsPromise =
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false,
- "http://mochi.test:8888/");
- EventUtils.synthesizeMouseAtCenter(oneOffs[0], {});
- yield resultsPromise;
-
- gBrowser.removeTab(gBrowser.selectedTab);
-});
-
-// Presses the Return key when a one-off is selected.
-add_task(function* oneOffReturn() {
- gBrowser.selectedTab = gBrowser.addTab();
-
- // We are explicitly using something that looks like a url, to make the test
- // stricter. Even if it looks like a url, we should search.
- let typedValue = "foo.bar";
- yield promiseAutocompleteResultPopup(typedValue, window, true);
-
- assertState(0, -1, typedValue);
-
- // Alt+Down to select the first one-off.
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true })
- assertState(0, 0, typedValue);
-
- let resultsPromise =
- BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false,
- "http://mochi.test:8888/");
- EventUtils.synthesizeKey("VK_RETURN", {})
- yield resultsPromise;
-
- gBrowser.removeTab(gBrowser.selectedTab);
-});
-
-
-function assertState(result, oneOff, textValue = undefined) {
- Assert.equal(gURLBar.popup.selectedIndex, result,
- "Expected result should be selected");
- Assert.equal(gURLBar.popup.oneOffSearchButtons.selectedButtonIndex, oneOff,
- "Expected one-off should be selected");
- if (textValue !== undefined) {
- Assert.equal(gURLBar.textValue, textValue, "Expected textValue");
- }
-}
-
-function* hidePopup() {
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promisePopupHidden(gURLBar.popup);
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarPrivateBrowsingWindowChange.js b/browser/base/content/test/urlbar/browser_urlbarPrivateBrowsingWindowChange.js
deleted file mode 100644
index 5db0f0ea6..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarPrivateBrowsingWindowChange.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-/**
- * Test that when opening a private browsing window and typing in it before about:privatebrowsing
- * loads, we don't clear the URL bar.
- */
-add_task(function*() {
- let urlbarTestValue = "Mary had a little lamb";
- let win = OpenBrowserWindow({private: true});
- yield BrowserTestUtils.waitForEvent(win, "load");
- let urlbar = win.document.getElementById("urlbar");
- urlbar.value = urlbarTestValue;
- // Need this so the autocomplete controller attaches:
- let focusEv = new FocusEvent("focus", {});
- urlbar.dispatchEvent(focusEv);
- // And so we know input happened:
- let inputEv = new InputEvent("input", {data: "", view: win, bubbles: true});
- urlbar.onInput(inputEv);
- // Check it worked:
- is(urlbar.value, urlbarTestValue, "URL bar value should be there");
- is(win.gBrowser.selectedBrowser.userTypedValue, urlbarTestValue, "browser object should know the url bar value");
-
- let continueTest;
- let continuePromise = new Promise(resolve => continueTest = resolve);
- let wpl = {
- onLocationChange(aWebProgress, aRequest, aLocation) {
- if (aLocation && aLocation.spec == "about:privatebrowsing") {
- continueTest();
- }
- },
- };
- win.gBrowser.addProgressListener(wpl);
-
- yield continuePromise;
- is(urlbar.value, urlbarTestValue,
- "URL bar value should be the same once about:privatebrowsing has loaded");
- is(win.gBrowser.selectedBrowser.userTypedValue, urlbarTestValue,
- "browser object should still know url bar value once about:privatebrowsing has loaded");
- win.gBrowser.removeProgressListener(wpl);
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarRaceWithTabs.js b/browser/base/content/test/urlbar/browser_urlbarRaceWithTabs.js
deleted file mode 100644
index d66514c5a..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarRaceWithTabs.js
+++ /dev/null
@@ -1,57 +0,0 @@
-const kURL = "http://example.org/browser/browser/base/content/test/urlbar/dummy_page.html";
-
-function* addBookmark(bookmark) {
- if (bookmark.keyword) {
- yield PlacesUtils.keywords.insert({
- keyword: bookmark.keyword,
- url: bookmark.url,
- });
- }
-
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: bookmark.url,
- title: bookmark.title,
- });
-
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.remove(bm);
- if (bookmark.keyword) {
- yield PlacesUtils.keywords.remove(bookmark.keyword);
- }
- });
-}
-
-/**
- * Check that if the user hits enter and ctrl-t at the same time, we open the URL in the right tab.
- */
-add_task(function* hitEnterLoadInRightTab() {
- info("Opening new tab");
- let oldTabCreatedPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- BrowserOpenTab();
- let oldTab = (yield oldTabCreatedPromise).target;
- let oldTabLoadedPromise = BrowserTestUtils.browserLoaded(oldTab.linkedBrowser, false, kURL);
- oldTabLoadedPromise.then(() => info("Old tab loaded"));
- let newTabCreatedPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
-
- info("Creating bookmark and keyword");
- yield addBookmark({title: "Test for keyword bookmark and URL", url: kURL, keyword: "urlbarkeyword"});
- info("Filling URL bar, sending <return> and opening a tab");
- gURLBar.value = "urlbarkeyword";
- gURLBar.select();
- EventUtils.sendKey("return");
- BrowserOpenTab();
- info("Waiting for new tab");
- let newTab = (yield newTabCreatedPromise).target;
- info("Created new tab; waiting for either tab to load");
- let newTabLoadedPromise = BrowserTestUtils.browserLoaded(newTab.linkedBrowser, false, kURL);
- newTabLoadedPromise.then(() => info("New tab loaded"));
- yield Promise.race([newTabLoadedPromise, oldTabLoadedPromise]);
- is(newTab.linkedBrowser.currentURI.spec, "about:newtab", "New tab still has about:newtab");
- is(oldTab.linkedBrowser.currentURI.spec, kURL, "Old tab loaded URL");
- info("Closing new tab");
- yield BrowserTestUtils.removeTab(newTab);
- info("Closing old tab");
- yield BrowserTestUtils.removeTab(oldTab);
- info("Finished");
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarRevert.js b/browser/base/content/test/urlbar/browser_urlbarRevert.js
deleted file mode 100644
index 0ce3c8fac..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarRevert.js
+++ /dev/null
@@ -1,37 +0,0 @@
-var tab = null;
-
-function test() {
- waitForExplicitFinish();
-
- let pageLoaded = {
- onStateChange: function onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
- if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
- gBrowser.removeProgressListener(this);
- executeSoon(checkURLBarRevert);
- }
- }
- }
-
- gBrowser.addProgressListener(pageLoaded);
- tab = gBrowser.addTab("http://example.com");
- gBrowser.selectedTab = tab;
-}
-
-function checkURLBarRevert() {
- let originalValue = gURLBar.value;
-
- gBrowser.userTypedValue = "foobar";
- gBrowser.selectedTab = gBrowser.tabs[0];
- gBrowser.selectedTab = tab;
- is(gURLBar.value, "foobar", "location bar displays typed value");
-
- gURLBar.focus();
-
- EventUtils.synthesizeKey("VK_ESCAPE", {});
-
- is(gURLBar.value, originalValue, "ESC reverted the location bar value");
-
- gBrowser.removeTab(tab);
- finish();
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js b/browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js
deleted file mode 100644
index ee0342055..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSingleWordNotification.js
+++ /dev/null
@@ -1,198 +0,0 @@
-"use strict";
-
-var notificationObserver;
-registerCleanupFunction(function() {
- Services.prefs.clearUserPref("browser.fixup.domainwhitelist.localhost");
- if (notificationObserver) {
- notificationObserver.disconnect();
- }
-});
-
-function promiseNotification(aBrowser, value, expected, input) {
- let deferred = Promise.defer();
- let notificationBox = aBrowser.getNotificationBox(aBrowser.selectedBrowser);
- if (expected) {
- info("Waiting for " + value + " notification");
- let checkForNotification = function() {
- if (notificationBox.getNotificationWithValue(value)) {
- info("Saw the notification");
- notificationObserver.disconnect();
- notificationObserver = null;
- deferred.resolve();
- }
- }
- if (notificationObserver) {
- notificationObserver.disconnect();
- }
- notificationObserver = new MutationObserver(checkForNotification);
- notificationObserver.observe(notificationBox, {childList: true});
- } else {
- setTimeout(() => {
- is(notificationBox.getNotificationWithValue(value), null,
- `We are expecting to not get a notification for ${input}`);
- deferred.resolve();
- }, 1000);
- }
- return deferred.promise;
-}
-
-function* runURLBarSearchTest({valueToOpen, expectSearch, expectNotification, aWindow=window}) {
- aWindow.gURLBar.value = valueToOpen;
- let expectedURI;
- if (!expectSearch) {
- expectedURI = "http://" + valueToOpen + "/";
- } else {
- yield new Promise(resolve => {
- Services.search.init(resolve);
- });
- expectedURI = Services.search.defaultEngine.getSubmission(valueToOpen, null, "keyword").uri.spec;
- }
- aWindow.gURLBar.focus();
- let docLoadPromise = waitForDocLoadAndStopIt(expectedURI, aWindow.gBrowser.selectedBrowser);
- EventUtils.synthesizeKey("VK_RETURN", {}, aWindow);
-
- yield Promise.all([
- docLoadPromise,
- promiseNotification(aWindow.gBrowser, "keyword-uri-fixup", expectNotification, valueToOpen)
- ]);
-}
-
-add_task(function* test_navigate_full_domain() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "www.mozilla.org",
- expectSearch: false,
- expectNotification: false,
- });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_navigate_decimal_ip() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "1234",
- expectSearch: true,
- expectNotification: false,
- });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_navigate_decimal_ip_with_path() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "1234/12",
- expectSearch: true,
- expectNotification: false,
- });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_navigate_large_number() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "123456789012345",
- expectSearch: true,
- expectNotification: false
- });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_navigate_small_hex_number() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "0x1f00ffff",
- expectSearch: true,
- expectNotification: false
- });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_navigate_large_hex_number() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "0x7f0000017f000001",
- expectSearch: true,
- expectNotification: false
- });
- gBrowser.removeTab(tab);
-});
-
-function get_test_function_for_localhost_with_hostname(hostName, isPrivate) {
- return function* test_navigate_single_host() {
- const pref = "browser.fixup.domainwhitelist.localhost";
- let win;
- if (isPrivate) {
- let promiseWin = BrowserTestUtils.waitForNewWindow();
- win = OpenBrowserWindow({private: true});
- yield promiseWin;
- let deferredOpenFocus = Promise.defer();
- waitForFocus(deferredOpenFocus.resolve, win);
- yield deferredOpenFocus.promise;
- } else {
- win = window;
- }
- let browser = win.gBrowser;
- let tab = yield BrowserTestUtils.openNewForegroundTab(browser);
-
- Services.prefs.setBoolPref(pref, false);
- yield* runURLBarSearchTest({
- valueToOpen: hostName,
- expectSearch: true,
- expectNotification: true,
- aWindow: win,
- });
-
- let notificationBox = browser.getNotificationBox(tab.linkedBrowser);
- let notification = notificationBox.getNotificationWithValue("keyword-uri-fixup");
- let docLoadPromise = waitForDocLoadAndStopIt("http://" + hostName + "/", tab.linkedBrowser);
- notification.querySelector(".notification-button-default").click();
-
- // check pref value
- let prefValue = Services.prefs.getBoolPref(pref);
- is(prefValue, !isPrivate, "Pref should have the correct state.");
-
- yield docLoadPromise;
- browser.removeTab(tab);
-
- // Now try again with the pref set.
- tab = browser.selectedTab = browser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- // In a private window, the notification should appear again.
- yield* runURLBarSearchTest({
- valueToOpen: hostName,
- expectSearch: isPrivate,
- expectNotification: isPrivate,
- aWindow: win,
- });
- browser.removeTab(tab);
- if (isPrivate) {
- info("Waiting for private window to close");
- yield BrowserTestUtils.closeWindow(win);
- let deferredFocus = Promise.defer();
- info("Waiting for focus");
- waitForFocus(deferredFocus.resolve, window);
- yield deferredFocus.promise;
- }
- }
-}
-
-add_task(get_test_function_for_localhost_with_hostname("localhost"));
-add_task(get_test_function_for_localhost_with_hostname("localhost."));
-add_task(get_test_function_for_localhost_with_hostname("localhost", true));
-
-add_task(function* test_navigate_invalid_url() {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield* runURLBarSearchTest({
- valueToOpen: "mozilla is awesome",
- expectSearch: true,
- expectNotification: false,
- });
- gBrowser.removeTab(tab);
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js b/browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js
deleted file mode 100644
index 5146ba98c..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestions.js
+++ /dev/null
@@ -1,66 +0,0 @@
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-// Must run first.
-add_task(function* prepare() {
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
- let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- let oldCurrentEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
- Services.search.currentEngine = oldCurrentEngine;
-
- // Clicking suggestions causes visits to search results pages, so clear that
- // history now.
- yield PlacesTestUtils.clearHistory();
-
- // Make sure the popup is closed for the next test.
- gURLBar.blur();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed");
- });
-});
-
-add_task(function* clickSuggestion() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo");
- let [idx, suggestion, engineName] = yield promiseFirstSuggestion();
- Assert.equal(engineName,
- "browser_searchSuggestionEngine%20searchSuggestionEngine.xml",
- "Expected suggestion engine");
- let item = gURLBar.popup.richlistbox.getItemAtIndex(idx);
-
- let uri = Services.search.currentEngine.getSubmission(suggestion).uri;
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser,
- false, uri.spec);
- item.click();
- yield loadPromise;
- yield BrowserTestUtils.removeTab(tab);
-});
-
-function getFirstSuggestion() {
- let controller = gURLBar.popup.input.controller;
- let matchCount = controller.matchCount;
- for (let i = 0; i < matchCount; i++) {
- let url = controller.getValueAt(i);
- let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/);
- if (mozActionMatch) {
- let [, type, paramStr] = mozActionMatch;
- let params = JSON.parse(paramStr);
- if (type == "searchengine" && "searchSuggestion" in params) {
- return [i, params.searchSuggestion, params.engineName];
- }
- }
- }
- return [-1, null, null];
-}
-
-function* promiseFirstSuggestion() {
- let tuple = [-1, null, null];
- yield BrowserTestUtils.waitForCondition(() => {
- tuple = getFirstSuggestion();
- return tuple[0] >= 0;
- });
- return tuple;
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js b/browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js
deleted file mode 100644
index 94ae8a3ff..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarSearchSuggestionsNotification.js
+++ /dev/null
@@ -1,254 +0,0 @@
-const SUGGEST_ALL_PREF = "browser.search.suggest.enabled";
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-const CHOICE_PREF = "browser.urlbar.userMadeSearchSuggestionsChoice";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-// Must run first.
-add_task(function* prepare() {
- let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- let oldCurrentEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- registerCleanupFunction(function* () {
- Services.search.currentEngine = oldCurrentEngine;
- Services.prefs.clearUserPref(SUGGEST_ALL_PREF);
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
-
- // Disable the notification for future tests so it doesn't interfere with
- // them. clearUserPref() won't work because by default the pref is false.
- yield setUserMadeChoicePref(true);
-
- // Make sure the popup is closed for the next test.
- gURLBar.blur();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed");
- });
-});
-
-add_task(function* focus() {
- // Focusing the urlbar used to open the popup in order to show the
- // notification, but it doesn't anymore. Make sure it does not.
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- yield setUserMadeChoicePref(false);
- gURLBar.blur();
- gURLBar.focus();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should remain closed");
-});
-
-add_task(function* dismissWithoutResults() {
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- yield setUserMadeChoicePref(false);
- gURLBar.blur();
- gURLBar.focus();
- let popupPromise = promisePopupShown(gURLBar.popup);
- gURLBar.openPopup();
- yield popupPromise;
- Assert.ok(gURLBar.popup.popupOpen, "popup should be open");
- assertVisible(true);
- Assert.equal(gURLBar.popup._matchCount, 0, "popup should have no results");
- let disableButton = document.getAnonymousElementByAttribute(
- gURLBar.popup, "anonid", "search-suggestions-notification-disable"
- );
- let transitionPromise = promiseTransition();
- disableButton.click();
- yield transitionPromise;
- Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed");
- gURLBar.blur();
- gURLBar.focus();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should remain closed");
- yield promiseAutocompleteResultPopup("foo");
- Assert.ok(gURLBar.popup.popupOpen, "popup should be open");
- assertVisible(false);
-});
-
-add_task(function* dismissWithResults() {
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- yield setUserMadeChoicePref(false);
- gURLBar.blur();
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo");
- Assert.ok(gURLBar.popup.popupOpen, "popup should be open");
- assertVisible(true);
- Assert.ok(gURLBar.popup._matchCount > 0, "popup should have results");
- let disableButton = document.getAnonymousElementByAttribute(
- gURLBar.popup, "anonid", "search-suggestions-notification-disable"
- );
- let transitionPromise = promiseTransition();
- disableButton.click();
- yield transitionPromise;
- Assert.ok(gURLBar.popup.popupOpen, "popup should remain open");
- gURLBar.blur();
- gURLBar.focus();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should remain closed");
- yield promiseAutocompleteResultPopup("foo");
- Assert.ok(gURLBar.popup.popupOpen, "popup should be open");
- assertVisible(false);
-});
-
-add_task(function* disable() {
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- yield setUserMadeChoicePref(false);
- gURLBar.blur();
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo");
- Assert.ok(gURLBar.popup.popupOpen, "popup should be open");
- assertVisible(true);
- let disableButton = document.getAnonymousElementByAttribute(
- gURLBar.popup, "anonid", "search-suggestions-notification-disable"
- );
- let transitionPromise = promiseTransition();
- disableButton.click();
- yield transitionPromise;
- gURLBar.blur();
- yield promiseAutocompleteResultPopup("foo");
- Assert.ok(!suggestionsPresent());
-});
-
-add_task(function* enable() {
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, false);
- yield setUserMadeChoicePref(false);
- gURLBar.blur();
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo");
- assertVisible(true);
- Assert.ok(!suggestionsPresent());
- let enableButton = document.getAnonymousElementByAttribute(
- gURLBar.popup, "anonid", "search-suggestions-notification-enable"
- );
- let searchPromise = BrowserTestUtils.waitForCondition(suggestionsPresent,
- "waiting for suggestions");
- enableButton.click();
- yield searchPromise;
- // Clicking Yes should trigger a new search so that suggestions appear
- // immediately.
- Assert.ok(suggestionsPresent());
- gURLBar.blur();
- gURLBar.focus();
- // Suggestions should still be present in a new search of course.
- yield promiseAutocompleteResultPopup("bar");
- Assert.ok(suggestionsPresent());
-});
-
-add_task(function* privateWindow() {
- // Since suggestions are disabled in private windows, the notification should
- // not appear even when suggestions are otherwise enabled.
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- win.gURLBar.blur();
- win.gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo", win);
- assertVisible(false, win);
- win.gURLBar.blur();
- yield BrowserTestUtils.closeWindow(win);
-});
-
-add_task(function* multipleWindows() {
- // Opening multiple windows, using their urlbars, and then dismissing the
- // notification in one should dismiss the notification in all.
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, false);
- yield setUserMadeChoicePref(false);
-
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("win1");
- assertVisible(true);
-
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
- win2.gURLBar.focus();
- yield promiseAutocompleteResultPopup("win2", win2);
- assertVisible(true, win2);
-
- let win3 = yield BrowserTestUtils.openNewBrowserWindow();
- win3.gURLBar.focus();
- yield promiseAutocompleteResultPopup("win3", win3);
- assertVisible(true, win3);
-
- let enableButton = win3.document.getAnonymousElementByAttribute(
- win3.gURLBar.popup, "anonid", "search-suggestions-notification-enable"
- );
- let transitionPromise = promiseTransition(win3);
- enableButton.click();
- yield transitionPromise;
- assertVisible(false, win3);
-
- win2.gURLBar.focus();
- yield promiseAutocompleteResultPopup("win2done", win2);
- assertVisible(false, win2);
-
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("win1done");
- assertVisible(false);
-
- yield BrowserTestUtils.closeWindow(win2);
- yield BrowserTestUtils.closeWindow(win3);
-});
-
-add_task(function* enableOutsideNotification() {
- // Setting the suggest.searches pref outside the notification (e.g., by
- // ticking the checkbox in the preferences window) should hide it.
- Services.prefs.setBoolPref(SUGGEST_ALL_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, false);
- yield setUserMadeChoicePref(false);
-
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("foo");
- assertVisible(false);
-});
-
-/**
- * Setting the choice pref triggers a pref observer in the urlbar, which hides
- * the notification if it's present. This function returns a promise that's
- * resolved once the observer fires.
- *
- * @param userMadeChoice A boolean, the pref's new value.
- * @return A Promise that's resolved when the observer fires -- or, if the pref
- * is currently the given value, that's resolved immediately.
- */
-function setUserMadeChoicePref(userMadeChoice) {
- return new Promise(resolve => {
- let currentUserMadeChoice = Services.prefs.getBoolPref(CHOICE_PREF);
- if (currentUserMadeChoice != userMadeChoice) {
- Services.prefs.addObserver(CHOICE_PREF, function obs(subj, topic, data) {
- Services.prefs.removeObserver(CHOICE_PREF, obs);
- resolve();
- }, false);
- }
- Services.prefs.setBoolPref(CHOICE_PREF, userMadeChoice);
- if (currentUserMadeChoice == userMadeChoice) {
- resolve();
- }
- });
-}
-
-function suggestionsPresent() {
- let controller = gURLBar.popup.input.controller;
- let matchCount = controller.matchCount;
- for (let i = 0; i < matchCount; i++) {
- let url = controller.getValueAt(i);
- let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/);
- if (mozActionMatch) {
- let [, type, paramStr] = mozActionMatch;
- let params = JSON.parse(paramStr);
- if (type == "searchengine" && "searchSuggestion" in params) {
- return true;
- }
- }
- }
- return false;
-}
-
-function assertVisible(visible, win=window) {
- let style =
- win.getComputedStyle(win.gURLBar.popup.searchSuggestionsNotification);
- Assert.equal(style.visibility, visible ? "visible" : "collapse");
-}
-
-function promiseTransition(win=window) {
- return new Promise(resolve => {
- win.gURLBar.popup.addEventListener("transitionend", function onEnd() {
- win.gURLBar.popup.removeEventListener("transitionend", onEnd, true);
- // The urlbar needs to handle the transitionend first, but that happens
- // naturally since promises are resolved at the end of the current tick.
- resolve();
- }, true);
- });
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js
deleted file mode 100644
index 8c28401ea..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js
+++ /dev/null
@@ -1,216 +0,0 @@
-"use strict";
-
-Cu.import("resource:///modules/BrowserUITelemetry.jsm");
-
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-// Must run first.
-add_task(function* prepare() {
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
- let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME);
- let oldCurrentEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
- Services.search.currentEngine = oldCurrentEngine;
-
- // Clicking urlbar results causes visits to their associated pages, so clear
- // that history now.
- yield PlacesTestUtils.clearHistory();
-
- // Make sure the popup is closed for the next test.
- gURLBar.blur();
- Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed");
- });
-
- // Move the mouse away from the urlbar one-offs so that a one-off engine is
- // not inadvertently selected.
- yield new Promise(resolve => {
- EventUtils.synthesizeNativeMouseMove(window.document.documentElement, 0, 0,
- resolve);
- });
-});
-
-add_task(function* heuristicResultMouse() {
- yield compareCounts(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("heuristicResult");
- let action = getActionAtIndex(0);
- Assert.ok(!!action, "there should be an action at index 0");
- Assert.equal(action.type, "searchengine", "type should be searchengine");
- let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- gURLBar.popup.richlistbox.getItemAtIndex(0).click();
- yield loadPromise;
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-add_task(function* heuristicResultKeyboard() {
- yield compareCounts(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("heuristicResult");
- let action = getActionAtIndex(0);
- Assert.ok(!!action, "there should be an action at index 0");
- Assert.equal(action.type, "searchengine", "type should be searchengine");
- let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- EventUtils.sendKey("return");
- yield loadPromise;
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-add_task(function* searchSuggestionMouse() {
- yield compareCounts(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("searchSuggestion");
- let idx = getFirstSuggestionIndex();
- Assert.ok(idx >= 0, "there should be a first suggestion");
- let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- gURLBar.popup.richlistbox.getItemAtIndex(idx).click();
- yield loadPromise;
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-add_task(function* searchSuggestionKeyboard() {
- yield compareCounts(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- gURLBar.focus();
- yield promiseAutocompleteResultPopup("searchSuggestion");
- let idx = getFirstSuggestionIndex();
- Assert.ok(idx >= 0, "there should be a first suggestion");
- let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- while (idx--) {
- EventUtils.sendKey("down");
- }
- EventUtils.sendKey("return");
- yield loadPromise;
- yield BrowserTestUtils.removeTab(tab);
- });
-});
-
-/**
- * This does three things: gets current telemetry/FHR counts, calls
- * clickCallback, gets telemetry/FHR counts again to compare them to the old
- * counts.
- *
- * @param clickCallback Use this to open the urlbar popup and choose and click a
- * result.
- */
-function* compareCounts(clickCallback) {
- // Search events triggered by clicks (not the Return key in the urlbar) are
- // recorded in three places:
- // * BrowserUITelemetry
- // * Telemetry histogram named "SEARCH_COUNTS"
- // * FHR
-
- let engine = Services.search.currentEngine;
- let engineID = "org.mozilla.testsearchsuggestions";
-
- // First, get the current counts.
-
- // BrowserUITelemetry
- let uiTelemCount = 0;
- let bucket = BrowserUITelemetry.currentBucket;
- let events = BrowserUITelemetry.getToolbarMeasures().countableEvents;
- if (events[bucket] &&
- events[bucket].search &&
- events[bucket].search.urlbar) {
- uiTelemCount = events[bucket].search.urlbar;
- }
-
- // telemetry histogram SEARCH_COUNTS
- let histogramCount = 0;
- let histogramKey = engineID + ".urlbar";
- let histogram;
- try {
- histogram = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
- } catch (ex) {
- // No searches performed yet, not a problem.
- }
- if (histogram) {
- let snapshot = histogram.snapshot();
- if (histogramKey in snapshot) {
- histogramCount = snapshot[histogramKey].sum;
- }
- }
-
- // FHR -- first make sure the engine has an identifier so that FHR is happy.
- Object.defineProperty(engine.wrappedJSObject, "identifier",
- { value: engineID });
-
- gURLBar.focus();
- yield clickCallback();
-
- // Now get the new counts and compare them to the old.
-
- // BrowserUITelemetry
- events = BrowserUITelemetry.getToolbarMeasures().countableEvents;
- Assert.ok(bucket in events, "bucket should be recorded");
- events = events[bucket];
- Assert.ok("search" in events, "search should be recorded");
- events = events.search;
- Assert.ok("urlbar" in events, "urlbar should be recorded");
- Assert.equal(events.urlbar, uiTelemCount + 1,
- "clicked suggestion should be recorded");
-
- // telemetry histogram SEARCH_COUNTS
- histogram = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
- let snapshot = histogram.snapshot();
- Assert.ok(histogramKey in snapshot, "histogram with key should be recorded");
- Assert.equal(snapshot[histogramKey].sum, histogramCount + 1,
- "histogram sum should be incremented");
-}
-
-/**
- * Returns the "action" object at the given index in the urlbar results:
- * { type, params: {}}
- *
- * @param index The index in the urlbar results.
- * @return An action object, or null if index >= number of results.
- */
-function getActionAtIndex(index) {
- let controller = gURLBar.popup.input.controller;
- if (controller.matchCount <= index) {
- return null;
- }
- let url = controller.getValueAt(index);
- let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/);
- if (!mozActionMatch) {
- let msg = "result at index " + index + " is not a moz-action: " + url;
- Assert.ok(false, msg);
- throw new Error(msg);
- }
- let [, type, paramStr] = mozActionMatch;
- return {
- type: type,
- params: JSON.parse(paramStr),
- };
-}
-
-/**
- * Returns the index of the first search suggestion in the urlbar results.
- *
- * @return An index, or -1 if there are no search suggestions.
- */
-function getFirstSuggestionIndex() {
- let controller = gURLBar.popup.input.controller;
- let matchCount = controller.matchCount;
- for (let i = 0; i < matchCount; i++) {
- let url = controller.getValueAt(i);
- let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/);
- if (mozActionMatch) {
- let [, type, paramStr] = mozActionMatch;
- let params = JSON.parse(paramStr);
- if (type == "searchengine" && "searchSuggestion" in params) {
- return i;
- }
- }
- }
- return -1;
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarStop.js b/browser/base/content/test/urlbar/browser_urlbarStop.js
deleted file mode 100644
index 8cf9d8017..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarStop.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-
-const goodURL = "http://mochi.test:8888/";
-const badURL = "http://mochi.test:8888/whatever.html";
-
-add_task(function* () {
- gBrowser.selectedTab = gBrowser.addTab(goodURL);
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- is(gURLBar.textValue, gURLBar.trimValue(goodURL), "location bar reflects loaded page");
-
- yield typeAndSubmitAndStop(badURL);
- is(gURLBar.textValue, gURLBar.trimValue(goodURL), "location bar reflects loaded page after stop()");
- gBrowser.removeCurrentTab();
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- is(gURLBar.textValue, "", "location bar is empty");
-
- yield typeAndSubmitAndStop(badURL);
- is(gURLBar.textValue, gURLBar.trimValue(badURL), "location bar reflects stopped page in an empty tab");
- gBrowser.removeCurrentTab();
-});
-
-function* typeAndSubmitAndStop(url) {
- yield promiseAutocompleteResultPopup(url, window, true);
- is(gURLBar.textValue, gURLBar.trimValue(url), "location bar reflects loading page");
-
- let promise = waitForDocLoadAndStopIt(url, gBrowser.selectedBrowser, false);
- gURLBar.handleCommand();
- yield promise;
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarTrimURLs.js b/browser/base/content/test/urlbar/browser_urlbarTrimURLs.js
deleted file mode 100644
index 913e99a8e..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarTrimURLs.js
+++ /dev/null
@@ -1,98 +0,0 @@
-add_task(function* () {
- const PREF_TRIMURLS = "browser.urlbar.trimURLs";
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- registerCleanupFunction(function* () {
- yield BrowserTestUtils.removeTab(tab);
- Services.prefs.clearUserPref(PREF_TRIMURLS);
- URLBarSetURI();
- });
-
- Services.prefs.setBoolPref(PREF_TRIMURLS, true);
-
- testVal("http://mozilla.org/", "mozilla.org");
- testVal("https://mozilla.org/", "https://mozilla.org");
- testVal("http://mözilla.org/", "mözilla.org");
- testVal("http://mozilla.imaginatory/", "mozilla.imaginatory");
- testVal("http://www.mozilla.org/", "www.mozilla.org");
- testVal("http://sub.mozilla.org/", "sub.mozilla.org");
- testVal("http://sub1.sub2.sub3.mozilla.org/", "sub1.sub2.sub3.mozilla.org");
- testVal("http://mozilla.org/file.ext", "mozilla.org/file.ext");
- testVal("http://mozilla.org/sub/", "mozilla.org/sub/");
-
- testVal("http://ftp.mozilla.org/", "ftp.mozilla.org");
- testVal("http://ftp1.mozilla.org/", "ftp1.mozilla.org");
- testVal("http://ftp42.mozilla.org/", "ftp42.mozilla.org");
- testVal("http://ftpx.mozilla.org/", "ftpx.mozilla.org");
- testVal("ftp://ftp.mozilla.org/", "ftp://ftp.mozilla.org");
- testVal("ftp://ftp1.mozilla.org/", "ftp://ftp1.mozilla.org");
- testVal("ftp://ftp42.mozilla.org/", "ftp://ftp42.mozilla.org");
- testVal("ftp://ftpx.mozilla.org/", "ftp://ftpx.mozilla.org");
-
- testVal("https://user:pass@mozilla.org/", "https://user:pass@mozilla.org");
- testVal("https://user@mozilla.org/", "https://user@mozilla.org");
- testVal("http://user:pass@mozilla.org/", "user:pass@mozilla.org");
- testVal("http://user@mozilla.org/", "user@mozilla.org");
- testVal("http://sub.mozilla.org:666/", "sub.mozilla.org:666");
-
- testVal("https://[fe80::222:19ff:fe11:8c76]/file.ext");
- testVal("http://[fe80::222:19ff:fe11:8c76]/", "[fe80::222:19ff:fe11:8c76]");
- testVal("https://user:pass@[fe80::222:19ff:fe11:8c76]:666/file.ext");
- testVal("http://user:pass@[fe80::222:19ff:fe11:8c76]:666/file.ext", "user:pass@[fe80::222:19ff:fe11:8c76]:666/file.ext");
-
- testVal("mailto:admin@mozilla.org");
- testVal("gopher://mozilla.org/");
- testVal("about:config");
- testVal("jar:http://mozilla.org/example.jar!/");
- testVal("view-source:http://mozilla.org/");
-
- // Behaviour for hosts with no dots depends on the whitelist:
- let fixupWhitelistPref = "browser.fixup.domainwhitelist.localhost";
- Services.prefs.setBoolPref(fixupWhitelistPref, false);
- testVal("http://localhost");
- Services.prefs.setBoolPref(fixupWhitelistPref, true);
- testVal("http://localhost", "localhost");
- Services.prefs.clearUserPref(fixupWhitelistPref);
-
- testVal("http:// invalid url");
-
- testVal("http://someotherhostwithnodots");
- testVal("http://localhost/ foo bar baz");
- testVal("http://localhost.localdomain/ foo bar baz", "localhost.localdomain/ foo bar baz");
-
- Services.prefs.setBoolPref(PREF_TRIMURLS, false);
-
- testVal("http://mozilla.org/");
-
- Services.prefs.setBoolPref(PREF_TRIMURLS, true);
-
- let promiseLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser,
- false, "http://example.com/");
- gBrowser.loadURI("http://example.com/");
- yield promiseLoaded;
-
- yield testCopy("example.com", "http://example.com/")
-
- SetPageProxyState("invalid");
- gURLBar.valueIsTyped = true;
- yield testCopy("example.com", "example.com");
-});
-
-function testVal(originalValue, targetValue) {
- gURLBar.value = originalValue;
- gURLBar.valueIsTyped = false;
- is(gURLBar.textValue, targetValue || originalValue, "url bar value set");
-}
-
-function testCopy(originalValue, targetValue) {
- return new Promise((resolve, reject) => {
- waitForClipboard(targetValue, function () {
- is(gURLBar.textValue, originalValue, "url bar copy value set");
-
- gURLBar.focus();
- gURLBar.select();
- goDoCommand("cmd_copy");
- }, resolve, reject);
- });
-}
diff --git a/browser/base/content/test/urlbar/browser_urlbarUpdateForDomainCompletion.js b/browser/base/content/test/urlbar/browser_urlbarUpdateForDomainCompletion.js
deleted file mode 100644
index c3cdf507f..000000000
--- a/browser/base/content/test/urlbar/browser_urlbarUpdateForDomainCompletion.js
+++ /dev/null
@@ -1,17 +0,0 @@
-"use strict";
-
-/**
- * Disable keyword.enabled (so no keyword search), and check that when you type in
- * "example" and hit enter, the browser loads and the URL bar is updated accordingly.
- */
-add_task(function* () {
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({set: [["keyword.enabled", false]]}, resolve));
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
- gURLBar.value = "example";
- gURLBar.select();
- let loadPromise = BrowserTestUtils.browserLoaded(browser, false, url => url == "http://www.example.com/");
- EventUtils.sendKey("return");
- yield loadPromise;
- is(gURLBar.textValue, "www.example.com");
- });
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbar_autoFill_backspaced.js b/browser/base/content/test/urlbar/browser_urlbar_autoFill_backspaced.js
deleted file mode 100644
index 7fefd3f77..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_autoFill_backspaced.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/* This test ensures that backspacing autoFilled values still allows to
- * confirm the remaining value.
- */
-
-function* test_autocomplete(data) {
- let {desc, typed, autofilled, modified, keys, action, onAutoFill} = data;
- info(desc);
-
- yield promiseAutocompleteResultPopup(typed);
- is(gURLBar.textValue, autofilled, "autofilled value is as expected");
- if (onAutoFill)
- onAutoFill()
-
- keys.forEach(key => EventUtils.synthesizeKey(key, {}));
-
- is(gURLBar.textValue, modified, "backspaced value is as expected");
-
- yield promiseSearchComplete();
-
- ok(gURLBar.popup.richlistbox.children.length > 0, "Should get at least 1 result");
- let result = gURLBar.popup.richlistbox.children[0];
- let type = result.getAttribute("type");
- let types = type.split(/\s+/);
- ok(types.indexOf(action) >= 0, `The type attribute "${type}" includes the expected action "${action}"`);
-
- gURLBar.popup.hidePopup();
- yield promisePopupHidden(gURLBar.popup);
- gURLBar.blur();
-}
-
-add_task(function* () {
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref("browser.urlbar.autoFill");
- gURLBar.handleRevert();
- yield PlacesTestUtils.clearHistory();
- });
- Services.prefs.setBoolPref("browser.urlbar.autoFill", true);
-
- // Add a typed visit, so it will be autofilled.
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://example.com/"),
- transition: Ci.nsINavHistoryService.TRANSITION_TYPED
- });
-
- yield test_autocomplete({ desc: "DELETE the autofilled part should search",
- typed: "exam",
- autofilled: "example.com/",
- modified: "exam",
- keys: ["VK_DELETE"],
- action: "searchengine"
- });
- yield test_autocomplete({ desc: "DELETE the final slash should visit",
- typed: "example.com",
- autofilled: "example.com/",
- modified: "example.com",
- keys: ["VK_DELETE"],
- action: "visiturl"
- });
-
- yield test_autocomplete({ desc: "BACK_SPACE the autofilled part should search",
- typed: "exam",
- autofilled: "example.com/",
- modified: "exam",
- keys: ["VK_BACK_SPACE"],
- action: "searchengine"
- });
- yield test_autocomplete({ desc: "BACK_SPACE the final slash should visit",
- typed: "example.com",
- autofilled: "example.com/",
- modified: "example.com",
- keys: ["VK_BACK_SPACE"],
- action: "visiturl"
- });
-
- yield test_autocomplete({ desc: "DELETE the autofilled part, then BACK_SPACE, should search",
- typed: "exam",
- autofilled: "example.com/",
- modified: "exa",
- keys: ["VK_DELETE", "VK_BACK_SPACE"],
- action: "searchengine"
- });
- yield test_autocomplete({ desc: "DELETE the final slash, then BACK_SPACE, should search",
- typed: "example.com",
- autofilled: "example.com/",
- modified: "example.co",
- keys: ["VK_DELETE", "VK_BACK_SPACE"],
- action: "visiturl"
- });
-
- yield test_autocomplete({ desc: "BACK_SPACE the autofilled part, then BACK_SPACE, should search",
- typed: "exam",
- autofilled: "example.com/",
- modified: "exa",
- keys: ["VK_BACK_SPACE", "VK_BACK_SPACE"],
- action: "searchengine"
- });
- yield test_autocomplete({ desc: "BACK_SPACE the final slash, then BACK_SPACE, should search",
- typed: "example.com",
- autofilled: "example.com/",
- modified: "example.co",
- keys: ["VK_BACK_SPACE", "VK_BACK_SPACE"],
- action: "visiturl"
- });
-
- yield test_autocomplete({ desc: "BACK_SPACE after blur should search",
- typed: "ex",
- autofilled: "example.com/",
- modified: "e",
- keys: ["VK_BACK_SPACE"],
- action: "searchengine",
- onAutoFill: () => {
- gURLBar.blur();
- gURLBar.focus();
- gURLBar.selectionStart = 1;
- gURLBar.selectionEnd = 12;
- }
- });
- yield test_autocomplete({ desc: "DELETE after blur should search",
- typed: "ex",
- autofilled: "example.com/",
- modified: "e",
- keys: ["VK_DELETE"],
- action: "searchengine",
- onAutoFill: () => {
- gURLBar.blur();
- gURLBar.focus();
- gURLBar.selectionStart = 1;
- gURLBar.selectionEnd = 12;
- }
- });
- yield test_autocomplete({ desc: "double BACK_SPACE after blur should search",
- typed: "ex",
- autofilled: "example.com/",
- modified: "e",
- keys: ["VK_BACK_SPACE", "VK_BACK_SPACE"],
- action: "searchengine",
- onAutoFill: () => {
- gURLBar.blur();
- gURLBar.focus();
- gURLBar.selectionStart = 2;
- gURLBar.selectionEnd = 12;
- }
- });
-
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbar_blanking.js b/browser/base/content/test/urlbar/browser_urlbar_blanking.js
deleted file mode 100644
index 13660edab..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_blanking.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-add_task(function*() {
- for (let page of gInitialPages) {
- if (page == "about:newtab") {
- // New tab preloading makes this a pain to test, so skip
- continue;
- }
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, page);
- ok(!gURLBar.value, "The URL bar should be empty if we load a plain " + page + " page.");
- yield BrowserTestUtils.removeTab(tab);
- }
-});
-
-add_task(function*() {
- const URI = "http://www.example.com/browser/browser/base/content/test/urlbar/file_blank_but_not_blank.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URI);
- is(gURLBar.value, URI, "The URL bar should match the URI");
- let browserLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- ContentTask.spawn(tab.linkedBrowser, null, function() {
- content.document.querySelector('a').click();
- });
- yield browserLoaded;
- ok(gURLBar.value.startsWith("javascript"), "The URL bar should have the JS URI");
- // When reloading, the javascript: uri we're using will throw an exception.
- // That's deliberate, so we need to tell mochitest to ignore it:
- SimpleTest.expectUncaughtException(true);
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- // This is sync, so by the time we return we should have changed the URL bar.
- content.location.reload();
- });
- ok(!!gURLBar.value, "URL bar should not be blank.");
- yield BrowserTestUtils.removeTab(tab);
- SimpleTest.expectUncaughtException(false);
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbar_locationchange_urlbar_edit_dos.js b/browser/base/content/test/urlbar/browser_urlbar_locationchange_urlbar_edit_dos.js
deleted file mode 100644
index 63ed58a62..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_locationchange_urlbar_edit_dos.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-function* checkURLBarValueStays(browser) {
- gURLBar.select();
- EventUtils.synthesizeKey("a", {});
- is(gURLBar.value, "a", "URL bar value should match after sending a key");
- yield new Promise(resolve => {
- let listener = {
- onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
- ok(aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT,
- "Should only get a same document location change");
- gBrowser.selectedBrowser.removeProgressListener(filter);
- filter = null;
- resolve();
- },
- };
- let filter = Cc["@mozilla.org/appshell/component/browser-status-filter;1"]
- .createInstance(Ci.nsIWebProgress);
- filter.addProgressListener(listener, Ci.nsIWebProgress.NOTIFY_ALL);
- gBrowser.selectedBrowser.addProgressListener(filter);
- });
- is(gURLBar.value, "a", "URL bar should not have been changed by location changes.");
-}
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/browser/browser/base/content/test/urlbar/file_urlbar_edit_dos.html"
- }, function*(browser) {
- yield ContentTask.spawn(browser, "", function() {
- content.wrappedJSObject.dos_hash();
- });
- yield checkURLBarValueStays(browser);
- yield ContentTask.spawn(browser, "", function() {
- content.clearTimeout(content.wrappedJSObject.dos_timeout);
- content.wrappedJSObject.dos_pushState();
- });
- yield checkURLBarValueStays(browser);
- });
-});
-
diff --git a/browser/base/content/test/urlbar/browser_urlbar_remoteness_switch.js b/browser/base/content/test/urlbar/browser_urlbar_remoteness_switch.js
deleted file mode 100644
index 9a1df0505..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_remoteness_switch.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-
-/**
- * Verify that when loading and going back/forward through history between URLs
- * loaded in the content process, and URLs loaded in the parent process, we
- * don't set the URL for the tab to about:blank inbetween the loads.
- */
-add_task(function*() {
- let url = "http://www.example.com/foo.html";
- yield BrowserTestUtils.withNewTab({gBrowser, url}, function*(browser) {
- let wpl = {
- onLocationChange(wpl, request, location, flags) {
- if (location.schemeIs("about")) {
- is(location.spec, "about:config", "Only about: location change should be for about:preferences");
- } else {
- is(location.spec, url, "Only non-about: location change should be for the http URL we're dealing with.");
- }
- },
- };
- gBrowser.addProgressListener(wpl);
-
- let didLoad = BrowserTestUtils.browserLoaded(browser, null, function(loadedURL) {
- return loadedURL == "about:config";
- });
- yield BrowserTestUtils.loadURI(browser, "about:config");
- yield didLoad;
-
- gBrowser.goBack();
- yield BrowserTestUtils.browserLoaded(browser, null, function(loadedURL) {
- return url == loadedURL;
- });
- gBrowser.goForward();
- yield BrowserTestUtils.browserLoaded(browser, null, function(loadedURL) {
- return loadedURL == "about:config";
- });
- gBrowser.removeProgressListener(wpl);
- });
-});
-
diff --git a/browser/base/content/test/urlbar/browser_urlbar_searchsettings.js b/browser/base/content/test/urlbar/browser_urlbar_searchsettings.js
deleted file mode 100644
index 04b1c508b..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_searchsettings.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-add_task(function*() {
- let button = document.getElementById("urlbar-search-settings");
- if (!button) {
- ok("Skipping test");
- return;
- }
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* () {
- let popupopened = BrowserTestUtils.waitForEvent(gURLBar.popup, "popupshown");
-
- gURLBar.focus();
- EventUtils.synthesizeKey("a", {});
- yield popupopened;
-
- // Since the current tab is blank the preferences pane will load there
- let loaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- let popupclosed = BrowserTestUtils.waitForEvent(gURLBar.popup, "popuphidden");
- EventUtils.synthesizeMouseAtCenter(button, {});
- yield loaded;
- yield popupclosed;
-
- is(gBrowser.selectedBrowser.currentURI.spec, "about:preferences#search",
- "Should have loaded the right page");
- });
-});
diff --git a/browser/base/content/test/urlbar/browser_urlbar_stop_pending.js b/browser/base/content/test/urlbar/browser_urlbar_stop_pending.js
deleted file mode 100644
index 6b6a10ea3..000000000
--- a/browser/base/content/test/urlbar/browser_urlbar_stop_pending.js
+++ /dev/null
@@ -1,138 +0,0 @@
-"use strict";
-
-const SLOW_PAGE = "http://www.example.com/browser/browser/base/content/test/urlbar/slow-page.sjs";
-const SLOW_PAGE2 = "http://mochi.test:8888/browser/browser/base/content/test/urlbar/slow-page.sjs?faster";
-
-/**
- * Check that if we:
- * 1) have a loaded page
- * 2) load a separate URL
- * 3) before the URL for step 2 has finished loading, load a third URL
- * we don't revert to the URL from (1).
- */
-add_task(function*() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com", true, true);
-
- let expectedURLBarChange = SLOW_PAGE;
- let sawChange = false;
- let handler = e => {
- sawChange = true;
- is(gURLBar.value, expectedURLBarChange, "Should not change URL bar value!");
- };
-
- let obs = new MutationObserver(handler);
-
- obs.observe(gURLBar, {attributes: true});
- gURLBar.value = SLOW_PAGE;
- gURLBar.handleCommand();
-
- // If this ever starts going intermittent, we've broken this.
- yield new Promise(resolve => setTimeout(resolve, 200));
- expectedURLBarChange = SLOW_PAGE2;
- let pageLoadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- gURLBar.value = expectedURLBarChange;
- gURLBar.handleCommand();
- is(gURLBar.value, expectedURLBarChange, "Should not have changed URL bar value synchronously.");
- yield pageLoadPromise;
- ok(sawChange, "The URL bar change handler should have been called by the time the page was loaded");
- obs.disconnect();
- obs = null;
- yield BrowserTestUtils.removeTab(tab);
-});
-
-/**
- * Check that if we:
- * 1) middle-click a link to a separate page whose server doesn't respond
- * 2) we switch to that tab and stop the request
- *
- * The URL bar continues to contain the URL of the page we wanted to visit.
- */
-add_task(function*() {
- let socket = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);
- socket.init(-1, true, -1);
- const PORT = socket.port;
- registerCleanupFunction(() => { socket.close(); });
-
- const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "https://example.com");
- const BASE_PAGE = TEST_PATH + "dummy_page.html";
- const SLOW_HOST = `https://localhost:${PORT}/`;
- info("Using URLs: " + SLOW_HOST);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, BASE_PAGE);
- info("opened tab");
- yield ContentTask.spawn(tab.linkedBrowser, SLOW_HOST, URL => {
- let link = content.document.createElement("a");
- link.href = URL;
- link.textContent = "click me to open a slow page";
- link.id = "clickme"
- content.document.body.appendChild(link);
- });
- info("added link");
- let newTabPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- // Middle click the link:
- yield BrowserTestUtils.synthesizeMouseAtCenter("#clickme", { button: 1 }, tab.linkedBrowser);
- // get new tab, switch to it
- let newTab = (yield newTabPromise).target;
- yield BrowserTestUtils.switchTab(gBrowser, newTab);
- is(gURLBar.value, SLOW_HOST, "Should have slow page in URL bar");
- let browserStoppedPromise = BrowserTestUtils.browserStopped(newTab.linkedBrowser);
- BrowserStop();
- yield browserStoppedPromise;
-
- is(gURLBar.value, SLOW_HOST, "Should still have slow page in URL bar after stop");
- yield BrowserTestUtils.removeTab(newTab);
- yield BrowserTestUtils.removeTab(tab);
-});
-/**
- * Check that if we:
- * 1) middle-click a link to a separate page whose server doesn't respond
- * 2) we alter the URL on that page to some other server that doesn't respond
- * 3) we stop the request
- *
- * The URL bar continues to contain the second URL.
- */
-add_task(function*() {
- let socket = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);
- socket.init(-1, true, -1);
- const PORT1 = socket.port;
- let socket2 = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);
- socket2.init(-1, true, -1);
- const PORT2 = socket2.port;
- registerCleanupFunction(() => { socket.close(); socket2.close(); });
-
- const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "https://example.com");
- const BASE_PAGE = TEST_PATH + "dummy_page.html";
- const SLOW_HOST1 = `https://localhost:${PORT1}/`;
- const SLOW_HOST2 = `https://localhost:${PORT2}/`;
- info("Using URLs: " + SLOW_HOST1 + " and " + SLOW_HOST2);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, BASE_PAGE);
- info("opened tab");
- yield ContentTask.spawn(tab.linkedBrowser, SLOW_HOST1, URL => {
- let link = content.document.createElement("a");
- link.href = URL;
- link.textContent = "click me to open a slow page";
- link.id = "clickme"
- content.document.body.appendChild(link);
- });
- info("added link");
- let newTabPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- // Middle click the link:
- yield BrowserTestUtils.synthesizeMouseAtCenter("#clickme", { button: 1 }, tab.linkedBrowser);
- // get new tab, switch to it
- let newTab = (yield newTabPromise).target;
- yield BrowserTestUtils.switchTab(gBrowser, newTab);
- is(gURLBar.value, SLOW_HOST1, "Should have slow page in URL bar");
- let browserStoppedPromise = BrowserTestUtils.browserStopped(newTab.linkedBrowser);
- gURLBar.value = SLOW_HOST2;
- gURLBar.handleCommand();
- yield browserStoppedPromise;
-
- is(gURLBar.value, SLOW_HOST2, "Should have second slow page in URL bar");
- browserStoppedPromise = BrowserTestUtils.browserStopped(newTab.linkedBrowser);
- BrowserStop();
- yield browserStoppedPromise;
-
- is(gURLBar.value, SLOW_HOST2, "Should still have second slow page in URL bar after stop");
- yield BrowserTestUtils.removeTab(newTab);
- yield BrowserTestUtils.removeTab(tab);
-});
-
diff --git a/browser/base/content/test/urlbar/browser_wyciwyg_urlbarCopying.js b/browser/base/content/test/urlbar/browser_wyciwyg_urlbarCopying.js
deleted file mode 100644
index 54b174aa8..000000000
--- a/browser/base/content/test/urlbar/browser_wyciwyg_urlbarCopying.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function testURLBarCopy(targetValue) {
- return new Promise((resolve, reject) => {
- info("Expecting copy of: " + targetValue);
- waitForClipboard(targetValue, function () {
- gURLBar.focus();
- gURLBar.select();
-
- goDoCommand("cmd_copy");
- }, resolve, () => {
- ok(false, "Clipboard copy failed");
- reject();
- });
- });
-}
-
-add_task(function* () {
- const url = "http://mochi.test:8888/browser/browser/base/content/test/urlbar/test_wyciwyg_copying.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#btn", {}, tab.linkedBrowser);
- let currentURL = gBrowser.currentURI.spec;
- ok(/^wyciwyg:\/\//i.test(currentURL), currentURL + " is a wyciwyg URI");
-
- yield testURLBarCopy(url);
-
- while (gBrowser.tabs.length > 1)
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/base/content/test/urlbar/dummy_page.html b/browser/base/content/test/urlbar/dummy_page.html
deleted file mode 100644
index 1a87e2840..000000000
--- a/browser/base/content/test/urlbar/dummy_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Dummy test page</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Dummy test page</p>
-</body>
-</html>
diff --git a/browser/base/content/test/urlbar/file_blank_but_not_blank.html b/browser/base/content/test/urlbar/file_blank_but_not_blank.html
deleted file mode 100644
index 1f5fea8dc..000000000
--- a/browser/base/content/test/urlbar/file_blank_but_not_blank.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<script>var q = "1";</script>
-<a href="javascript:q">Click me</a>
diff --git a/browser/base/content/test/urlbar/file_urlbar_edit_dos.html b/browser/base/content/test/urlbar/file_urlbar_edit_dos.html
deleted file mode 100644
index 5a6e7d109..000000000
--- a/browser/base/content/test/urlbar/file_urlbar_edit_dos.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Try editing the URL bar</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<script>
-var dos_timeout = null;
-function dos_hash() {
- dos_timeout = setTimeout(function() {
- location.hash = "#";
- }, 50);
-}
-
-function dos_pushState() {
- dos_timeout = setTimeout(function() {
- history.pushState({}, "Some title", "");
- }, 50);
-}
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/urlbar/head.js b/browser/base/content/test/urlbar/head.js
deleted file mode 100644
index 427dba080..000000000
--- a/browser/base/content/test/urlbar/head.js
+++ /dev/null
@@ -1,205 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
- "resource://gre/modules/Preferences.jsm");
-
-/**
- * Waits for the next top-level document load in the current browser. The URI
- * of the document is compared against aExpectedURL. The load is then stopped
- * before it actually starts.
- *
- * @param aExpectedURL
- * The URL of the document that is expected to load.
- * @param aStopFromProgressListener
- * Whether to cancel the load directly from the progress listener. Defaults to true.
- * If you're using this method to avoid hitting the network, you want the default (true).
- * However, the browser UI will behave differently for loads stopped directly from
- * the progress listener (effectively in the middle of a call to loadURI) and so there
- * are cases where you may want to avoid stopping the load directly from within the
- * progress listener callback.
- * @return promise
- */
-function waitForDocLoadAndStopIt(aExpectedURL, aBrowser=gBrowser.selectedBrowser, aStopFromProgressListener=true) {
- function content_script(aStopFromProgressListener) {
- let { interfaces: Ci, utils: Cu } = Components;
- Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
- let wp = docShell.QueryInterface(Ci.nsIWebProgress);
-
- function stopContent(now, uri) {
- if (now) {
- /* Hammer time. */
- content.stop();
-
- /* Let the parent know we're done. */
- sendAsyncMessage("Test:WaitForDocLoadAndStopIt", { uri });
- } else {
- setTimeout(stopContent.bind(null, true, uri), 0);
- }
- }
-
- let progressListener = {
- onStateChange: function (webProgress, req, flags, status) {
- dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n");
-
- if (webProgress.isTopLevel &&
- flags & Ci.nsIWebProgressListener.STATE_START) {
- wp.removeProgressListener(progressListener);
-
- let chan = req.QueryInterface(Ci.nsIChannel);
- dump(`waitForDocLoadAndStopIt: Document start: ${chan.URI.spec}\n`);
-
- stopContent(aStopFromProgressListener, chan.originalURI.spec);
- }
- },
- QueryInterface: XPCOMUtils.generateQI(["nsISupportsWeakReference"])
- };
- wp.addProgressListener(progressListener, wp.NOTIFY_STATE_WINDOW);
-
- /**
- * As |this| is undefined and we can't extend |docShell|, adding an unload
- * event handler is the easiest way to ensure the weakly referenced
- * progress listener is kept alive as long as necessary.
- */
- addEventListener("unload", function () {
- try {
- wp.removeProgressListener(progressListener);
- } catch (e) { /* Will most likely fail. */ }
- });
- }
-
- return new Promise((resolve, reject) => {
- function complete({ data }) {
- is(data.uri, aExpectedURL, "waitForDocLoadAndStopIt: The expected URL was loaded");
- mm.removeMessageListener("Test:WaitForDocLoadAndStopIt", complete);
- resolve();
- }
-
- let mm = aBrowser.messageManager;
- mm.loadFrameScript("data:,(" + content_script.toString() + ")(" + aStopFromProgressListener + ");", true);
- mm.addMessageListener("Test:WaitForDocLoadAndStopIt", complete);
- info("waitForDocLoadAndStopIt: Waiting for URL: " + aExpectedURL);
- });
-}
-
-function is_hidden(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
- if (style.display == "-moz-popup")
- return ["hiding", "closed"].indexOf(element.state) != -1;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_hidden(element.parentNode);
-
- return false;
-}
-
-function is_visible(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return false;
- if (style.visibility != "visible")
- return false;
- if (style.display == "-moz-popup" && element.state != "open")
- return false;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_visible(element.parentNode);
-
- return true;
-}
-
-function is_element_visible(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_visible(element), msg || "Element should be visible");
-}
-
-function is_element_hidden(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_hidden(element), msg || "Element should be hidden");
-}
-
-function promisePopupEvent(popup, eventSuffix) {
- let endState = {shown: "open", hidden: "closed"}[eventSuffix];
-
- if (popup.state == endState)
- return Promise.resolve();
-
- let eventType = "popup" + eventSuffix;
- let deferred = Promise.defer();
- popup.addEventListener(eventType, function onPopupShown(event) {
- popup.removeEventListener(eventType, onPopupShown);
- deferred.resolve();
- });
-
- return deferred.promise;
-}
-
-function promisePopupShown(popup) {
- return promisePopupEvent(popup, "shown");
-}
-
-function promisePopupHidden(popup) {
- return promisePopupEvent(popup, "hidden");
-}
-
-function promiseSearchComplete(win = window) {
- return promisePopupShown(win.gURLBar.popup).then(() => {
- function searchIsComplete() {
- return win.gURLBar.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH;
- }
-
- // Wait until there are at least two matches.
- return BrowserTestUtils.waitForCondition(searchIsComplete, "waiting urlbar search to complete");
- });
-}
-
-function promiseAutocompleteResultPopup(inputText,
- win = window,
- fireInputEvent = false) {
- waitForFocus(() => {
- win.gURLBar.focus();
- win.gURLBar.value = inputText;
- if (fireInputEvent) {
- // This is necessary to get the urlbar to set gBrowser.userTypedValue.
- let event = document.createEvent("Events");
- event.initEvent("input", true, true);
- win.gURLBar.dispatchEvent(event);
- }
- win.gURLBar.controller.startSearch(inputText);
- }, win);
-
- return promiseSearchComplete(win);
-}
-
-function promiseNewSearchEngine(basename) {
- return new Promise((resolve, reject) => {
- info("Waiting for engine to be added: " + basename);
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- registerCleanupFunction(() => Services.search.removeEngine(engine));
- resolve(engine);
- },
- onError: function (errCode) {
- Assert.ok(false, "addEngine failed with error code " + errCode);
- reject();
- },
- });
- });
-}
-
diff --git a/browser/base/content/test/urlbar/moz.png b/browser/base/content/test/urlbar/moz.png
deleted file mode 100644
index 769c63634..000000000
--- a/browser/base/content/test/urlbar/moz.png
+++ /dev/null
Binary files differ
diff --git a/browser/base/content/test/urlbar/print_postdata.sjs b/browser/base/content/test/urlbar/print_postdata.sjs
deleted file mode 100644
index 4175a2480..000000000
--- a/browser/base/content/test/urlbar/print_postdata.sjs
+++ /dev/null
@@ -1,22 +0,0 @@
-const CC = Components.Constructor;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(request, response) {
- response.setHeader("Content-Type", "text/plain", false);
- if (request.method == "GET") {
- response.write(request.queryString);
- } else {
- var body = new BinaryInputStream(request.bodyInputStream);
-
- var avail;
- var bytes = [];
-
- while ((avail = body.available()) > 0)
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
-
- var data = String.fromCharCode.apply(null, bytes);
- response.bodyOutputStream.write(data, data.length);
- }
-}
diff --git a/browser/base/content/test/urlbar/redirect_bug623155.sjs b/browser/base/content/test/urlbar/redirect_bug623155.sjs
deleted file mode 100644
index 64c6f143b..000000000
--- a/browser/base/content/test/urlbar/redirect_bug623155.sjs
+++ /dev/null
@@ -1,16 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const REDIRECT_TO = "https://www.bank1.com/"; // Bad-cert host.
-
-function handleRequest(aRequest, aResponse) {
- // Set HTTP Status
- aResponse.setStatusLine(aRequest.httpVersion, 301, "Moved Permanently");
-
- // Set redirect URI, mirroring the hash value.
- let hash = (/\#.+/.test(aRequest.path))?
- "#" + aRequest.path.split("#")[1]:
- "";
- aResponse.setHeader("Location", REDIRECT_TO + hash);
-}
diff --git a/browser/base/content/test/urlbar/searchSuggestionEngine.sjs b/browser/base/content/test/urlbar/searchSuggestionEngine.sjs
deleted file mode 100644
index 1978b4f66..000000000
--- a/browser/base/content/test/urlbar/searchSuggestionEngine.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(req, resp) {
- let suffixes = ["foo", "bar"];
- let data = [req.queryString, suffixes.map(s => req.queryString + s)];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
-}
diff --git a/browser/base/content/test/urlbar/searchSuggestionEngine.xml b/browser/base/content/test/urlbar/searchSuggestionEngine.xml
deleted file mode 100644
index a5659792e..000000000
--- a/browser/base/content/test/urlbar/searchSuggestionEngine.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_searchSuggestionEngine searchSuggestionEngine.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/base/content/test/urlbar/searchSuggestionEngine.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://mochi.test:8888/" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/base/content/test/urlbar/slow-page.sjs b/browser/base/content/test/urlbar/slow-page.sjs
deleted file mode 100644
index f428d66e4..000000000
--- a/browser/base/content/test/urlbar/slow-page.sjs
+++ /dev/null
@@ -1,22 +0,0 @@
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-let timer;
-
-const DELAY_MS = 5000;
-function handleRequest(request, response) {
- if (request.queryString.endsWith("faster")) {
- response.setHeader("Content-Type", "text/html", false);
- response.write("<body>Not so slow!</body>");
- return;
- }
- response.processAsync();
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.init(() => {
- response.setHeader("Content-Type", "text/html", false);
- response.write("<body>This was the slow load. You should never see this.</body>");
- response.finish();
- }, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
-}
diff --git a/browser/base/content/test/urlbar/test_wyciwyg_copying.html b/browser/base/content/test/urlbar/test_wyciwyg_copying.html
deleted file mode 100644
index 3a8c3a150..000000000
--- a/browser/base/content/test/urlbar/test_wyciwyg_copying.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<html>
-<body>
-<script>
- function go() {
- var w = window.open();
- w.document.open();
- w.document.write("<html><body>test document</body></html>");
- w.document.close();
- }
-</script>
-<button id="btn" onclick="go();">test</button>
-</body>
-</html>
diff --git a/browser/base/content/test/webrtc/.eslintrc.js b/browser/base/content/test/webrtc/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/base/content/test/webrtc/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/base/content/test/webrtc/browser.ini b/browser/base/content/test/webrtc/browser.ini
deleted file mode 100644
index 8830989ad..000000000
--- a/browser/base/content/test/webrtc/browser.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-support-files =
- get_user_media.html
- get_user_media_content_script.js
- head.js
-
-[browser_devices_get_user_media.js]
-skip-if = (os == "linux" && debug) # linux: bug 976544
-[browser_devices_get_user_media_anim.js]
-[browser_devices_get_user_media_in_frame.js]
-[browser_devices_get_user_media_tear_off_tab.js]
diff --git a/browser/base/content/test/webrtc/browser_devices_get_user_media.js b/browser/base/content/test/webrtc/browser_devices_get_user_media.js
deleted file mode 100644
index 3681a810b..000000000
--- a/browser/base/content/test/webrtc/browser_devices_get_user_media.js
+++ /dev/null
@@ -1,554 +0,0 @@
-/* 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/. */
-
-requestLongerTimeout(2);
-
-registerCleanupFunction(function() {
- gBrowser.removeCurrentTab();
-});
-
-const permissionError = "error: NotAllowedError: The request is not allowed " +
- "by the user agent or the platform in the current context.";
-
-var gTests = [
-
-{
- desc: "getUserMedia audio+video",
- run: function* checkAudioVideo() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- is(PopupNotifications.getNotification("webRTC-shareDevices").anchorID,
- "webRTC-shareDevices-notification-icon", "anchored to device icon");
- checkDeviceSelectors(true, true);
- let iconclass =
- PopupNotifications.panel.firstChild.getAttribute("iconclass");
- ok(iconclass.includes("camera-icon"), "panel using devices icon");
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({audio: true, video: true});
- yield closeStream();
- }
-},
-
-{
- desc: "getUserMedia audio only",
- run: function* checkAudioOnly() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- is(PopupNotifications.getNotification("webRTC-shareDevices").anchorID,
- "webRTC-shareMicrophone-notification-icon", "anchored to mic icon");
- checkDeviceSelectors(true);
- let iconclass =
- PopupNotifications.panel.firstChild.getAttribute("iconclass");
- ok(iconclass.includes("microphone-icon"), "panel using microphone icon");
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "Microphone",
- "expected microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({audio: true});
- yield closeStream();
- }
-},
-
-{
- desc: "getUserMedia video only",
- run: function* checkVideoOnly() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(false, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- is(PopupNotifications.getNotification("webRTC-shareDevices").anchorID,
- "webRTC-shareDevices-notification-icon", "anchored to device icon");
- checkDeviceSelectors(false, true);
- let iconclass =
- PopupNotifications.panel.firstChild.getAttribute("iconclass");
- ok(iconclass.includes("camera-icon"), "panel using devices icon");
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "Camera", "expected camera to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true});
- yield closeStream();
- }
-},
-
-{
- desc: "getUserMedia audio+video, user clicks \"Don't Share\"",
- run: function* checkDontShare() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- yield promiseMessage(permissionError, () => {
- activateSecondaryAction(kActionDeny);
- });
-
- yield expectObserverCalled("getUserMedia:response:deny");
- yield expectObserverCalled("recording-window-ended");
- yield checkNotSharing();
- }
-},
-
-{
- desc: "getUserMedia audio+video: stop sharing",
- run: function* checkStopSharing() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- yield stopSharing();
-
- // the stream is already closed, but this will do some cleanup anyway
- yield closeStream(true);
- }
-},
-
-{
- desc: "getUserMedia audio+video: reloading the page removes all gUM UI",
- run: function* checkReloading() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- info("reloading the web page");
- promise = promiseObserverCalled("recording-device-events");
- content.location.reload();
- yield promise;
-
- yield expectObserverCalled("recording-window-ended");
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-},
-
-{
- desc: "getUserMedia prompt: Always/Never Share",
- run: function* checkRememberCheckbox() {
- let elt = id => document.getElementById(id);
-
- function* checkPerm(aRequestAudio, aRequestVideo,
- aExpectedAudioPerm, aExpectedVideoPerm, aNever) {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(aRequestAudio, aRequestVideo);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- is(elt("webRTC-selectMicrophone").hidden, !aRequestAudio,
- "microphone selector expected to be " + (aRequestAudio ? "visible" : "hidden"));
-
- is(elt("webRTC-selectCamera").hidden, !aRequestVideo,
- "camera selector expected to be " + (aRequestVideo ? "visible" : "hidden"));
-
- let expectedMessage = aNever ? permissionError : "ok";
- yield promiseMessage(expectedMessage, () => {
- activateSecondaryAction(aNever ? kActionNever : kActionAlways);
- });
- let expected = [];
- if (expectedMessage == "ok") {
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- if (aRequestVideo)
- expected.push("Camera");
- if (aRequestAudio)
- expected.push("Microphone");
- expected = expected.join("And");
- }
- else {
- yield expectObserverCalled("getUserMedia:response:deny");
- yield expectObserverCalled("recording-window-ended");
- expected = "none";
- }
- is((yield getMediaCaptureState()), expected,
- "expected " + expected + " to be shared");
-
- function checkDevicePermissions(aDevice, aExpected) {
- let Perms = Services.perms;
- let uri = gBrowser.selectedBrowser.documentURI;
- let devicePerms = Perms.testExactPermission(uri, aDevice);
- if (aExpected === undefined)
- is(devicePerms, Perms.UNKNOWN_ACTION, "no " + aDevice + " persistent permissions");
- else {
- is(devicePerms, aExpected ? Perms.ALLOW_ACTION : Perms.DENY_ACTION,
- aDevice + " persistently " + (aExpected ? "allowed" : "denied"));
- }
- Perms.remove(uri, aDevice);
- }
- checkDevicePermissions("microphone", aExpectedAudioPerm);
- checkDevicePermissions("camera", aExpectedVideoPerm);
-
- if (expectedMessage == "ok")
- yield closeStream();
- }
-
- // 3 cases where the user accepts the device prompt.
- info("audio+video, user grants, expect both perms set to allow");
- yield checkPerm(true, true, true, true);
- info("audio only, user grants, check audio perm set to allow, video perm not set");
- yield checkPerm(true, false, true, undefined);
- info("video only, user grants, check video perm set to allow, audio perm not set");
- yield checkPerm(false, true, undefined, true);
-
- // 3 cases where the user rejects the device request by using 'Never Share'.
- info("audio only, user denies, expect audio perm set to deny, video not set");
- yield checkPerm(true, false, false, undefined, true);
- info("video only, user denies, expect video perm set to deny, audio perm not set");
- yield checkPerm(false, true, undefined, false, true);
- info("audio+video, user denies, expect both perms set to deny");
- yield checkPerm(true, true, false, false, true);
- }
-},
-
-{
- desc: "getUserMedia without prompt: use persistent permissions",
- run: function* checkUsePersistentPermissions() {
- function* usePerm(aAllowAudio, aAllowVideo, aRequestAudio, aRequestVideo,
- aExpectStream) {
- let Perms = Services.perms;
- let uri = gBrowser.selectedBrowser.documentURI;
-
- if (aAllowAudio !== undefined) {
- Perms.add(uri, "microphone", aAllowAudio ? Perms.ALLOW_ACTION
- : Perms.DENY_ACTION);
- }
- if (aAllowVideo !== undefined) {
- Perms.add(uri, "camera", aAllowVideo ? Perms.ALLOW_ACTION
- : Perms.DENY_ACTION);
- }
-
- if (aExpectStream === undefined) {
- // Check that we get a prompt.
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(aRequestAudio, aRequestVideo);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- // Deny the request to cleanup...
- yield promiseMessage(permissionError, () => {
- activateSecondaryAction(kActionDeny);
- });
- yield expectObserverCalled("getUserMedia:response:deny");
- yield expectObserverCalled("recording-window-ended");
- }
- else {
- let expectedMessage = aExpectStream ? "ok" : permissionError;
- let promise = promiseMessage(expectedMessage);
- yield promiseRequestDevice(aRequestAudio, aRequestVideo);
- yield promise;
-
- if (expectedMessage == "ok") {
- yield expectObserverCalled("getUserMedia:request");
- yield promiseNoPopupNotification("webRTC-shareDevices");
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
-
- // Check what's actually shared.
- let expected = [];
- if (aAllowVideo && aRequestVideo)
- expected.push("Camera");
- if (aAllowAudio && aRequestAudio)
- expected.push("Microphone");
- expected = expected.join("And");
- is((yield getMediaCaptureState()), expected,
- "expected " + expected + " to be shared");
-
- yield closeStream();
- }
- else {
- yield expectObserverCalled("recording-window-ended");
- }
- }
-
- Perms.remove(uri, "camera");
- Perms.remove(uri, "microphone");
- }
-
- // Set both permissions identically
- info("allow audio+video, request audio+video, expect ok (audio+video)");
- yield usePerm(true, true, true, true, true);
- info("deny audio+video, request audio+video, expect denied");
- yield usePerm(false, false, true, true, false);
-
- // Allow audio, deny video.
- info("allow audio, deny video, request audio+video, expect denied");
- yield usePerm(true, false, true, true, false);
- info("allow audio, deny video, request audio, expect ok (audio)");
- yield usePerm(true, false, true, false, true);
- info("allow audio, deny video, request video, expect denied");
- yield usePerm(true, false, false, true, false);
-
- // Deny audio, allow video.
- info("deny audio, allow video, request audio+video, expect denied");
- yield usePerm(false, true, true, true, false);
- info("deny audio, allow video, request audio, expect denied");
- yield usePerm(false, true, true, false, false);
- info("deny audio, allow video, request video, expect ok (video)");
- yield usePerm(false, true, false, true, true);
-
- // Allow audio, video not set.
- info("allow audio, request audio+video, expect prompt");
- yield usePerm(true, undefined, true, true, undefined);
- info("allow audio, request audio, expect ok (audio)");
- yield usePerm(true, undefined, true, false, true);
- info("allow audio, request video, expect prompt");
- yield usePerm(true, undefined, false, true, undefined);
-
- // Deny audio, video not set.
- info("deny audio, request audio+video, expect denied");
- yield usePerm(false, undefined, true, true, false);
- info("deny audio, request audio, expect denied");
- yield usePerm(false, undefined, true, false, false);
- info("deny audio, request video, expect prompt");
- yield usePerm(false, undefined, false, true, undefined);
-
- // Allow video, audio not set.
- info("allow video, request audio+video, expect prompt");
- yield usePerm(undefined, true, true, true, undefined);
- info("allow video, request audio, expect prompt");
- yield usePerm(undefined, true, true, false, undefined);
- info("allow video, request video, expect ok (video)");
- yield usePerm(undefined, true, false, true, true);
-
- // Deny video, audio not set.
- info("deny video, request audio+video, expect denied");
- yield usePerm(undefined, false, true, true, false);
- info("deny video, request audio, expect prompt");
- yield usePerm(undefined, false, true, false, undefined);
- info("deny video, request video, expect denied");
- yield usePerm(undefined, false, false, true, false);
- }
-},
-
-{
- desc: "Stop Sharing removes persistent permissions",
- run: function* checkStopSharingRemovesPersistentPermissions() {
- function* stopAndCheckPerm(aRequestAudio, aRequestVideo) {
- let Perms = Services.perms;
- let uri = gBrowser.selectedBrowser.documentURI;
-
- // Initially set both permissions to 'allow'.
- Perms.add(uri, "microphone", Perms.ALLOW_ACTION);
- Perms.add(uri, "camera", Perms.ALLOW_ACTION);
-
- let indicator = promiseIndicatorWindow();
- // Start sharing what's been requested.
- let promise = promiseMessage("ok");
- yield promiseRequestDevice(aRequestAudio, aRequestVideo);
- yield promise;
-
- yield expectObserverCalled("getUserMedia:request");
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- yield indicator;
- yield checkSharingUI({video: aRequestVideo, audio: aRequestAudio});
-
- yield stopSharing(aRequestVideo ? "camera" : "microphone");
-
- // Check that permissions have been removed as expected.
- let audioPerm = Perms.testExactPermission(uri, "microphone");
- if (aRequestAudio)
- is(audioPerm, Perms.UNKNOWN_ACTION, "microphone permissions removed");
- else
- is(audioPerm, Perms.ALLOW_ACTION, "microphone permissions untouched");
-
- let videoPerm = Perms.testExactPermission(uri, "camera");
- if (aRequestVideo)
- is(videoPerm, Perms.UNKNOWN_ACTION, "camera permissions removed");
- else
- is(videoPerm, Perms.ALLOW_ACTION, "camera permissions untouched");
-
- // Cleanup.
- yield closeStream(true);
-
- Perms.remove(uri, "camera");
- Perms.remove(uri, "microphone");
- }
-
- info("request audio+video, stop sharing resets both");
- yield stopAndCheckPerm(true, true);
- info("request audio, stop sharing resets audio only");
- yield stopAndCheckPerm(true, false);
- info("request video, stop sharing resets video only");
- yield stopAndCheckPerm(false, true);
- }
-},
-
-{
- desc: "test showControlCenter",
- run: function* checkShowControlCenter() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(false, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(false, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "Camera", "expected camera to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true});
-
- ok(gIdentityHandler._identityPopup.hidden, "control center should be hidden");
- if ("nsISystemStatusBar" in Ci) {
- let activeStreams = webrtcUI.getActiveStreams(true, false, false);
- webrtcUI.showSharingDoorhanger(activeStreams[0], "Devices");
- }
- else {
- let win =
- Services.wm.getMostRecentWindow("Browser:WebRTCGlobalIndicator");
- let elt = win.document.getElementById("audioVideoButton");
- EventUtils.synthesizeMouseAtCenter(elt, {}, win);
- yield promiseWaitForCondition(() => !gIdentityHandler._identityPopup.hidden);
- }
- ok(!gIdentityHandler._identityPopup.hidden, "control center should be open");
-
- gIdentityHandler._identityPopup.hidden = true;
- yield expectNoObserverCalled();
-
- yield closeStream();
- }
-},
-
-{
- desc: "'Always Allow' ignored and not shown on http pages",
- run: function* checkNoAlwaysOnHttp() {
- // Load an http page instead of the https version.
- let browser = gBrowser.selectedBrowser;
- browser.loadURI(browser.documentURI.spec.replace("https://", "http://"));
- yield BrowserTestUtils.browserLoaded(browser);
-
- // Initially set both permissions to 'allow'.
- let Perms = Services.perms;
- let uri = browser.documentURI;
- Perms.add(uri, "microphone", Perms.ALLOW_ACTION);
- Perms.add(uri, "camera", Perms.ALLOW_ACTION);
-
- // Request devices and expect a prompt despite the saved 'Allow' permission,
- // because the connection isn't secure.
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- // Ensure that the 'Always Allow' action isn't shown.
- let alwaysLabel = gNavigatorBundle.getString("getUserMedia.always.label");
- ok(!!alwaysLabel, "found the 'Always Allow' localized label");
- let labels = [];
- let notification = PopupNotifications.panel.firstChild;
- for (let node of notification.childNodes) {
- if (node.localName == "menuitem")
- labels.push(node.getAttribute("label"));
- }
- is(labels.indexOf(alwaysLabel), -1, "The 'Always Allow' item isn't shown");
-
- // Cleanup.
- yield closeStream(true);
- Perms.remove(uri, "camera");
- Perms.remove(uri, "microphone");
- }
-}
-
-];
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- browser.messageManager.loadFrameScript(CONTENT_SCRIPT_HELPER, true);
-
- browser.addEventListener("load", function onload() {
- browser.removeEventListener("load", onload, true);
-
- is(PopupNotifications._currentNotifications.length, 0,
- "should start the test without any prior popup notification");
- ok(gIdentityHandler._identityPopup.hidden,
- "should start the test with the control center hidden");
-
- Task.spawn(function* () {
- yield SpecialPowers.pushPrefEnv({"set": [[PREF_PERMISSION_FAKE, true]]});
-
- for (let test of gTests) {
- info(test.desc);
- yield test.run();
-
- // Cleanup before the next test
- yield expectNoObserverCalled();
- }
- }).then(finish, ex => {
- Cu.reportError(ex);
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
- }, true);
- let rootDir = getRootDirectory(gTestPath);
- rootDir = rootDir.replace("chrome://mochitests/content/",
- "https://example.com/");
- content.location = rootDir + "get_user_media.html";
-}
diff --git a/browser/base/content/test/webrtc/browser_devices_get_user_media_anim.js b/browser/base/content/test/webrtc/browser_devices_get_user_media_anim.js
deleted file mode 100644
index f407061a7..000000000
--- a/browser/base/content/test/webrtc/browser_devices_get_user_media_anim.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-registerCleanupFunction(function() {
- gBrowser.removeCurrentTab();
-});
-
-var gTests = [
-
-{
- desc: "device sharing animation on background tabs",
- run: function* checkAudioVideo() {
- function* getStreamAndCheckBackgroundAnim(aAudio, aVideo, aSharing) {
- // Get a stream
- let popupPromise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(aAudio, aVideo);
- yield popupPromise;
- yield expectObserverCalled("getUserMedia:request");
-
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- let expected = [];
- if (aVideo)
- expected.push("Camera");
- if (aAudio)
- expected.push("Microphone");
- is((yield getMediaCaptureState()), expected.join("And"),
- "expected stream to be shared");
-
- // Check the attribute on the tab, and check there's no visible
- // sharing icon on the tab
- let tab = gBrowser.selectedTab;
- is(tab.getAttribute("sharing"), aSharing,
- "the tab has the attribute to show the " + aSharing + " icon");
- let icon =
- document.getAnonymousElementByAttribute(tab, "anonid", "sharing-icon");
- is(window.getComputedStyle(icon).display, "none",
- "the animated sharing icon of the tab is hidden");
-
- // After selecting a new tab, check the attribute is still there,
- // and the icon is now visible.
- yield BrowserTestUtils.switchTab(gBrowser, gBrowser.addTab());
- is(gBrowser.selectedTab.getAttribute("sharing"), "",
- "the new tab doesn't have the 'sharing' attribute");
- is(tab.getAttribute("sharing"), aSharing,
- "the tab still has the 'sharing' attribute");
- isnot(window.getComputedStyle(icon).display, "none",
- "the animated sharing icon of the tab is now visible");
-
- // Ensure the icon disappears when selecting the tab.
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- ok(tab.selected, "the tab with ongoing sharing is selected again");
- is(window.getComputedStyle(icon).display, "none",
- "the animated sharing icon is gone after selecting the tab again");
-
- // And finally verify the attribute is removed when closing the stream.
- yield closeStream();
-
- // TODO(Bug 1304997): Fix the race in closeStream() and remove this
- // promiseWaitForCondition().
- yield promiseWaitForCondition(() => !tab.getAttribute("sharing"));
- is(tab.getAttribute("sharing"), "",
- "the tab no longer has the 'sharing' attribute after closing the stream");
- }
-
- yield getStreamAndCheckBackgroundAnim(true, true, "camera");
- yield getStreamAndCheckBackgroundAnim(false, true, "camera");
- yield getStreamAndCheckBackgroundAnim(true, false, "microphone");
- }
-}
-
-];
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- browser.messageManager.loadFrameScript(CONTENT_SCRIPT_HELPER, true);
-
- browser.addEventListener("load", function onload() {
- browser.removeEventListener("load", onload, true);
-
- is(PopupNotifications._currentNotifications.length, 0,
- "should start the test without any prior popup notification");
-
- Task.spawn(function* () {
- yield SpecialPowers.pushPrefEnv({"set": [[PREF_PERMISSION_FAKE, true]]});
-
- for (let test of gTests) {
- info(test.desc);
- yield test.run();
- }
- }).then(finish, ex => {
- Cu.reportError(ex);
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
- }, true);
- let rootDir = getRootDirectory(gTestPath);
- rootDir = rootDir.replace("chrome://mochitests/content/",
- "https://example.com/");
- content.location = rootDir + "get_user_media.html";
-}
diff --git a/browser/base/content/test/webrtc/browser_devices_get_user_media_in_frame.js b/browser/base/content/test/webrtc/browser_devices_get_user_media_in_frame.js
deleted file mode 100644
index 01a544aae..000000000
--- a/browser/base/content/test/webrtc/browser_devices_get_user_media_in_frame.js
+++ /dev/null
@@ -1,266 +0,0 @@
-/* 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/. */
-
-registerCleanupFunction(function() {
- gBrowser.removeCurrentTab();
-});
-
-function promiseReloadFrame(aFrameId) {
- return ContentTask.spawn(gBrowser.selectedBrowser, aFrameId, function*(aFrameId) {
- content.wrappedJSObject.document.getElementById(aFrameId).contentWindow.location.reload();
- });
-}
-
-var gTests = [
-
-{
- desc: "getUserMedia audio+video",
- run: function* checkAudioVideo() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
-
- is(PopupNotifications.getNotification("webRTC-shareDevices").anchorID,
- "webRTC-shareDevices-notification-icon", "anchored to device icon");
- checkDeviceSelectors(true, true);
- is(PopupNotifications.panel.firstChild.getAttribute("popupid"),
- "webRTC-shareDevices", "panel using devices icon");
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({audio: true, video: true});
- yield closeStream(false, "frame1");
- }
-},
-
-{
- desc: "getUserMedia audio+video: stop sharing",
- run: function* checkStopSharing() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- activateSecondaryAction(kActionAlways);
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- let Perms = Services.perms;
- let uri = Services.io.newURI("https://example.com/", null, null);
- is(Perms.testExactPermission(uri, "microphone"), Perms.ALLOW_ACTION,
- "microphone persistently allowed");
- is(Perms.testExactPermission(uri, "camera"), Perms.ALLOW_ACTION,
- "camera persistently allowed");
-
- yield stopSharing();
-
- // The persistent permissions for the frame should have been removed.
- is(Perms.testExactPermission(uri, "microphone"), Perms.UNKNOWN_ACTION,
- "microphone not persistently allowed");
- is(Perms.testExactPermission(uri, "camera"), Perms.UNKNOWN_ACTION,
- "camera not persistently allowed");
-
- // the stream is already closed, but this will do some cleanup anyway
- yield closeStream(true, "frame1");
- }
-},
-
-{
- desc: "getUserMedia audio+video: reloading the frame removes all sharing UI",
- run: function* checkReloading() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- info("reloading the frame");
- promise = promiseObserverCalled("recording-device-events");
- yield promiseReloadFrame("frame1");
- yield promise;
-
- yield expectObserverCalled("recording-window-ended");
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-},
-
-{
- desc: "getUserMedia audio+video: reloading the frame removes prompts",
- run: function* checkReloadingRemovesPrompts() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- info("reloading the frame");
- promise = promiseObserverCalled("recording-window-ended");
- yield promiseReloadFrame("frame1");
- yield promise;
- yield promiseNoPopupNotification("webRTC-shareDevices");
-
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-},
-
-{
- desc: "getUserMedia audio+video: reloading a frame updates the sharing UI",
- run: function* checkUpdateWhenReloading() {
- // We'll share only the mic in the first frame, then share both in the
- // second frame, then reload the second frame. After each step, we'll check
- // the UI is in the correct state.
-
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, false, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, false);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "Microphone", "microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: false, audio: true});
- yield expectNoObserverCalled();
-
- promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame2");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield checkSharingUI({video: true, audio: true});
- yield expectNoObserverCalled();
-
- info("reloading the second frame");
- promise = promiseObserverCalled("recording-device-events");
- yield promiseReloadFrame("frame2");
- yield promise;
-
- yield expectObserverCalled("recording-window-ended");
- yield checkSharingUI({video: false, audio: true});
- yield expectNoObserverCalled();
-
- yield closeStream(false, "frame1");
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-},
-
-{
- desc: "getUserMedia audio+video: reloading the top level page removes all sharing UI",
- run: function* checkReloading() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true, "frame1");
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- info("reloading the web page");
- promise = promiseObserverCalled("recording-device-events");
- content.location.reload();
- yield promise;
-
- yield expectObserverCalled("recording-window-ended");
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-}
-
-];
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- browser.messageManager.loadFrameScript(CONTENT_SCRIPT_HELPER, true);
-
- browser.addEventListener("load", function onload() {
- browser.removeEventListener("load", onload, true);
-
- is(PopupNotifications._currentNotifications.length, 0,
- "should start the test without any prior popup notification");
-
- Task.spawn(function* () {
- yield SpecialPowers.pushPrefEnv({"set": [[PREF_PERMISSION_FAKE, true]]});
-
- for (let test of gTests) {
- info(test.desc);
- yield test.run();
-
- // Cleanup before the next test
- yield expectNoObserverCalled();
- }
- }).then(finish, ex => {
- Cu.reportError(ex);
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
- }, true);
- let rootDir = getRootDirectory(gTestPath);
- rootDir = rootDir.replace("chrome://mochitests/content/",
- "https://example.com/");
- let url = rootDir + "get_user_media.html";
- content.location = 'data:text/html,<iframe id="frame1" src="' + url + '"></iframe><iframe id="frame2" src="' + url + '"></iframe>'
-}
diff --git a/browser/base/content/test/webrtc/browser_devices_get_user_media_tear_off_tab.js b/browser/base/content/test/webrtc/browser_devices_get_user_media_tear_off_tab.js
deleted file mode 100644
index b19065371..000000000
--- a/browser/base/content/test/webrtc/browser_devices_get_user_media_tear_off_tab.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/* 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/. */
-
-registerCleanupFunction(function() {
- gBrowser.removeCurrentTab();
-});
-
-var gTests = [
-
-{
- desc: "getUserMedia: tearing-off a tab keeps sharing indicators",
- run: function* checkTearingOff() {
- let promise = promisePopupNotificationShown("webRTC-shareDevices");
- yield promiseRequestDevice(true, true);
- yield promise;
- yield expectObserverCalled("getUserMedia:request");
- checkDeviceSelectors(true, true);
-
- let indicator = promiseIndicatorWindow();
- yield promiseMessage("ok", () => {
- PopupNotifications.panel.firstChild.button.click();
- });
- yield expectObserverCalled("getUserMedia:response:allow");
- yield expectObserverCalled("recording-device-events");
- is((yield getMediaCaptureState()), "CameraAndMicrophone",
- "expected camera and microphone to be shared");
-
- yield indicator;
- yield checkSharingUI({video: true, audio: true});
-
- info("tearing off the tab");
- let win = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
- yield whenDelayedStartupFinished(win);
- yield checkSharingUI({audio: true, video: true}, win);
-
- // Clicking the global sharing indicator should open the control center in
- // the second window.
- ok(win.gIdentityHandler._identityPopup.hidden, "control center should be hidden");
- let activeStreams = webrtcUI.getActiveStreams(true, false, false);
- webrtcUI.showSharingDoorhanger(activeStreams[0], "Devices");
- ok(!win.gIdentityHandler._identityPopup.hidden,
- "control center should be open in the second window");
- ok(gIdentityHandler._identityPopup.hidden,
- "control center should be hidden in the first window");
- win.gIdentityHandler._identityPopup.hidden = true;
-
- // Closing the new window should remove all sharing indicators.
- // We need to load the content script in the first window so that we can
- // catch the notifications fired globally when closing the second window.
- gBrowser.selectedBrowser.messageManager.loadFrameScript(CONTENT_SCRIPT_HELPER, true);
-
- let promises = [promiseObserverCalled("recording-device-events"),
- promiseObserverCalled("recording-window-ended")];
- yield BrowserTestUtils.closeWindow(win);
- yield Promise.all(promises);
-
- yield expectNoObserverCalled();
- yield checkNotSharing();
- }
-}
-
-];
-
-function test() {
- waitForExplicitFinish();
- SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", 1]]}, runTest);
-}
-
-function runTest() {
- // An empty tab where we can load the content script without leaving it
- // behind at the end of the test.
- gBrowser.addTab();
-
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- browser.messageManager.loadFrameScript(CONTENT_SCRIPT_HELPER, true);
-
- browser.addEventListener("load", function onload() {
- browser.removeEventListener("load", onload, true);
-
- is(PopupNotifications._currentNotifications.length, 0,
- "should start the test without any prior popup notification");
- ok(gIdentityHandler._identityPopup.hidden,
- "should start the test with the control center hidden");
-
- Task.spawn(function* () {
- yield SpecialPowers.pushPrefEnv({"set": [[PREF_PERMISSION_FAKE, true]]});
-
- for (let test of gTests) {
- info(test.desc);
- yield test.run();
-
- // Cleanup before the next test
- yield expectNoObserverCalled();
- }
- }).then(finish, ex => {
- Cu.reportError(ex);
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
- }, true);
- let rootDir = getRootDirectory(gTestPath);
- rootDir = rootDir.replace("chrome://mochitests/content/",
- "https://example.com/");
- content.location = rootDir + "get_user_media.html";
-}
diff --git a/browser/base/content/test/webrtc/get_user_media.html b/browser/base/content/test/webrtc/get_user_media.html
deleted file mode 100644
index 16303c62d..000000000
--- a/browser/base/content/test/webrtc/get_user_media.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="UTF-8"></head>
-<body>
-<div id="message"></div>
-<script>
-// Specifies whether we are using fake streams to run this automation
-var useFakeStreams = true;
-try {
- var audioDevice = SpecialPowers.getCharPref("media.audio_loopback_dev");
- var videoDevice = SpecialPowers.getCharPref("media.video_loopback_dev");
- dump("TEST DEVICES: Using media devices:\n");
- dump("audio: " + audioDevice + "\nvideo: " + videoDevice + "\n");
- useFakeStreams = false;
-} catch (e) {
- dump("TEST DEVICES: No test devices found (in media.{audio,video}_loopback_dev, using fake streams.\n");
- useFakeStreams = true;
-}
-
-function message(m) {
- document.getElementById("message").innerHTML = m;
- window.parent.postMessage(m, "*");
-}
-
-var gStream;
-
-function requestDevice(aAudio, aVideo, aShare) {
- var opts = {video: aVideo, audio: aAudio};
- if (aShare) {
- opts.video = {
- mozMediaSource: aShare,
- mediaSource: aShare
- }
- } else if (useFakeStreams) {
- opts.fake = true;
- }
-
- window.navigator.mediaDevices.getUserMedia(opts)
- .then(stream => {
- gStream = stream;
- message("ok");
- }, err => message("error: " + err));
-}
-message("pending");
-
-function closeStream() {
- if (!gStream)
- return;
- gStream.getTracks().forEach(t => t.stop());
- gStream = null;
- message("closed");
-}
-</script>
-</body>
-</html>
diff --git a/browser/base/content/test/webrtc/get_user_media_content_script.js b/browser/base/content/test/webrtc/get_user_media_content_script.js
deleted file mode 100644
index 71b68d826..000000000
--- a/browser/base/content/test/webrtc/get_user_media_content_script.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyServiceGetter(this, "MediaManagerService",
- "@mozilla.org/mediaManagerService;1",
- "nsIMediaManagerService");
-
-const kObservedTopics = [
- "getUserMedia:response:allow",
- "getUserMedia:revoke",
- "getUserMedia:response:deny",
- "getUserMedia:request",
- "recording-device-events",
- "recording-window-ended"
-];
-
-var gObservedTopics = {};
-function observer(aSubject, aTopic, aData) {
- if (!(aTopic in gObservedTopics))
- gObservedTopics[aTopic] = 1;
- else
- ++gObservedTopics[aTopic];
-}
-
-kObservedTopics.forEach(topic => {
- Services.obs.addObserver(observer, topic, false);
-});
-
-addMessageListener("Test:ExpectObserverCalled", ({data}) => {
- sendAsyncMessage("Test:ExpectObserverCalled:Reply",
- {count: gObservedTopics[data]});
- if (data in gObservedTopics)
- --gObservedTopics[data];
-});
-
-addMessageListener("Test:ExpectNoObserverCalled", data => {
- sendAsyncMessage("Test:ExpectNoObserverCalled:Reply", gObservedTopics);
- gObservedTopics = {};
-});
-
-function _getMediaCaptureState() {
- let hasVideo = {};
- let hasAudio = {};
- let hasScreenShare = {};
- let hasWindowShare = {};
- MediaManagerService.mediaCaptureWindowState(content, hasVideo, hasAudio,
- hasScreenShare, hasWindowShare);
- if (hasVideo.value && hasAudio.value)
- return "CameraAndMicrophone";
- if (hasVideo.value)
- return "Camera";
- if (hasAudio.value)
- return "Microphone";
- if (hasScreenShare.value)
- return "Screen";
- if (hasWindowShare.value)
- return "Window";
- return "none";
-}
-
-addMessageListener("Test:GetMediaCaptureState", data => {
- sendAsyncMessage("Test:MediaCaptureState", _getMediaCaptureState());
-});
-
-addMessageListener("Test:WaitForObserverCall", ({data}) => {
- let topic = data;
- Services.obs.addObserver(function observer() {
- sendAsyncMessage("Test:ObserverCalled", topic);
- Services.obs.removeObserver(observer, topic);
-
- if (kObservedTopics.indexOf(topic) != -1) {
- if (!(topic in gObservedTopics))
- gObservedTopics[topic] = -1;
- else
- --gObservedTopics[topic];
- }
- }, topic, false);
-});
-
-addMessageListener("Test:WaitForMessage", () => {
- content.addEventListener("message", ({data}) => {
- sendAsyncMessage("Test:MessageReceived", data);
- }, {once: true});
-});
diff --git a/browser/base/content/test/webrtc/head.js b/browser/base/content/test/webrtc/head.js
deleted file mode 100644
index 70b183773..000000000
--- a/browser/base/content/test/webrtc/head.js
+++ /dev/null
@@ -1,453 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-
-const PREF_PERMISSION_FAKE = "media.navigator.permission.fake";
-const CONTENT_SCRIPT_HELPER = getRootDirectory(gTestPath) + "get_user_media_content_script.js";
-
-function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
- var tries = 0;
- var interval = setInterval(function() {
- if (tries >= retryTimes) {
- ok(false, errorMsg);
- moveOn();
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, 100);
- var moveOn = function() { clearInterval(interval); nextTest(); };
-}
-
-function promiseWaitForCondition(aConditionFn) {
- let deferred = Promise.defer();
- waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
- return deferred.promise;
-}
-
-/**
- * Waits for a window with the given URL to exist.
- *
- * @param url
- * The url of the window.
- * @return {Promise} resolved when the window exists.
- * @resolves to the window
- */
-function promiseWindow(url) {
- info("expecting a " + url + " window");
- return new Promise(resolve => {
- Services.obs.addObserver(function obs(win) {
- win.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function loadHandler() {
- win.removeEventListener("load", loadHandler);
-
- if (win.location.href !== url) {
- info("ignoring a window with this url: " + win.location.href);
- return;
- }
-
- Services.obs.removeObserver(obs, "domwindowopened");
- resolve(win);
- });
- }, "domwindowopened", false);
- });
-}
-
-function whenDelayedStartupFinished(aWindow) {
- return new Promise(resolve => {
- info("Waiting for delayed startup to finish");
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- resolve();
- }
- }, "browser-delayed-startup-finished", false);
- });
-}
-
-function promiseIndicatorWindow() {
- // We don't show the indicator window on Mac.
- if ("nsISystemStatusBar" in Ci)
- return Promise.resolve();
-
- return promiseWindow("chrome://browser/content/webrtcIndicator.xul");
-}
-
-function* assertWebRTCIndicatorStatus(expected) {
- let ui = Cu.import("resource:///modules/webrtcUI.jsm", {}).webrtcUI;
- let expectedState = expected ? "visible" : "hidden";
- let msg = "WebRTC indicator " + expectedState;
- if (!expected && ui.showGlobalIndicator) {
- // It seems the global indicator is not always removed synchronously
- // in some cases.
- info("waiting for the global indicator to be hidden");
- yield promiseWaitForCondition(() => !ui.showGlobalIndicator);
- }
- is(ui.showGlobalIndicator, !!expected, msg);
-
- let expectVideo = false, expectAudio = false, expectScreen = false;
- if (expected) {
- if (expected.video)
- expectVideo = true;
- if (expected.audio)
- expectAudio = true;
- if (expected.screen)
- expectScreen = true;
- }
- is(ui.showCameraIndicator, expectVideo, "camera global indicator as expected");
- is(ui.showMicrophoneIndicator, expectAudio, "microphone global indicator as expected");
- is(ui.showScreenSharingIndicator, expectScreen, "screen global indicator as expected");
-
- let windows = Services.wm.getEnumerator("navigator:browser");
- while (windows.hasMoreElements()) {
- let win = windows.getNext();
- let menu = win.document.getElementById("tabSharingMenu");
- is(menu && !menu.hidden, !!expected, "WebRTC menu should be " + expectedState);
- }
-
- if (!("nsISystemStatusBar" in Ci)) {
- if (!expected) {
- let win = Services.wm.getMostRecentWindow("Browser:WebRTCGlobalIndicator");
- if (win) {
- yield new Promise((resolve, reject) => {
- win.addEventListener("unload", function listener(e) {
- if (e.target == win.document) {
- win.removeEventListener("unload", listener);
- resolve();
- }
- }, false);
- });
- }
- }
- let indicator = Services.wm.getEnumerator("Browser:WebRTCGlobalIndicator");
- let hasWindow = indicator.hasMoreElements();
- is(hasWindow, !!expected, "popup " + msg);
- if (hasWindow) {
- let document = indicator.getNext().document;
- let docElt = document.documentElement;
-
- if (document.readyState != "complete") {
- info("Waiting for the sharing indicator's document to load");
- let deferred = Promise.defer();
- document.addEventListener("readystatechange",
- function onReadyStateChange() {
- if (document.readyState != "complete")
- return;
- document.removeEventListener("readystatechange", onReadyStateChange);
- deferred.resolve();
- });
- yield deferred.promise;
- }
-
- for (let item of ["video", "audio", "screen"]) {
- let expectedValue = (expected && expected[item]) ? "true" : "";
- is(docElt.getAttribute("sharing" + item), expectedValue,
- item + " global indicator attribute as expected");
- }
-
- ok(!indicator.hasMoreElements(), "only one global indicator window");
- }
- }
-}
-
-function promisePopupEvent(popup, eventSuffix) {
- let endState = {shown: "open", hidden: "closed"}[eventSuffix];
-
- if (popup.state == endState)
- return Promise.resolve();
-
- let eventType = "popup" + eventSuffix;
- let deferred = Promise.defer();
- popup.addEventListener(eventType, function onPopupShown(event) {
- popup.removeEventListener(eventType, onPopupShown);
- deferred.resolve();
- });
-
- return deferred.promise;
-}
-
-function promiseNotificationShown(notification) {
- let win = notification.browser.ownerGlobal;
- if (win.PopupNotifications.panel.state == "open") {
- return Promise.resolve();
- }
- let panelPromise = promisePopupEvent(win.PopupNotifications.panel, "shown");
- notification.reshow();
- return panelPromise;
-}
-
-function _mm() {
- return gBrowser.selectedBrowser.messageManager;
-}
-
-function promiseObserverCalled(aTopic) {
- return new Promise(resolve => {
- let mm = _mm();
- mm.addMessageListener("Test:ObserverCalled", function listener({data}) {
- if (data == aTopic) {
- ok(true, "got " + aTopic + " notification");
- mm.removeMessageListener("Test:ObserverCalled", listener);
- resolve();
- }
- });
- mm.sendAsyncMessage("Test:WaitForObserverCall", aTopic);
- });
-}
-
-function expectObserverCalled(aTopic) {
- return new Promise(resolve => {
- let mm = _mm();
- mm.addMessageListener("Test:ExpectObserverCalled:Reply",
- function listener({data}) {
- is(data.count, 1, "expected notification " + aTopic);
- mm.removeMessageListener("Test:ExpectObserverCalled:Reply", listener);
- resolve();
- });
- mm.sendAsyncMessage("Test:ExpectObserverCalled", aTopic);
- });
-}
-
-function expectNoObserverCalled() {
- return new Promise(resolve => {
- let mm = _mm();
- mm.addMessageListener("Test:ExpectNoObserverCalled:Reply",
- function listener({data}) {
- mm.removeMessageListener("Test:ExpectNoObserverCalled:Reply", listener);
- for (let topic in data) {
- if (data[topic])
- is(data[topic], 0, topic + " notification unexpected");
- }
- resolve();
- });
- mm.sendAsyncMessage("Test:ExpectNoObserverCalled");
- });
-}
-
-function promiseMessage(aMessage, aAction) {
- let promise = new Promise((resolve, reject) => {
- let mm = _mm();
- mm.addMessageListener("Test:MessageReceived", function listener({data}) {
- is(data, aMessage, "received " + aMessage);
- if (data == aMessage)
- resolve();
- else
- reject();
- mm.removeMessageListener("Test:MessageReceived", listener);
- });
- mm.sendAsyncMessage("Test:WaitForMessage");
- });
-
- if (aAction)
- aAction();
-
- return promise;
-}
-
-function promisePopupNotificationShown(aName, aAction) {
- let deferred = Promise.defer();
-
- PopupNotifications.panel.addEventListener("popupshown", function popupNotifShown() {
- PopupNotifications.panel.removeEventListener("popupshown", popupNotifShown);
-
- ok(!!PopupNotifications.getNotification(aName), aName + " notification shown");
- ok(PopupNotifications.isPanelOpen, "notification panel open");
- ok(!!PopupNotifications.panel.firstChild, "notification panel populated");
-
- deferred.resolve();
- });
-
- if (aAction)
- aAction();
-
- return deferred.promise;
-}
-
-function promisePopupNotification(aName) {
- let deferred = Promise.defer();
-
- waitForCondition(() => PopupNotifications.getNotification(aName),
- () => {
- ok(!!PopupNotifications.getNotification(aName),
- aName + " notification appeared");
-
- deferred.resolve();
- }, "timeout waiting for popup notification " + aName);
-
- return deferred.promise;
-}
-
-function promiseNoPopupNotification(aName) {
- let deferred = Promise.defer();
-
- waitForCondition(() => !PopupNotifications.getNotification(aName),
- () => {
- ok(!PopupNotifications.getNotification(aName),
- aName + " notification removed");
- deferred.resolve();
- }, "timeout waiting for popup notification " + aName + " to disappear");
-
- return deferred.promise;
-}
-
-const kActionAlways = 1;
-const kActionDeny = 2;
-const kActionNever = 3;
-
-function activateSecondaryAction(aAction) {
- let notification = PopupNotifications.panel.firstChild;
- notification.button.focus();
- let popup = notification.menupopup;
- popup.addEventListener("popupshown", function () {
- popup.removeEventListener("popupshown", arguments.callee, false);
-
- // Press 'down' as many time as needed to select the requested action.
- while (aAction--)
- EventUtils.synthesizeKey("VK_DOWN", {});
-
- // Activate
- EventUtils.synthesizeKey("VK_RETURN", {});
- }, false);
-
- // One down event to open the popup
- EventUtils.synthesizeKey("VK_DOWN",
- { altKey: !navigator.platform.includes("Mac") });
-}
-
-function getMediaCaptureState() {
- return new Promise(resolve => {
- let mm = _mm();
- mm.addMessageListener("Test:MediaCaptureState", ({data}) => {
- resolve(data);
- });
- mm.sendAsyncMessage("Test:GetMediaCaptureState");
- });
-}
-
-function* stopSharing(aType = "camera") {
- let promiseRecordingEvent = promiseObserverCalled("recording-device-events");
- gIdentityHandler._identityBox.click();
- let permissions = document.getElementById("identity-popup-permission-list");
- let cancelButton =
- permissions.querySelector(".identity-popup-permission-icon." + aType + "-icon ~ " +
- ".identity-popup-permission-remove-button");
- cancelButton.click();
- gIdentityHandler._identityPopup.hidden = true;
- yield promiseRecordingEvent;
- yield expectObserverCalled("getUserMedia:revoke");
- yield expectObserverCalled("recording-window-ended");
- yield expectNoObserverCalled();
- yield* checkNotSharing();
-}
-
-function promiseRequestDevice(aRequestAudio, aRequestVideo, aFrameId, aType) {
- info("requesting devices");
- return ContentTask.spawn(gBrowser.selectedBrowser,
- {aRequestAudio, aRequestVideo, aFrameId, aType},
- function*(args) {
- let global = content.wrappedJSObject;
- if (args.aFrameId)
- global = global.document.getElementById(args.aFrameId).contentWindow;
- global.requestDevice(args.aRequestAudio, args.aRequestVideo, args.aType);
- });
-}
-
-function* closeStream(aAlreadyClosed, aFrameId) {
- yield expectNoObserverCalled();
-
- let promises;
- if (!aAlreadyClosed) {
- promises = [promiseObserverCalled("recording-device-events"),
- promiseObserverCalled("recording-window-ended")];
- }
-
- info("closing the stream");
- yield ContentTask.spawn(gBrowser.selectedBrowser, aFrameId, function*(aFrameId) {
- let global = content.wrappedJSObject;
- if (aFrameId)
- global = global.document.getElementById(aFrameId).contentWindow;
- global.closeStream();
- });
-
- if (promises)
- yield Promise.all(promises);
-
- yield* assertWebRTCIndicatorStatus(null);
-}
-
-function checkDeviceSelectors(aAudio, aVideo) {
- let micSelector = document.getElementById("webRTC-selectMicrophone");
- if (aAudio)
- ok(!micSelector.hidden, "microphone selector visible");
- else
- ok(micSelector.hidden, "microphone selector hidden");
-
- let cameraSelector = document.getElementById("webRTC-selectCamera");
- if (aVideo)
- ok(!cameraSelector.hidden, "camera selector visible");
- else
- ok(cameraSelector.hidden, "camera selector hidden");
-}
-
-function* checkSharingUI(aExpected, aWin = window) {
- let doc = aWin.document;
- // First check the icon above the control center (i) icon.
- let identityBox = doc.getElementById("identity-box");
- ok(identityBox.hasAttribute("sharing"), "sharing attribute is set");
- let sharing = identityBox.getAttribute("sharing");
- if (aExpected.video)
- is(sharing, "camera", "showing camera icon on the control center icon");
- else if (aExpected.audio)
- is(sharing, "microphone", "showing mic icon on the control center icon");
-
- // Then check the sharing indicators inside the control center panel.
- identityBox.click();
- let permissions = doc.getElementById("identity-popup-permission-list");
- for (let id of ["microphone", "camera", "screen"]) {
- let convertId = id => {
- if (id == "camera")
- return "video";
- if (id == "microphone")
- return "audio";
- return id;
- };
- let expected = aExpected[convertId(id)];
- is(!!aWin.gIdentityHandler._sharingState[id], !!expected,
- "sharing state for " + id + " as expected");
- let icon = permissions.querySelectorAll(
- ".identity-popup-permission-icon." + id + "-icon");
- if (expected) {
- is(icon.length, 1, "should show " + id + " icon in control center panel");
- ok(icon[0].classList.contains("in-use"), "icon should have the in-use class");
- } else if (!icon.length) {
- ok(true, "should not show " + id + " icon in the control center panel");
- } else {
- // This will happen if there are persistent permissions set.
- ok(!icon[0].classList.contains("in-use"),
- "if shown, the " + id + " icon should not have the in-use class");
- is(icon.length, 1, "should not show more than 1 " + id + " icon");
- }
- }
- aWin.gIdentityHandler._identityPopup.hidden = true;
-
- // Check the global indicators.
- yield* assertWebRTCIndicatorStatus(aExpected);
-}
-
-function* checkNotSharing() {
- is((yield getMediaCaptureState()), "none", "expected nothing to be shared");
-
- ok(!document.getElementById("identity-box").hasAttribute("sharing"),
- "no sharing indicator on the control center icon");
-
- yield* assertWebRTCIndicatorStatus(null);
-}
diff --git a/browser/components/contextualidentity/test/browser/.eslintrc.js b/browser/components/contextualidentity/test/browser/.eslintrc.js
deleted file mode 100644
index e25a6863e..000000000
--- a/browser/components/contextualidentity/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,11 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ],
-
- "rules": {
- "no-undef": "error"
- }
-};
diff --git a/browser/components/contextualidentity/test/browser/browser.ini b/browser/components/contextualidentity/test/browser/browser.ini
deleted file mode 100644
index 55083f8d2..000000000
--- a/browser/components/contextualidentity/test/browser/browser.ini
+++ /dev/null
@@ -1,30 +0,0 @@
-[DEFAULT]
-support-files =
- empty_file.html
- file_reflect_cookie_into_title.html
- favicon-normal32.png
- file_set_storages.html
- serviceworker.html
- worker.js
-
-[browser_aboutURLs.js]
-[browser_eme.js]
-[browser_favicon.js]
-[browser_forgetaboutsite.js]
-[browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js]
-[browser_forgetAPI_EME_forgetThisSite.js]
-[browser_forgetAPI_quota_clearStoragesForPrincipal.js]
-[browser_newtabButton.js]
-[browser_usercontext.js]
-[browser_usercontextid_tabdrop.js]
-skip-if = os == "mac" || os == "win" # Intermittent failure - bug 1268276
-[browser_windowName.js]
-tags = openwindow
-[browser_windowOpen.js]
-tags = openwindow
-[browser_serviceworkers.js]
-[browser_broadcastchannel.js]
-[browser_blobUrl.js]
-[browser_middleClick.js]
-[browser_imageCache.js]
-[browser_count_and_remove.js]
diff --git a/browser/components/contextualidentity/test/browser/browser_aboutURLs.js b/browser/components/contextualidentity/test/browser/browser_aboutURLs.js
deleted file mode 100644
index 586bca37f..000000000
--- a/browser/components/contextualidentity/test/browser/browser_aboutURLs.js
+++ /dev/null
@@ -1,49 +0,0 @@
-"use strict";
-
-// For some about: URLs, they will take more time to load and cause timeout.
-// See Bug 1270998.
-requestLongerTimeout(2);
-
-add_task(function* () {
- let aboutURLs = [];
-
- // List of about: URLs that will initiate network requests.
- let networkURLs = [
- "credits",
- "telemetry" // about:telemetry will fetch Telemetry asynchrounously and takes
- // longer, we skip this for now.
- ];
-
- let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- for (let cid in Cc) {
- let result = cid.match(/@mozilla.org\/network\/protocol\/about;1\?what\=(.*)$/);
- if (!result) {
- continue;
- }
-
- let aboutType = result[1];
- let contract = "@mozilla.org/network/protocol/about;1?what=" + aboutType;
- try {
- let am = Cc[contract].getService(Ci.nsIAboutModule);
- let uri = ios.newURI("about:"+aboutType, null, null);
- let flags = am.getURIFlags(uri);
- if (!(flags & Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT) &&
- networkURLs.indexOf(aboutType) == -1) {
- aboutURLs.push(aboutType);
- }
- } catch (e) {
- // getService might have thrown if the component doesn't actually
- // implement nsIAboutModule
- }
- }
-
- for (let url of aboutURLs) {
- info("Loading about:" + url);
- let tab = gBrowser.addTab("about:"+url, {userContextId: 1});
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- ok(true, "Done loading about:" + url);
-
- yield BrowserTestUtils.removeTab(tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_blobUrl.js b/browser/components/contextualidentity/test/browser/browser_blobUrl.js
deleted file mode 100644
index 8a441311e..000000000
--- a/browser/components/contextualidentity/test/browser/browser_blobUrl.js
+++ /dev/null
@@ -1,78 +0,0 @@
-"use strict";
-
-// Here we want to test that blob URLs are not available cross containers.
-
-const BASE_URI = "http://mochi.test:8888/browser/browser/components/"
- + "contextualidentity/test/browser/empty_file.html";
-
-add_task(function* setup() {
- yield new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]}, resolve);
- });
-});
-
-
-add_task(function* test() {
- info("Creating a tab with UCI = 1...");
- let tab1 = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab1.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
-
- let browser1 = gBrowser.getBrowserForTab(tab1);
- yield BrowserTestUtils.browserLoaded(browser1);
-
- let blobURL;
-
- info("Creating a blob URL...");
- yield ContentTask.spawn(browser1, null, function() {
- return Promise.resolve(content.window.URL.createObjectURL(new content.window.Blob([123])));
- }).then(newURL => { blobURL = newURL });
-
- info("Blob URL: " + blobURL);
-
- info("Creating a tab with UCI = 2...");
- let tab2 = gBrowser.addTab(BASE_URI, {userContextId: 2});
- is(tab2.getAttribute('usercontextid'), 2, "New tab has UCI equal 2");
-
- let browser2 = gBrowser.getBrowserForTab(tab2);
- yield BrowserTestUtils.browserLoaded(browser2);
-
- yield ContentTask.spawn(browser2, blobURL, function(url) {
- return new Promise(resolve => {
- var xhr = new content.window.XMLHttpRequest();
- xhr.onerror = function() { resolve("SendErrored"); }
- xhr.onload = function() { resolve("SendLoaded"); }
- xhr.open("GET", url);
- xhr.send();
- });
- }).then(status => {
- is(status, "SendErrored", "Using a blob URI from one user context id in another should not work");
- });
-
- info("Creating a tab with UCI = 1...");
- let tab3 = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab3.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
-
- let browser3 = gBrowser.getBrowserForTab(tab3);
- yield BrowserTestUtils.browserLoaded(browser3);
-
- yield ContentTask.spawn(browser3, blobURL, function(url) {
- return new Promise(resolve => {
- var xhr = new content.window.XMLHttpRequest();
- xhr.open("GET", url);
- try {
- xhr.send();
- resolve("SendSucceeded");
- } catch (e) {
- resolve("SendThrew");
- }
- });
- }).then(status => {
- is(status, "SendSucceeded", "Using a blob URI within a single user context id should work");
- });
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
- yield BrowserTestUtils.removeTab(tab3);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js b/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js
deleted file mode 100644
index a821ce96b..000000000
--- a/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js
+++ /dev/null
@@ -1,80 +0,0 @@
-let { classes: Cc, interfaces: Ci } = Components;
-
-const BASE_ORIGIN = "http://example.com";
-const URI = BASE_ORIGIN +
- "/browser/browser/components/contextualidentity/test/browser/empty_file.html";
-
-// opens `uri' in a new tab with the provided userContextId and focuses it.
-// returns the newly opened tab
-function* openTabInUserContext(uri, userContextId) {
- // open the tab in the correct userContextId
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // select tab and make sure its browser is focused
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]}, resolve);
- });
-});
-
-add_task(function* test() {
- let receiver = yield* openTabInUserContext(URI, 2);
-
- let channelName = "contextualidentity-broadcastchannel";
-
- // reflect the received message on title
- yield ContentTask.spawn(receiver.browser, channelName,
- function (name) {
- content.window.testPromise = new content.window.Promise(resolve => {
- content.window.bc = new content.window.BroadcastChannel(name);
- content.window.bc.onmessage = function (e) {
- content.document.title += e.data;
- resolve();
- }
- });
- }
- );
-
- let sender1 = yield* openTabInUserContext(URI, 1);
- let sender2 = yield* openTabInUserContext(URI, 2);
- sender1.message = "Message from user context #1";
- sender2.message = "Message from user context #2";
-
- // send a message from a tab in different user context first
- // then send a message from a tab in the same user context
- for (let sender of [sender1, sender2]) {
- yield ContentTask.spawn(
- sender.browser,
- { name: channelName, message: sender.message },
- function (opts) {
- let bc = new content.window.BroadcastChannel(opts.name);
- bc.postMessage(opts.message);
- });
- }
-
- // Since sender1 sends before sender2, if the title is exactly
- // sender2's message, sender1's message must've been blocked
- yield ContentTask.spawn(receiver.browser, sender2.message,
- function* (message) {
- yield content.window.testPromise.then(function() {
- is(content.document.title, message,
- "should only receive messages from the same user context");
- });
- }
- );
-
- gBrowser.removeTab(sender1.tab);
- gBrowser.removeTab(sender2.tab);
- gBrowser.removeTab(receiver.tab);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_count_and_remove.js b/browser/components/contextualidentity/test/browser/browser_count_and_remove.js
deleted file mode 100644
index 23b7e948a..000000000
--- a/browser/components/contextualidentity/test/browser/browser_count_and_remove.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/ContextualIdentityService.jsm");
-
-function openTabInUserContext(userContextId) {
- let tab = gBrowser.addTab("about:blank", {userContextId});
- gBrowser.selectedTab = tab;
-}
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]});
-});
-
-add_task(function* test() {
- is(ContextualIdentityService.countContainerTabs(), 0, "0 container tabs by default.");
-
- openTabInUserContext(1);
- is(ContextualIdentityService.countContainerTabs(), 1, "1 container tab created");
-
- openTabInUserContext(1);
- is(ContextualIdentityService.countContainerTabs(), 2, "2 container tab created");
-
- openTabInUserContext(2);
- is(ContextualIdentityService.countContainerTabs(), 3, "3 container tab created");
-
- ContextualIdentityService.closeAllContainerTabs();
- is(ContextualIdentityService.countContainerTabs(), 0, "0 container tab at the end.");
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_eme.js b/browser/components/contextualidentity/test/browser/browser_eme.js
deleted file mode 100644
index 557648d60..000000000
--- a/browser/components/contextualidentity/test/browser/browser_eme.js
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Bug 1283325 - A test case to test the EME is originAttributes aware or not.
- */
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-const TEST_HOST = "example.com";
-const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
-
-const TESTKEY = {
- initDataType: 'keyids',
- initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}',
- kid: "LwVHf8JLtPrv2GUXFW2v_A",
- key: "97b9ddc459c8d5ff23c1f2754c95abe8",
- sessionType: 'persistent-license',
-};
-
-const USER_ID_DEFAULT = 0;
-const USER_ID_PERSONAL = 1;
-
-function* openTabInUserContext(uri, userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerDocument.defaultView.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function HexToBase64(hex)
-{
- var bin = "";
- for (var i = 0; i < hex.length; i += 2) {
- bin += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
- }
- return window.btoa(bin).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
-}
-
-function Base64ToHex(str)
-{
- var bin = window.atob(str.replace(/-/g, "+").replace(/_/g, "/"));
- var res = "";
- for (var i = 0; i < bin.length; i++) {
- res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
- }
- return res;
-}
-
-function ByteArrayToHex(array) {
- let bin = String.fromCharCode.apply(null, new Uint8Array(array));
- let res = "";
-
- for (let i = 0; i < bin.length; i++) {
- res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
- }
-
- return res;
-}
-
-function generateKeyObject(aKid, aKey) {
- let keyObj = {
- kty: 'oct',
- kid: aKid,
- k: HexToBase64(aKey),
- };
-
- return new TextEncoder().encode(JSON.stringify({
- keys: [keyObj]
- }));
-}
-
-function generateKeyInfo(aData) {
- let keyInfo = {
- initDataType: aData.initDataType,
- initData: new TextEncoder().encode(aData.initData),
- sessionType: aData.sessionType,
- keyObj: generateKeyObject(aData.kid, aData.key),
- };
-
- return keyInfo;
-}
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- [ "privacy.userContext.enabled", true ],
- [ "media.mediasource.enabled", true ],
- [ "media.eme.apiVisible", true ],
- [ "media.mediasource.webm.enabled", true ],
- [ "media.clearkey.persistent-license.enabled", true ],
- ]}, resolve);
- });
-});
-
-add_task(function* test() {
- // Open a tab with the default container.
- let defaultContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_DEFAULT);
-
- // Generate the key info for the default container.
- let keyInfo = generateKeyInfo(TESTKEY);
-
- // Update the media key for the default container.
- let result = yield ContentTask.spawn(defaultContainer.browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
- [{
- initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
- }]);
- let mediaKeys = yield access.createMediaKeys();
- let session = mediaKeys.createSession(aKeyInfo.sessionType);
- let res = {};
-
- // Insert the media key.
- yield new Promise(resolve => {
- session.addEventListener("message", function(event) {
- session.update(aKeyInfo.keyObj).then(
- () => { resolve(); }
- ).catch(
- () => {
- ok(false, "Update the media key fail.");
- resolve();
- }
- );
- });
-
- session.generateRequest(aKeyInfo.initDataType, aKeyInfo.initData);
- });
-
- let map = session.keyStatuses;
-
- is(map.size, 1, "One media key has been added.");
-
- if (map.size === 1) {
- res.keyId = map.keys().next().value;
- res.sessionId = session.sessionId;
- }
-
- // Close the session.
- session.close();
- yield session.closed;
-
- return res;
- });
-
- // Check the media key ID.
- is(ByteArrayToHex(result.keyId), Base64ToHex(TESTKEY.kid), "The key Id of the default container is correct.");
-
- // Store the sessionId for the further checking.
- keyInfo.sessionId = result.sessionId;
-
- // Open a tab with personal container.
- let personalContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_PERSONAL);
-
- yield ContentTask.spawn(personalContainer.browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
- [{
- initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
- }]);
- let mediaKeys = yield access.createMediaKeys();
- let session = mediaKeys.createSession(aKeyInfo.sessionType);
-
- // First, load the session to check that mediakeys do not share with
- // default container.
- yield session.load(aKeyInfo.sessionId);
-
- let map = session.keyStatuses;
-
- // Check that there is no media key here.
- is(map.size, 0, "No media key should be here for the personal container.");
- });
-
- // Close default container tab.
- yield BrowserTestUtils.removeTab(defaultContainer.tab);
-
- // Close personal container tab.
- yield BrowserTestUtils.removeTab(personalContainer.tab);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_favicon.js b/browser/components/contextualidentity/test/browser/browser_favicon.js
deleted file mode 100644
index a0a7eb208..000000000
--- a/browser/components/contextualidentity/test/browser/browser_favicon.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Bug 1270678 - A test case to test does the favicon obey originAttributes.
- */
-let { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
-
-const USER_CONTEXTS = [
- "default",
- "personal",
- "work",
-];
-
-let gHttpServer = null;
-let gUserContextId;
-let gFaviconData;
-
-function getIconFile() {
- new Promise(resolve => {
- NetUtil.asyncFetch({
- uri: "http://www.example.com/browser/browser/components/contextualidentity/test/browser/favicon-normal32.png",
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- }, function(inputStream, status) {
- let size = inputStream.available();
- gFaviconData = NetUtil.readInputStreamToString(inputStream, size);
- resolve();
- });
- });
-}
-
-function* openTabInUserContext(uri, userContextId) {
- // open the tab in the correct userContextId
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // select tab and make sure its browser is focused
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function loadIndexHandler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, "Ok");
- response.setHeader("Content-Type", "text/html", false);
- let body = `
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Favicon Test</title>
- </head>
- <body>
- Favicon!!
- </body>
- </html>`;
- response.bodyOutputStream.write(body, body.length);
-}
-
-function loadFaviconHandler(metadata, response) {
- let expectedCookie = "userContext=" + USER_CONTEXTS[gUserContextId];
-
- if (metadata.hasHeader("Cookie")) {
- is(metadata.getHeader("Cookie"), expectedCookie, "The cookie has matched with the expected cookie.");
- } else {
- ok(false, "The request should have a cookie.");
- }
-
- response.setStatusLine(metadata.httpVersion, 200, "Ok");
- response.setHeader("Content-Type", "image/png", false);
- response.bodyOutputStream.write(gFaviconData, gFaviconData.length);
-}
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]}, resolve);
- });
-
- // Create a http server for the image cache test.
- if (!gHttpServer) {
- gHttpServer = new HttpServer();
- gHttpServer.registerPathHandler('/', loadIndexHandler);
- gHttpServer.registerPathHandler('/favicon.png', loadFaviconHandler);
- gHttpServer.start(-1);
- }
-});
-
-registerCleanupFunction(() => {
- gHttpServer.stop(() => {
- gHttpServer = null;
- });
-});
-
-add_task(function* test() {
- waitForExplicitFinish();
-
- // First, get the icon data.
- yield getIconFile();
-
- let serverPort = gHttpServer.identity.primaryPort;
- let testURL = "http://localhost:" + serverPort + "/";
- let testFaviconURL = "http://localhost:" + serverPort + "/favicon.png";
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- gUserContextId = userContextId;
-
- // Load the page in 3 different contexts and set a cookie
- // which should only be visible in that context.
-
- // Open our tab in the given user context.
- let tabInfo = yield* openTabInUserContext(testURL, userContextId);
-
- // Write a cookie according to the userContext.
- yield ContentTask.spawn(tabInfo.browser, { userContext: USER_CONTEXTS[userContextId] }, function (arg) {
- content.document.cookie = "userContext=" + arg.userContext;
- });
-
- let pageURI = NetUtil.newURI(testURL);
- let favIconURI = NetUtil.newURI(testFaviconURL);
-
- yield new Promise(resolve => {
- PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
- true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, {
- onComplete() {
- resolve();
- },
- },
- tabInfo.browser.contentPrincipal);
- });
-
- yield BrowserTestUtils.removeTab(tabInfo.tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
deleted file mode 100644
index 1a97448c0..000000000
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Bug 1278037 - A Test case for checking whether forgetting APIs are working for the media key.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-const TEST_HOST = "example.com";
-const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
-
-const USER_CONTEXTS = [
- "default",
- "personal",
-];
-
-const TEST_EME_KEY = {
- initDataType: 'keyids',
- initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}',
- kid: "LwVHf8JLtPrv2GUXFW2v_A",
- key: "97b9ddc459c8d5ff23c1f2754c95abe8",
- sessionType: 'persistent-license',
-};
-
-//
-// Support functions.
-//
-
-function* openTabInUserContext(uri, userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function HexToBase64(hex) {
- var bin = "";
- for (var i = 0; i < hex.length; i += 2) {
- bin += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
- }
- return window.btoa(bin).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
-}
-
-function Base64ToHex(str) {
- var bin = window.atob(str.replace(/-/g, "+").replace(/_/g, "/"));
- var res = "";
- for (var i = 0; i < bin.length; i++) {
- res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
- }
- return res;
-}
-
-function ByteArrayToHex(array) {
- let bin = String.fromCharCode.apply(null, new Uint8Array(array));
- let res = "";
-
- for (let i = 0; i < bin.length; i++) {
- res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
- }
-
- return res;
-}
-
-function generateKeyObject(aKid, aKey) {
- let keyObj = {
- kty: 'oct',
- kid: aKid,
- k: HexToBase64(aKey),
- };
-
- return new TextEncoder().encode(JSON.stringify({
- keys: [keyObj]
- }));
-}
-
-function generateKeyInfo(aData) {
- let keyInfo = {
- initDataType: aData.initDataType,
- initData: new TextEncoder().encode(aData.initData),
- sessionType: aData.sessionType,
- keyObj: generateKeyObject(aData.kid, aData.key),
- };
-
- return keyInfo;
-}
-
-// Setup a EME key for the given browser, and return the sessionId.
-function* setupEMEKey(browser) {
- // Generate the key info.
- let keyInfo = generateKeyInfo(TEST_EME_KEY);
-
- // Setup the EME key.
- let result = yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
- [{
- initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
- }]);
- let mediaKeys = yield access.createMediaKeys();
- let session = mediaKeys.createSession(aKeyInfo.sessionType);
- let res = {};
-
- // Insert the EME key.
- yield new Promise(resolve => {
- session.addEventListener("message", function(event) {
- session.update(aKeyInfo.keyObj).then(
- () => { resolve(); }
- ).catch(
- () => {
- ok(false, "Update the EME key fail.");
- resolve();
- }
- );
- });
-
- session.generateRequest(aKeyInfo.initDataType, aKeyInfo.initData);
- });
-
- let map = session.keyStatuses;
-
- is(map.size, 1, "One EME key has been added.");
-
- if (map.size === 1) {
- res.keyId = map.keys().next().value;
- res.sessionId = session.sessionId;
- }
-
- // Close the session.
- session.close();
- yield session.closed;
-
- return res;
- });
-
- // Check the EME key ID.
- is(ByteArrayToHex(result.keyId), Base64ToHex(TEST_EME_KEY.kid), "The key Id is correct.");
- return result.sessionId;
-}
-
-// Check whether the EME key has been cleared.
-function* checkEMEKey(browser, emeSessionId) {
- // Generate the key info.
- let keyInfo = generateKeyInfo(TEST_EME_KEY);
- keyInfo.sessionId = emeSessionId;
-
- yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
- [{
- initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
- }]);
- let mediaKeys = yield access.createMediaKeys();
- let session = mediaKeys.createSession(aKeyInfo.sessionType);
-
- // First, load the session with the sessionId.
- yield session.load(aKeyInfo.sessionId);
-
- let map = session.keyStatuses;
-
- // Check that there is no media key here.
- is(map.size, 0, "No media key should be here after forgetThisSite() was called.");
- });
-}
-
-//
-// Test functions.
-//
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- [ "privacy.userContext.enabled", true ],
- [ "media.mediasource.enabled", true ],
- [ "media.eme.apiVisible", true ],
- [ "media.mediasource.webm.enabled", true ],
- [ "media.clearkey.persistent-license.enabled", true ],
- ]});
-});
-
-add_task(function* test_EME_forgetThisSite() {
- let tabs = [];
- let emeSessionIds = [];
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId);
-
- // Setup EME Key.
- emeSessionIds[userContextId] = yield setupEMEKey(tabs[userContextId].browser);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-
- // Clear all EME data for a given domain with originAttributes pattern.
- let mps = Cc["@mozilla.org/gecko-media-plugin-service;1"].
- getService(Ci.mozIGeckoMediaPluginChromeService);
- mps.forgetThisSite(TEST_HOST, JSON.stringify({}));
-
- // Open tabs again to check EME keys have been cleared.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId);
-
- // Check whether EME Key has been cleared.
- yield checkEMEKey(tabs[userContextId].browser, emeSessionIds[userContextId]);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js
deleted file mode 100644
index 1d9024d25..000000000
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Bug 1278037 - A Test case for checking whether forgetting APIs are working for cookies.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-const TEST_HOST = "example.com";
-const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
-
-const USER_CONTEXTS = [
- "default",
- "personal",
-];
-
-//
-// Support functions.
-//
-
-function* openTabInUserContext(uri, userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function getCookiesForOA(host, userContextId) {
- return Services.cookies.getCookiesFromHost(host, {userContextId});
-}
-
-//
-// Test functions.
-//
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- [ "privacy.userContext.enabled", true ],
- ]});
-});
-
-add_task(function* test_cookie_getCookiesWithOriginAttributes() {
- let tabs = [];
- let cookieName = "userContextId";
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Load the page in 2 different contexts and set a cookie
- // which should only be visible in that context.
- let value = USER_CONTEXTS[userContextId];
-
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "file_reflect_cookie_into_title.html?" + value, userContextId);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-
- // Check that cookies have been set properly.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let enumerator = getCookiesForOA(TEST_HOST, userContextId);
- ok(enumerator.hasMoreElements(), "Cookies available");
-
- let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
- is(foundCookie["name"], cookieName, "Check cookie name");
- is(foundCookie["value"], USER_CONTEXTS[userContextId], "Check cookie value");
- }
-
- // Using getCookiesWithOriginAttributes() to get all cookies for a certain
- // domain by using the originAttributes pattern, and clear all these cookies.
- let enumerator = Services.cookies.getCookiesWithOriginAttributes(JSON.stringify({}), TEST_HOST);
- while (enumerator.hasMoreElements()) {
- let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
- Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);
- }
-
- // Check that whether cookies has been cleared.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let enumerator = getCookiesForOA(TEST_HOST, userContextId);
- ok(!enumerator.hasMoreElements(), "No Cookie should be here");
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js
deleted file mode 100644
index 6a4b37c55..000000000
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Bug 1278037 - A Test case for checking whether forgetting APIs are working for the quota manager.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-const TEST_HOST = "example.com";
-const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
-
-const USER_CONTEXTS = [
- "default",
- "personal",
-];
-
-//
-// Support functions.
-//
-
-function* openTabInUserContext(uri, userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-// Setup an entry for the indexedDB.
-function* setupIndexedDB(browser) {
- yield ContentTask.spawn(browser, { input: "TestForgetAPIs" }, function* (arg) {
- let request = content.indexedDB.open("idb", 1);
-
- request.onerror = function() {
- throw new Error("error opening db connection");
- };
-
- request.onupgradeneeded = event => {
- let db = event.target.result;
- let store = db.createObjectStore("obj", { keyPath: "id" });
- store.createIndex("userContext", "userContext", { unique: false });
- };
-
- let db = yield new Promise(resolve => {
- request.onsuccess = event => {
- resolve(event.target.result);
- };
- });
-
- // Add an entry into the indexedDB.
- let transaction = db.transaction(["obj"], "readwrite");
- let store = transaction.objectStore("obj");
- store.add({id: 1, userContext: arg.input});
-
- yield new Promise(resolve => {
- transaction.oncomplete = () => {
- resolve();
- };
- });
-
- // Check the indexedDB has been set properly.
- transaction = db.transaction(["obj"], "readonly");
- store = transaction.objectStore("obj");
- let getRequest = store.get(1);
- yield new Promise(resolve => {
- getRequest.onsuccess = () => {
- let res = getRequest.result;
- is(res.userContext, arg.input, "Check the indexedDB value");
- resolve();
- };
- });
- });
-}
-
-// Check whether the indexedDB has been cleared.
-function* checkIndexedDB(browser) {
- yield ContentTask.spawn(browser, null, function* () {
- let request = content.indexedDB.open("idb", 1);
-
- let db = yield new Promise(done => {
- request.onsuccess = event => {
- done(event.target.result);
- };
- });
-
- try {
- db.transaction(["obj"], "readonly");
- ok(false, "The indexedDB should not exist");
- } catch (e) {
- is(e.name, "NotFoundError", "The indexedDB does not exist as expected");
- }
- });
-}
-
-//
-// Test functions.
-//
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- [ "privacy.userContext.enabled", true ],
- ]});
-});
-
-add_task(function* test_quota_clearStoragesForPrincipal() {
- let tabs = [];
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId);
-
- // Setup an entry for the indexedDB.
- yield setupIndexedDB(tabs[userContextId].browser);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-
- // Using quota manager to clear all indexed DB for a given domain.
- let qms = Cc["@mozilla.org/dom/quota-manager-service;1"].
- getService(Ci.nsIQuotaManagerService);
-
- let caUtils = {};
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- scriptLoader.loadSubScript("chrome://global/content/contentAreaUtils.js",
- caUtils);
- let httpURI = caUtils.makeURI("http://" + TEST_HOST);
- let httpPrincipal = Services.scriptSecurityManager
- .createCodebasePrincipal(httpURI, {});
- qms.clearStoragesForPrincipal(httpPrincipal, null, true);
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId);
-
- // Check whether indexed DB has been cleared.
- yield checkIndexedDB(tabs[userContextId].browser);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
deleted file mode 100644
index 9efc86e0c..000000000
--- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Bug 1238183 - Test cases for forgetAboutSite with userContextId.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/ForgetAboutSite.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
-let LoadContextInfo = Cc["@mozilla.org/load-context-info-factory;1"]
- .getService(Ci.nsILoadContextInfoFactory);
-let css = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
-
-const USER_CONTEXTS = [
- "default",
- "personal",
-];
-const TEST_HOST = "example.com";
-const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
-const COOKIE_NAME = "userContextId";
-
-// Counter for image load hits.
-let gHits = 0;
-
-let gHttpServer = null;
-
-function imageHandler(metadata, response) {
- // A 1x1 PNG image.
- // Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain)
- const IMAGE = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
- "ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
- gHits++;
- response.setHeader("Cache-Control", "max-age=10000", false);
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "image/png", false);
- response.write(IMAGE);
-}
-
-function loadImagePageHandler(metadata, response) {
- response.setHeader("Cache-Control", "max-age=10000", false);
- response.setStatusLine(metadata.httpVersion, 200, "Ok");
- response.setHeader("Content-Type", "text/html", false);
- let body = "<!DOCTYPE HTML>\
- <html>\
- <head>\
- <meta charset='utf-8'>\
- <title>Load Image</title>\
- </head>\
- <body>\
- <img src='image.png'>\
- </body>\
- </html>";
- response.bodyOutputStream.write(body, body.length);
-}
-
-function* openTabInUserContext(uri, userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function getCookiesForOA(host, userContextId) {
- return Services.cookies.getCookiesFromHost(host, {userContextId});
-}
-
-function createURI(uri)
-{
- let ioServ = Cc["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
- return ioServ.newURI(uri, null, null);
-}
-
-function getCacheStorage(where, lci, appcache)
-{
- if (!lci) lci = LoadContextInfo.default;
- switch (where) {
- case "disk": return css.diskCacheStorage(lci, false);
- case "memory": return css.memoryCacheStorage(lci);
- case "appcache": return css.appCacheStorage(lci, appcache);
- case "pin": return css.pinningCacheStorage(lci);
- }
- return null;
-}
-
-function OpenCacheEntry(key, where, flags, lci)
-{
- return new Promise(resolve => {
- key = createURI(key);
- function CacheListener() { }
- CacheListener.prototype = {
- _appCache: null,
-
- QueryInterface: function (iid) {
- if (iid.equals(Components.interfaces.nsICacheEntryOpenCallback) ||
- iid.equals(Components.interfaces.nsISupports))
- return this;
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- onCacheEntryCheck: function(entry, appCache) {
- return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED;
- },
-
- onCacheEntryAvailable: function (entry, isnew, appCache, status) {
- resolve();
- },
-
- run: function () {
- let storage = getCacheStorage(where, lci, this._appCache);
- storage.asyncOpenURI(key, "", flags, this);
- }
- };
-
- (new CacheListener()).run();
- });
-}
-
-//
-// Test functions.
-//
-
-// Cookies
-function* test_cookie_cleared() {
- let tabs = [];
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Load the page in 2 different contexts and set a cookie
- // which should only be visible in that context.
- let value = USER_CONTEXTS[userContextId];
-
- // Open our tab in the given user context.
- tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "file_reflect_cookie_into_title.html?" + value, userContextId);
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
- // Check that cookies have been set properly.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let enumerator = getCookiesForOA(TEST_HOST, userContextId);
- ok(enumerator.hasMoreElements(), "Cookies available");
-
- let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
- Assert.equal(foundCookie["name"], COOKIE_NAME, "Check cookie name");
- Assert.equal(foundCookie["value"], USER_CONTEXTS[userContextId], "Check cookie value");
- }
-
- // Forget the site.
- ForgetAboutSite.removeDataFromDomain(TEST_HOST);
-
- // Check that whether cookies has been cleared or not.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let enumerator = getCookiesForOA(TEST_HOST, userContextId);
- ok(!enumerator.hasMoreElements(), "No Cookie should be here");
- }
-}
-
-// Cache
-function* test_cache_cleared() {
- // First, add some caches.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- yield OpenCacheEntry("http://" + TEST_HOST + "/",
- "disk",
- Ci.nsICacheStorage.OPEN_NORMALLY,
- LoadContextInfo.custom(false, {userContextId}));
-
- yield OpenCacheEntry("http://" + TEST_HOST + "/",
- "memory",
- Ci.nsICacheStorage.OPEN_NORMALLY,
- LoadContextInfo.custom(false, {userContextId}));
- }
-
-
- // Check that caches have been set correctly.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId}));
- let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId}));
-
- Assert.ok(mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache has been set correctly");
- Assert.ok(disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache has been set correctly");
- }
-
- // Forget the site.
- ForgetAboutSite.removeDataFromDomain(TEST_HOST);
-
- // Check that do caches be removed or not?
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId}));
- let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId}));
-
- Assert.ok(!mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache is cleared");
- Assert.ok(!disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache is cleared");
- }
-}
-
-// Image Cache
-function* test_image_cache_cleared() {
- let tabs = [];
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context to cache image.
- tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html',
- userContextId);
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-
- let expectedHits = USER_CONTEXTS.length;
-
- // Check that image cache works with the userContextId.
- is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times.");
-
- // Reset the cache count.
- gHits = 0;
-
- // Forget the site.
- ForgetAboutSite.removeDataFromDomain("localhost:" + gHttpServer.identity.primaryPort + "/");
-
- // Load again.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context to cache image.
- tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html',
- userContextId);
- yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
- }
-
- // Check that image cache was cleared and the server gets another two hits.
- is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times.");
-}
-
-// Offline Storage
-function* test_storage_cleared() {
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Load the page in 2 different contexts and set the local storage
- // which should only be visible in that context.
- let value = USER_CONTEXTS[userContextId];
-
- // Open our tab in the given user context.
- let tabInfo = yield* openTabInUserContext(TEST_URL+ "file_set_storages.html?" + value, userContextId);
-
- // Check that the storages has been set correctly.
- yield ContentTask.spawn(tabInfo.browser, { userContext: USER_CONTEXTS[userContextId] }, function* (arg) {
- // Check that the local storage has been set correctly.
- Assert.equal(content.localStorage.getItem("userContext"), arg.userContext, "Check the local storage value");
-
- // Check that the session storage has been set correctly.
- Assert.equal(content.sessionStorage.getItem("userContext"), arg.userContext, "Check the session storage value");
-
- // Check that the indexedDB has been set correctly.
- let request = content.indexedDB.open("idb", 1);
-
- let db = yield new Promise(done => {
- request.onsuccess = event => {
- done(event.target.result);
- };
- });
-
- let transaction = db.transaction(["obj"], "readonly");
- let store = transaction.objectStore("obj");
- let storeRequest = store.get(1);
-
- yield new Promise(done => {
- storeRequest.onsuccess = event => {
- let res = storeRequest.result;
- Assert.equal(res.userContext, arg.userContext, "Check the indexedDB value");
- done();
- };
- });
- });
-
- // Close this tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
- }
-
- // Forget the site.
- ForgetAboutSite.removeDataFromDomain(TEST_HOST);
-
- // Open the tab again without setting the localStorage and check that the
- // local storage has been cleared or not.
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Open our tab in the given user context without setting local storage.
- let tabInfo = yield* openTabInUserContext(TEST_URL+ "file_set_storages.html", userContextId);
-
- // Check that do storages be cleared or not.
- yield ContentTask.spawn(tabInfo.browser, null, function* () {
- // Check that does the local storage be cleared or not.
- Assert.ok(!content.localStorage.getItem("userContext"), "The local storage has been cleared");
-
- // Check that does the session storage be cleared or not.
- Assert.ok(!content.sessionStorage.getItem("userContext"), "The session storage has been cleared");
-
- // Check that does the indexedDB be cleared or not.
- let request = content.indexedDB.open("idb", 1);
-
- let db = yield new Promise(done => {
- request.onsuccess = event => {
- done(event.target.result);
- };
- });
- try {
- db.transaction(["obj"], "readonly");
- Assert.ok(false, "The indexedDB should not exist");
- } catch (e) {
- Assert.equal(e.name, "NotFoundError", "The indexedDB does not exist as expected");
- }
- });
-
- // Close the tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
- }
-}
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]}, resolve);
- });
-
- // Create a http server for the image cache test.
- if (!gHttpServer) {
- gHttpServer = new HttpServer();
- gHttpServer.registerPathHandler('/image.png', imageHandler);
- gHttpServer.registerPathHandler('/loadImage.html', loadImagePageHandler);
- gHttpServer.start(-1);
- }
-});
-
-let tests = [
- test_cookie_cleared,
- test_cache_cleared,
- test_image_cache_cleared,
- test_storage_cleared,
-];
-
-add_task(function* test() {
- for (let i = 0; i < tests.length; i++)
- add_task(tests[i]);
-});
-
-registerCleanupFunction(() => {
- gHttpServer.stop(() => {
- gHttpServer = null;
- });
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_imageCache.js b/browser/components/contextualidentity/test/browser/browser_imageCache.js
deleted file mode 100644
index df36d44c1..000000000
--- a/browser/components/contextualidentity/test/browser/browser_imageCache.js
+++ /dev/null
@@ -1,59 +0,0 @@
-let Cu = Components.utils;
-let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
-
-const NUM_USER_CONTEXTS = 3;
-
-let gHits = 0;
-
-let server = new HttpServer();
-server.registerPathHandler('/image.png', imageHandler);
-server.registerPathHandler('/file.html', fileHandler);
-server.start(-1);
-
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let IMAGE_URI = BASE_URI + '/image.png';
-let FILE_URI = BASE_URI + '/file.html';
-
-function imageHandler(metadata, response) {
- gHits++;
- response.setHeader("Cache-Control", "max-age=10000", false);
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "image/png", false);
- var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII=";
- response.bodyOutputStream.write(body, body.length);
-}
-
-function fileHandler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "text/html", false);
- let body = `<html><body><image src=${IMAGE_URI}></body></html>`;
- response.bodyOutputStream.write(body, body.length);
-}
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [["privacy.userContext.enabled", true]]});
-});
-
-// opens `uri' in a new tab with the provided userContextId and focuses it.
-// returns the newly opened tab
-function* openTabInUserContext(uri, userContextId) {
- // open the tab in the correct userContextId
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // select tab and make sure its browser is focused
- gBrowser.selectedTab = tab;
- tab.ownerDocument.defaultView.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return tab;
-}
-
-add_task(function* test() {
- for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) {
- let tab = yield* openTabInUserContext(FILE_URI, userContextId);
- gBrowser.removeTab(tab);
- }
- is(gHits, NUM_USER_CONTEXTS, "should get an image request for each user contexts");
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_middleClick.js b/browser/components/contextualidentity/test/browser/browser_middleClick.js
deleted file mode 100644
index f3bed2b53..000000000
--- a/browser/components/contextualidentity/test/browser/browser_middleClick.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-const BASE_ORIGIN = "http://example.com";
-const URI = BASE_ORIGIN +
- "/browser/browser/components/contextualidentity/test/browser/empty_file.html";
-
-add_task(function* () {
- info("Opening a new container tab...");
-
- let tab = gBrowser.addTab(URI, { userContextId: 1 });
- gBrowser.selectedTab = tab;
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
-
- info("Create a HTMLAnchorElement...");
- yield ContentTask.spawn(browser, URI,
- function(URI) {
- let anchor = content.document.createElement("a");
- anchor.setAttribute('id', 'clickMe');
- anchor.setAttribute("href", URI);
- anchor.appendChild(content.document.createTextNode("click me!"));
- content.document.body.appendChild(anchor);
- }
- );
-
- info("Synthesize a mouse click and wait for a new tab...");
- let newTab = yield new Promise((resolve, reject) => {
- gBrowser.tabContainer.addEventListener("TabOpen", function onTabOpen(openEvent) {
- gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen);
- resolve(openEvent.target);
- })
-
- BrowserTestUtils.synthesizeMouseAtCenter("#clickMe", { button: 1 }, browser);
- });
-
- is(newTab.getAttribute("usercontextid"), 1, "Correct UserContextId?");
-
- yield BrowserTestUtils.removeTab(tab);
- yield BrowserTestUtils.removeTab(newTab);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_newtabButton.js b/browser/components/contextualidentity/test/browser/browser_newtabButton.js
deleted file mode 100644
index 228e6f971..000000000
--- a/browser/components/contextualidentity/test/browser/browser_newtabButton.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-// Testing that when the user opens the add tab menu and clicks menu items
-// the correct context id is opened
-
-add_task(function* test() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]});
-
- let newTab = document.getElementById('tabbrowser-tabs');
- let newTabButton = document.getAnonymousElementByAttribute(newTab, "anonid", "tabs-newtab-button");
- ok(newTabButton, "New tab button exists");
- ok(!newTabButton.hidden, "New tab button is visible");
- yield BrowserTestUtils.waitForCondition(() => !!document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup"), "Wait for popup to exist");
- let popup = document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup");
-
- for (let i = 1; i <= 4; i++) {
- let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(newTabButton, {type: "mousedown"});
-
- yield popupShownPromise;
- let contextIdItem = popup.querySelector(`menuitem[data-usercontextid="${i}"]`);
-
- ok(contextIdItem, `User context id ${i} exists`);
-
- let waitForTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
- EventUtils.synthesizeMouseAtCenter(contextIdItem, {});
-
- let tab = yield waitForTabPromise;
-
- is(tab.getAttribute('usercontextid'), i, `New tab has UCI equal ${i}`);
- yield BrowserTestUtils.removeTab(tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js
deleted file mode 100644
index b074b91ac..000000000
--- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js
+++ /dev/null
@@ -1,108 +0,0 @@
-let { classes: Cc, interfaces: Ci } = Components;
-
-let swm = Cc["@mozilla.org/serviceworkers/manager;1"].
- getService(Ci.nsIServiceWorkerManager);
-
-const BASE_ORIGIN = "https://example.com";
-const URI = BASE_ORIGIN +
- "/browser/browser/components/contextualidentity/test/browser/serviceworker.html";
-const NUM_USER_CONTEXTS = 3;
-
-// opens `uri' in a new tab with the provided userContextId and focuses it.
-// returns the newly opened tab
-function openTabInUserContext(uri, userContextId) {
- // open the tab in the correct userContextId
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // select tab and make sure its browser is focused
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- return tab;
-}
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true],
- ["dom.serviceWorkers.enabled", true],
- ["dom.serviceWorkers.openWindow.enabled", true],
- ["dom.ipc.processCount", 1]
- ]}, resolve);
- });
-});
-
-let infos = [];
-
-add_task(function* test() {
- // Open the same URI in multiple user contexts, and make sure we have a
- // separate service worker in each of the contexts
- for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) {
- // Open a tab in given user contexts
- let tab = openTabInUserContext(URI, userContextId);
-
- // wait for tab load
- yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab));
-
- // remove the tab
- gBrowser.removeTab(tab);
- }
-
- if (!allRegistered()) {
- yield promiseAllRegistered();
- }
- ok(true, "all service workers are registered");
-
- // Unregistered all service workers added in this test
- for (let info of infos) {
- yield promiseUnregister(info);
- }
-});
-
-function allRegistered() {
- let results = [];
- let registrations = swm.getAllRegistrations();
- for (let i = 0; i < registrations.length; i++) {
- let info = registrations.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo);
- let principal = info.principal;
- if (principal.originNoSuffix === BASE_ORIGIN) {
- results[principal.userContextId] = true;
- infos[principal.userContextId] = info;
- }
- }
- for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) {
- if (!results[userContextId]) {
- return false;
- }
- }
- return true;
-}
-
-function promiseAllRegistered() {
- return new Promise(function(resolve) {
- let listener = {
- onRegister: function() {
- if (allRegistered()) {
- swm.removeListener(listener);
- resolve();
- }
- }
- }
- swm.addListener(listener);
- });
-}
-
-function promiseUnregister(info) {
- return new Promise(function(resolve) {
- swm.unregister(info.principal, {
- unregisterSucceeded: function(aState) {
- ok(aState, "ServiceWorkerRegistration exists");
- resolve();
- },
- unregisterFailed: function(aState) {
- ok(false, "unregister should succeed");
- }
- }, info.scope);
- });
-}
diff --git a/browser/components/contextualidentity/test/browser/browser_usercontext.js b/browser/components/contextualidentity/test/browser/browser_usercontext.js
deleted file mode 100644
index e0e785d3f..000000000
--- a/browser/components/contextualidentity/test/browser/browser_usercontext.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-const USER_CONTEXTS = [
- "default",
- "personal",
- "work",
-];
-
-const BASE_URI = "http://mochi.test:8888/browser/browser/components/"
- + "contextualidentity/test/browser/file_reflect_cookie_into_title.html";
-
-
-// opens `uri' in a new tab with the provided userContextId and focuses it.
-// returns the newly opened tab
-function openTabInUserContext(uri, userContextId) {
- // open the tab in the correct userContextId
- let tab = gBrowser.addTab(uri, {userContextId});
-
- // select tab and make sure its browser is focused
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- return tab;
-}
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true],
- ["dom.ipc.processCount", 1]
- ]}, resolve);
- });
-});
-
-add_task(function* test() {
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // load the page in 3 different contexts and set a cookie
- // which should only be visible in that context
- let cookie = USER_CONTEXTS[userContextId];
-
- // open our tab in the given user context
- let tab = openTabInUserContext(BASE_URI+"?"+cookie, userContextId);
-
- // wait for tab load
- yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab));
-
- // remove the tab
- gBrowser.removeTab(tab);
- }
-
- {
- // Set a cookie in a different context so we can detect if that affects
- // cross-context properly. If we don't do that, we get an UNEXPECTED-PASS
- // for the localStorage case for the last tab we set.
- let tab = openTabInUserContext(BASE_URI+"?foo", 9999);
- yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab));
- gBrowser.removeTab(tab);
- }
-
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Load the page without setting the cookie this time
- let expectedContext = USER_CONTEXTS[userContextId];
-
- let tab = openTabInUserContext(BASE_URI, userContextId);
-
- // wait for load
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
-
- // get the title
- let title = browser.contentDocument.title.trim().split("|");
-
- // check each item in the title and validate it meets expectatations
- for (let part of title) {
- let [storageMethodName, value] = part.split("=");
- is(value, expectedContext,
- "the title reflects the expected contextual identity of " +
- expectedContext + " for method " + storageMethodName + ": " + value);
- }
-
- gBrowser.removeTab(tab);
- }
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js b/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js
deleted file mode 100644
index 6a8fbc591..000000000
--- a/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js
+++ /dev/null
@@ -1,134 +0,0 @@
-"use strict";
-
-let EventUtils = {};
-Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
-/**
- * Dragging an URL to a tab without userContextId set.
- */
-add_task(function* () {
- let tab = gBrowser.addTab("http://example.com/");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop");
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://test1.example.com/");
-
- // A drop type of "link" onto an existing tab would normally trigger a
- // load in that same tab, but tabbrowser code in _getDragTargetTab treats
- // drops on the outer edges of a tab differently (loading a new tab
- // instead). Make events created by synthesizeDrop have all of their
- // coordinates set to 0 (screenX/screenY), so they're treated as drops
- // on the outer edge of the tab, thus they open new tabs.
- let event = {
- clientX: 0,
- clientY: 0,
- screenX: 0,
- screenY: 0,
- };
- EventUtils.synthesizeDrop(tab, tab, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window, undefined, event);
-
- yield awaitDrop;
-
- let tab2 = yield newTabPromise;
- Assert.ok(!tab2.hasAttribute("usercontextid"), "Tab shouldn't have usercontextid attribute");
-
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
-
- yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () {
- Assert.equal(content.document.documentURI, "http://test1.example.com/");
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 0);
-
- // referrer is empty when urls are dragged to new or existing tabs.
- // If this changes in the future, it would be okay to send the referrer
- // in this case because we are creating a new tab with the default
- // usercontextid as the original tab.
- Assert.equal(content.document.referrer, "", "referrer should be empty");
- });
-
- yield BrowserTestUtils.removeTab(tab);
- yield BrowserTestUtils.removeTab(tab2);
-});
-
-/**
- * When dragging an URL to a new tab, the new tab should have the same
- * userContextId as the original tab.
- */
-add_task(function* () {
- let tab = gBrowser.addTab("http://example.com/", {userContextId: 1});
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop");
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://test1.example.com/");
-
- // A drop type of "link" onto an existing tab would normally trigger a
- // load in that same tab, but tabbrowser code in _getDragTargetTab treats
- // drops on the outer edges of a tab differently (loading a new tab
- // instead). Make events created by synthesizeDrop have all of their
- // coordinates set to 0 (screenX/screenY), so they're treated as drops
- // on the outer edge of the tab, thus they open new tabs.
- let event = {
- clientX: 0,
- clientY: 0,
- screenX: 0,
- screenY: 0,
- };
- EventUtils.synthesizeDrop(tab, tab, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window, undefined, event);
-
- yield awaitDrop;
-
- let tab2 = yield newTabPromise;
- Assert.equal(tab2.getAttribute("usercontextid"), 1);
-
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
-
- yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () {
- Assert.equal(content.document.documentURI, "http://test1.example.com/");
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 1);
-
- // referrer is empty when urls are dragged to new or existing tabs.
- // If this changes in the future, it would be okay to send the referrer
- // in this case because we are creating a new tab with the same
- // usercontextid as the original tab.
- Assert.equal(content.document.referrer, "", "referrer should be empty");
- });
-
- yield BrowserTestUtils.removeTab(tab);
- yield BrowserTestUtils.removeTab(tab2);
-});
-
-/**
- * When dragging a URL from one tab or link on a tab to an existing tab, the
- * existing tab should not change its userContextId.
- * Ex: if you drag a link from tab 1 with userContext 1 to tab 2 with
- * userContext 2, the link will open in tab 2 with userContext 2.
- */
-add_task(function* () {
- let tab = gBrowser.addTab("http://example.com/", {userContextId: 1});
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- let tab2 = gBrowser.addTab("http://example.org/", {userContextId: 2});
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
-
- let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop");
-
- EventUtils.synthesizeDrop(tab, tab2, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window);
-
- yield awaitDrop;
- Assert.equal(tab2.getAttribute("usercontextid"), 2);
-
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
-
- yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () {
- Assert.equal(content.document.documentURI, "http://test1.example.com/");
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 2);
-
- // referrer is empty when urls are dragged to new or existing tabs.
- // If this changes in the future, we should ensure that we are not sending
- // a referrer for this case! When opening links across user contexts, we
- // don't want the referrer to follow the user from one context to another.
- Assert.equal(content.document.referrer, "", "referrer should be empty");
- });
-
- yield BrowserTestUtils.removeTab(tab);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_windowName.js b/browser/components/contextualidentity/test/browser/browser_windowName.js
deleted file mode 100644
index 555c421ce..000000000
--- a/browser/components/contextualidentity/test/browser/browser_windowName.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-const USER_CONTEXTS = [
- "default",
- "personal",
- "work",
-];
-
-const BASE_URI = "http://mochi.test:8888/browser/browser/components/"
- + "contextualidentity/test/browser/empty_file.html";
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true],
- ["browser.link.open_newwindow", 3],
- ]}, resolve);
- });
-});
-
-add_task(function* test() {
- info("Creating first tab...");
- let tab1 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 1});
- let browser1 = gBrowser.getBrowserForTab(tab1);
- yield BrowserTestUtils.browserLoaded(browser1);
- yield ContentTask.spawn(browser1, null, function(opts) {
- content.window.name = 'tab-1';
- });
-
- info("Creating second tab...");
- let tab2 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 2});
- let browser2 = gBrowser.getBrowserForTab(tab2);
- yield BrowserTestUtils.browserLoaded(browser2);
- yield ContentTask.spawn(browser2, null, function(opts) {
- content.window.name = 'tab-2';
- });
-
- // Let's try to open a window from tab1 with a name 'tab-2'.
- info("Opening a window from the first tab...");
- yield ContentTask.spawn(browser1, { url: BASE_URI + '?new' }, function* (opts) {
- yield (new content.window.wrappedJSObject.Promise(resolve => {
- let w = content.window.wrappedJSObject.open(opts.url, 'tab-2');
- w.onload = function() { resolve(); }
- }));
- });
-
- is(browser1.contentTitle, '?old', "Tab1 title must be 'old'");
- is(browser1.contentPrincipal.userContextId, 1, "Tab1 UCI must be 1");
-
- is(browser2.contentTitle, '?old', "Tab2 title must be 'old'");
- is(browser2.contentPrincipal.userContextId, 2, "Tab2 UCI must be 2");
-
- let found = false;
- for (let i = 0; i < gBrowser.tabContainer.childNodes.length; ++i) {
- let tab = gBrowser.tabContainer.childNodes[i];
- let browser = gBrowser.getBrowserForTab(tab);
- if (browser.contentTitle == '?new') {
- is(browser.contentPrincipal.userContextId, 1, "Tab3 UCI must be 1");
- isnot(browser, browser1, "Tab3 is not browser 1");
- isnot(browser, browser2, "Tab3 is not browser 2");
- gBrowser.removeTab(tab);
- found = true;
- break;
- }
- }
-
- ok(found, "We have tab3");
-
- gBrowser.removeTab(tab1);
- gBrowser.removeTab(tab2);
-});
diff --git a/browser/components/contextualidentity/test/browser/browser_windowOpen.js b/browser/components/contextualidentity/test/browser/browser_windowOpen.js
deleted file mode 100644
index 00c6e0aa0..000000000
--- a/browser/components/contextualidentity/test/browser/browser_windowOpen.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-// Here we want to test that a new opened window shows the same UI of the
-// parent one if this has been loaded from a particular container.
-
-const BASE_URI = "http://mochi.test:8888/browser/browser/components/"
- + "contextualidentity/test/browser/empty_file.html";
-
-add_task(function* setup() {
- yield new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true],
- ["browser.link.open_newwindow", 2],
- ]}, resolve);
- });
-});
-
-
-add_task(function* test() {
- info("Creating a tab with UCI = 1...");
- let tab = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
-
- info("Opening a new window from this tab...");
- ContentTask.spawn(browser, BASE_URI, function(url) {
- content.window.newWindow = content.window.open(url, "_blank");
- });
-
- let newWin = yield BrowserTestUtils.waitForNewWindow();
- let newTab = newWin.gBrowser.selectedTab;
-
- yield BrowserTestUtils.browserLoaded(newTab.linkedBrowser);
- is(newTab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
-
- info("Closing the new window and tab...");
- yield BrowserTestUtils.closeWindow(newWin);
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/contextualidentity/test/browser/empty_file.html b/browser/components/contextualidentity/test/browser/empty_file.html
deleted file mode 100644
index c6d11dcd5..000000000
--- a/browser/components/contextualidentity/test/browser/empty_file.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html><body>
-<script>
-document.title = window.location.search;
-</script>
-</body></html>
diff --git a/browser/components/contextualidentity/test/browser/favicon-normal32.png b/browser/components/contextualidentity/test/browser/favicon-normal32.png
deleted file mode 100644
index 5535363c9..000000000
--- a/browser/components/contextualidentity/test/browser/favicon-normal32.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html b/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html
deleted file mode 100644
index b04f3fd5c..000000000
--- a/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<html>
- <head>
- <meta charset="UTF-8">
- <title>title not set</title>
- <script>
- // if we have a query string, use it to set the cookie and localStorage
- if (window.location.search.length > 0) {
- let context_name = window.location.search.substr(1);
- document.cookie = "userContextId=" + context_name;
- localStorage.setItem("userContext", context_name);
- }
-
- // get the cookie
- let [name, val] = document.cookie.split("=");
-
- // set the title to reflect the cookie and local storage values we find
- document.title = "cookie=" + val + "|"
- + "local=" + localStorage.getItem("userContext");
- </script>
- </head>
- <body></body>
-</html>
-
diff --git a/browser/components/contextualidentity/test/browser/file_set_storages.html b/browser/components/contextualidentity/test/browser/file_set_storages.html
deleted file mode 100644
index c6adcbdde..000000000
--- a/browser/components/contextualidentity/test/browser/file_set_storages.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<html>
- <head>
- <meta charset="UTF-8">
- <title>Bug 1238183</title>
- </head>
- <body>
- <script type="application/javascript;version=1.7">
- "use strict";
-
- // if we have a query string, use it to set storages
- if (window.location.search.length > 0) {
- let context_name = window.location.search.substr(1);
- localStorage.setItem("userContext", context_name);
- sessionStorage.setItem("userContext", context_name);
-
- let request = indexedDB.open("idb", 1);
-
- request.onerror = function() {
- throw new Error("error opening db connection");
- };
-
- request.onupgradeneeded = event => {
- let db = event.target.result;
- let store = db.createObjectStore("obj", { keyPath: "id" });
- store.createIndex("userContext", "userContext", { unique: false });
- };
-
- request.onsuccess = event => {
- let db = request.result;
- let transaction = db.transaction(["obj"], "readwrite");
- let store = transaction.objectStore("obj");
- store.add({id: 1, userContext: context_name});
-
- transaction.oncomplete = () => {
- db.close();
- };
- };
- }
- </script>
- </body>
-</html>
diff --git a/browser/components/contextualidentity/test/browser/serviceworker.html b/browser/components/contextualidentity/test/browser/serviceworker.html
deleted file mode 100644
index 11edd001a..000000000
--- a/browser/components/contextualidentity/test/browser/serviceworker.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <script>
- navigator.serviceWorker.register("worker.js");
- </script>
- </head>
- <body>
- This is a test page.
- </body>
-<html>
diff --git a/browser/components/contextualidentity/test/browser/worker.js b/browser/components/contextualidentity/test/browser/worker.js
deleted file mode 100644
index 2aba167d1..000000000
--- a/browser/components/contextualidentity/test/browser/worker.js
+++ /dev/null
@@ -1 +0,0 @@
-// empty worker, always succeed!
diff --git a/browser/components/customizableui/test/.eslintrc.js b/browser/components/customizableui/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/customizableui/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/customizableui/test/browser.ini b/browser/components/customizableui/test/browser.ini
deleted file mode 100644
index 1c1f30498..000000000
--- a/browser/components/customizableui/test/browser.ini
+++ /dev/null
@@ -1,154 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- support/test_967000_charEncoding_page.html
- support/feeds_test_page.html
- support/test-feed.xml
-
-[browser_873501_handle_specials.js]
-[browser_876926_customize_mode_wrapping.js]
-[browser_876944_customize_mode_create_destroy.js]
-[browser_877006_missing_view.js]
-[browser_877178_unregisterArea.js]
-[browser_877447_skip_missing_ids.js]
-[browser_878452_drag_to_panel.js]
-[browser_880164_customization_context_menus.js]
-[browser_880382_drag_wide_widgets_in_panel.js]
-[browser_884402_customize_from_overflow.js]
-skip-if = os == "linux"
-[browser_885052_customize_mode_observers_disabed.js]
-tags = fullscreen
-# Bug 951403 - Disabled on OSX for frequent failures
-skip-if = os == "mac"
-
-[browser_885530_showInPrivateBrowsing.js]
-[browser_886323_buildArea_removable_nodes.js]
-[browser_887438_currentset_shim.js]
-[browser_888817_currentset_updating.js]
-[browser_890140_orphaned_placeholders.js]
-[browser_890262_destroyWidget_after_add_to_panel.js]
-[browser_892955_isWidgetRemovable_for_removed_widgets.js]
-[browser_892956_destroyWidget_defaultPlacements.js]
-[browser_909779_overflow_toolbars_new_window.js]
-skip-if = os == "linux"
-
-[browser_901207_searchbar_in_panel.js]
-[browser_913972_currentset_overflow.js]
-skip-if = os == "linux"
-
-[browser_914138_widget_API_overflowable_toolbar.js]
-skip-if = os == "linux"
-
-[browser_914863_disabled_help_quit_buttons.js]
-[browser_918049_skipintoolbarset_dnd.js]
-[browser_923857_customize_mode_event_wrapping_during_reset.js]
-[browser_927717_customize_drag_empty_toolbar.js]
-
-# Bug 1163231 - Causes failures on Developer Edition on Windows 7.
-# [browser_932928_show_notice_when_palette_empty.js]
-
-[browser_934113_menubar_removable.js]
-# Because this test is about the menubar, it can't be run on mac
-skip-if = os == "mac"
-
-[browser_934951_zoom_in_toolbar.js]
-[browser_938980_navbar_collapsed.js]
-[browser_938995_indefaultstate_nonremovable.js]
-[browser_940013_registerToolbarNode_calls_registerArea.js]
-[browser_940307_panel_click_closure_handling.js]
-[browser_940946_removable_from_navbar_customizemode.js]
-[browser_941083_invalidate_wrapper_cache_createWidget.js]
-[browser_942581_unregisterArea_keeps_placements.js]
-[browser_943683_migration_test.js]
-[browser_944887_destroyWidget_should_destroy_in_palette.js]
-[browser_945739_showInPrivateBrowsing_customize_mode.js]
-[browser_947914_button_addons.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_copy.js]
-subsuite = clipboard
-skip-if = os == "linux" # Intermittent failures on Linux
-[browser_947914_button_cut.js]
-subsuite = clipboard
-skip-if = os == "linux" # Intermittent failures on Linux
-[browser_947914_button_find.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_history.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_newPrivateWindow.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_newWindow.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_paste.js]
-subsuite = clipboard
-skip-if = os == "linux" # Intermittent failures on Linux
-[browser_947914_button_print.js]
-skip-if = os == "linux" # Intermittent failures on Linux
-[browser_947914_button_savePage.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_zoomIn.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_zoomOut.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947914_button_zoomReset.js]
-skip-if = os == "linux" # Intermittent failures
-[browser_947987_removable_default.js]
-[browser_948985_non_removable_defaultArea.js]
-[browser_952963_areaType_getter_no_area.js]
-[browser_956602_remove_special_widget.js]
-[browser_962069_drag_to_overflow_chevron.js]
-[browser_962884_opt_in_disable_hyphens.js]
-[browser_963639_customizing_attribute_non_customizable_toolbar.js]
-[browser_967000_button_charEncoding.js]
-[browser_967000_button_feeds.js]
-[browser_967000_button_sync.js]
-[browser_968447_bookmarks_toolbar_items_in_panel.js]
-skip-if = os == "linux" # Intemittent failures - bug 979207
-[browser_968565_insert_before_hidden_items.js]
-[browser_969427_recreate_destroyed_widget_after_reset.js]
-[browser_969661_character_encoding_navbar_disabled.js]
-[browser_970511_undo_restore_default.js]
-[browser_972267_customizationchange_events.js]
-[browser_973641_button_addon.js]
-[browser_973932_addonbar_currentset.js]
-[browser_975719_customtoolbars_behaviour.js]
-[browser_976792_insertNodeInWindow.js]
-skip-if = os == "linux"
-[browser_978084_dragEnd_after_move.js]
-[browser_980155_add_overflow_toolbar.js]
-[browser_981305_separator_insertion.js]
-[browser_981418-widget-onbeforecreated-handler.js]
-[browser_982656_restore_defaults_builtin_widgets.js]
-[browser_984455_bookmarks_items_reparenting.js]
-skip-if = os == "linux"
-[browser_985815_propagate_setToolbarVisibility.js]
-[browser_987177_destroyWidget_xul.js]
-[browser_987177_xul_wrapper_updating.js]
-[browser_987185_syncButton.js]
-[browser_987492_window_api.js]
-[browser_987640_charEncoding.js]
-[browser_988072_sidebar_events.js]
-[browser_989338_saved_placements_not_resaved.js]
-[browser_989751_subviewbutton_class.js]
-[browser_992747_toggle_noncustomizable_toolbar.js]
-[browser_993322_widget_notoolbar.js]
-[browser_995164_registerArea_during_customize_mode.js]
-[browser_996364_registerArea_different_properties.js]
-[browser_996635_remove_non_widgets.js]
-[browser_1003588_no_specials_in_panel.js]
-[browser_1007336_lwthemes_in_customize_mode.js]
-skip-if = os == "linux" # crashing on Linux due to bug 1271683
-[browser_1008559_anchor_undo_restore.js]
-[browser_1042100_default_placements_update.js]
-[browser_1058573_showToolbarsDropdown.js]
-[browser_1087303_button_fullscreen.js]
-tags = fullscreen
-skip-if = os == "mac"
-[browser_1087303_button_preferences.js]
-[browser_1089591_still_customizable_after_reset.js]
-[browser_1096763_seen_widgets_post_reset.js]
-[browser_1161838_inserted_new_default_buttons.js]
-[browser_bootstrapped_custom_toolbar.js]
-[browser_customizemode_contextmenu_menubuttonstate.js]
-[browser_panel_toggle.js]
-[browser_switch_to_customize_mode.js]
-[browser_check_tooltips_in_navbar.js]
diff --git a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js
deleted file mode 100644
index 22fbb5c0c..000000000
--- a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-function simulateItemDragAndEnd(aToDrag, aTarget) {
- var ds = Components.classes["@mozilla.org/widget/dragservice;1"].
- getService(Components.interfaces.nsIDragService);
-
- ds.startDragSession();
- try {
- var [result, dataTransfer] = EventUtils.synthesizeDragOver(aToDrag.parentNode, aTarget);
- EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, aTarget);
- // Send dragend to move dragging item back to initial place.
- EventUtils.sendDragEvent({ type: "dragend", dataTransfer: dataTransfer },
- aToDrag.parentNode);
- } finally {
- ds.endDragSession(true);
- }
-}
-
-add_task(function* checkNoAddingToPanel() {
- let area = CustomizableUI.AREA_PANEL;
- let previousPlacements = getAreaWidgetIds(area);
- CustomizableUI.addWidgetToArea("separator", area);
- CustomizableUI.addWidgetToArea("spring", area);
- CustomizableUI.addWidgetToArea("spacer", area);
- assertAreaPlacements(area, previousPlacements);
-
- let oldNumberOfItems = previousPlacements.length;
- if (getAreaWidgetIds(area).length != oldNumberOfItems) {
- CustomizableUI.reset();
- }
-});
-
-add_task(function* checkAddingToToolbar() {
- let area = CustomizableUI.AREA_NAVBAR;
- let previousPlacements = getAreaWidgetIds(area);
- CustomizableUI.addWidgetToArea("separator", area);
- CustomizableUI.addWidgetToArea("spring", area);
- CustomizableUI.addWidgetToArea("spacer", area);
- let expectedPlacements = [...previousPlacements].concat([
- /separator/,
- /spring/,
- /spacer/
- ]);
- assertAreaPlacements(area, expectedPlacements);
-
- let newlyAddedElements = getAreaWidgetIds(area).slice(-3);
- while (newlyAddedElements.length) {
- CustomizableUI.removeWidgetFromArea(newlyAddedElements.shift());
- }
-
- assertAreaPlacements(area, previousPlacements);
-
- let oldNumberOfItems = previousPlacements.length;
- if (getAreaWidgetIds(area).length != oldNumberOfItems) {
- CustomizableUI.reset();
- }
-});
-
-
-add_task(function* checkDragging() {
- let startArea = CustomizableUI.AREA_NAVBAR;
- let targetArea = CustomizableUI.AREA_PANEL;
- let startingToolbarPlacements = getAreaWidgetIds(startArea);
- let startingTargetPlacements = getAreaWidgetIds(targetArea);
-
- CustomizableUI.addWidgetToArea("separator", startArea);
- CustomizableUI.addWidgetToArea("spring", startArea);
- CustomizableUI.addWidgetToArea("spacer", startArea);
-
- let placementsWithSpecials = getAreaWidgetIds(startArea);
- let elementsToMove = [];
- for (let id of placementsWithSpecials) {
- if (CustomizableUI.isSpecialWidget(id)) {
- elementsToMove.push(id);
- }
- }
- is(elementsToMove.length, 3, "Should have 3 elements to try and drag.");
-
- yield startCustomizing();
- for (let id of elementsToMove) {
- simulateItemDragAndEnd(document.getElementById(id), PanelUI.contents);
- }
-
- assertAreaPlacements(startArea, placementsWithSpecials);
- assertAreaPlacements(targetArea, startingTargetPlacements);
-
- for (let id of elementsToMove) {
- simulateItemDrag(document.getElementById(id), gCustomizeMode.visiblePalette);
- }
-
- assertAreaPlacements(startArea, startingToolbarPlacements);
- assertAreaPlacements(targetArea, startingTargetPlacements);
-
- ok(!gCustomizeMode.visiblePalette.querySelector("toolbarspring,toolbarseparator,toolbarspacer"),
- "No specials should make it to the palette alive.");
- yield endCustomizing();
-});
-
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- CustomizableUI.reset();
-});
-
diff --git a/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js b/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js
deleted file mode 100644
index db4f88e6d..000000000
--- a/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}";
-const {LightweightThemeManager} = Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", {});
-
-add_task(function* () {
- Services.prefs.clearUserPref("lightweightThemes.usedThemes");
- Services.prefs.clearUserPref("lightweightThemes.recommendedThemes");
- LightweightThemeManager.clearBuiltInThemes();
-
- yield startCustomizing();
-
- let themesButton = document.getElementById("customization-lwtheme-button");
- let popup = document.getElementById("customization-lwtheme-menu");
-
- let popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button");
- yield popupShownPromise;
-
- // close current tab and re-open Customize menu to confirm correct number of Themes
- yield endCustomizing();
- info("Exited customize mode");
- yield startCustomizing();
- info("Started customizing a second time");
- popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button a second time");
- yield popupShownPromise;
-
- let header = document.getElementById("customization-lwtheme-menu-header");
- let recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended");
-
- is(header.nextSibling.nextSibling, recommendedHeader,
- "There should only be one theme (default) in the 'My Themes' section by default");
- is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "That theme should be the default theme");
-
- let firstLWTheme = recommendedHeader.nextSibling;
- let firstLWThemeId = firstLWTheme.theme.id;
- let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
- firstLWTheme.doCommand();
- info("Clicked on first theme");
- yield themeChangedPromise;
-
- popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button");
- yield popupShownPromise;
-
- is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "The first theme should be the Default theme");
- let installedThemeId = header.nextSibling.nextSibling.theme.id;
- ok(installedThemeId.startsWith(firstLWThemeId),
- "The second theme in the 'My Themes' section should be the newly installed theme: " +
- "Installed theme id: " + installedThemeId + "; First theme ID: " + firstLWThemeId);
- is(header.nextSibling.nextSibling.nextSibling, recommendedHeader,
- "There should be two themes in the 'My Themes' section");
-
- let defaultTheme = header.nextSibling;
- defaultTheme.doCommand();
- is(Services.prefs.getCharPref("lightweightThemes.selectedThemeID"), "", "No lwtheme should be selected");
-
- // ensure current theme isn't set to "Default"
- popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button a second time");
- yield popupShownPromise;
-
- firstLWTheme = recommendedHeader.nextSibling;
- themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
- firstLWTheme.doCommand();
- info("Clicked on first theme again");
- yield themeChangedPromise;
-
- // check that "Restore Defaults" button resets theme
- yield gCustomizeMode.reset();
- is(LightweightThemeManager.currentTheme, null, "Current theme reset to default");
-
- yield endCustomizing();
- Services.prefs.setCharPref("lightweightThemes.usedThemes", "[]");
- Services.prefs.setCharPref("lightweightThemes.recommendedThemes", "[]");
- info("Removed all recommended themes");
- yield startCustomizing();
- popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button a second time");
- yield popupShownPromise;
- header = document.getElementById("customization-lwtheme-menu-header");
- is(header.hidden, false, "Header should never be hidden");
- is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "The first theme should be the Default theme");
- is(header.nextSibling.hidden, false, "The default theme should never be hidden");
- recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended");
- is(header.nextSibling.nextSibling, recommendedHeader,
- "There should only be one theme (default) in the 'My Themes' section by default");
- let footer = document.getElementById("customization-lwtheme-menu-footer");
- is(recommendedHeader.nextSibling.id, footer.id, "There should be no recommended themes in the menu");
- is(recommendedHeader.hidden, true, "The recommendedHeader should be hidden since there are no recommended themes");
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
-
- Services.prefs.clearUserPref("lightweightThemes.usedThemes");
- Services.prefs.clearUserPref("lightweightThemes.recommendedThemes");
-});
diff --git a/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js b/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js
deleted file mode 100644
index 56657914b..000000000
--- a/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const kAnchorAttribute = "cui-anchorid";
-
-/**
- * Check that anchor gets set correctly when moving an item from the panel to the toolbar
- * using 'undo'
- */
-add_task(function*() {
- yield startCustomizing();
- let button = document.getElementById("history-panelmenu");
- is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button",
- "Button (" + button.id + ") starts out with correct anchor");
-
- let navbar = document.getElementById("nav-bar").customizationTarget;
- simulateItemDrag(button, navbar);
- is(CustomizableUI.getPlacementOfWidget(button.id).area, "nav-bar",
- "Button (" + button.id + ") ends up in nav-bar");
-
- ok(!button.hasAttribute(kAnchorAttribute),
- "Button (" + button.id + ") has no anchor in toolbar");
-
- let resetButton = document.getElementById("customization-reset-button");
- ok(!resetButton.hasAttribute("disabled"), "Should be able to reset now.");
- yield gCustomizeMode.reset();
-
- is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button",
- "Button (" + button.id + ") has anchor again");
-
- let undoButton = document.getElementById("customization-undo-reset-button");
- ok(!undoButton.hasAttribute("disabled"), "Should be able to undo now.");
- yield gCustomizeMode.undoReset();
-
- ok(!button.hasAttribute(kAnchorAttribute),
- "Button (" + button.id + ") once again has no anchor in toolbar");
-
- yield gCustomizeMode.reset();
-
- yield endCustomizing();
-});
-
-
-/**
- * Check that anchor gets set correctly when moving an item from the panel to the toolbar
- * using 'reset'
- */
-add_task(function*() {
- yield startCustomizing();
- let button = document.getElementById("bookmarks-menu-button");
- ok(!button.hasAttribute(kAnchorAttribute),
- "Button (" + button.id + ") has no anchor in toolbar");
-
- let panel = document.getElementById("PanelUI-contents");
- simulateItemDrag(button, panel);
- is(CustomizableUI.getPlacementOfWidget(button.id).area, "PanelUI-contents",
- "Button (" + button.id + ") ends up in panel");
- is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button",
- "Button (" + button.id + ") has correct anchor in the panel");
-
- let resetButton = document.getElementById("customization-reset-button");
- ok(!resetButton.hasAttribute("disabled"), "Should be able to reset now.");
- yield gCustomizeMode.reset();
-
- ok(!button.hasAttribute(kAnchorAttribute),
- "Button (" + button.id + ") once again has no anchor in toolbar");
-
- yield endCustomizing();
-});
diff --git a/browser/components/customizableui/test/browser_1042100_default_placements_update.js b/browser/components/customizableui/test/browser_1042100_default_placements_update.js
deleted file mode 100644
index 129dbd754..000000000
--- a/browser/components/customizableui/test/browser_1042100_default_placements_update.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// NB: This uses some ugly hacks to get into the CUI module from elsewhere...
-// don't try this at home, kids.
-function test() {
- // Customize something to make sure stuff changed:
- CustomizableUI.addWidgetToArea("feed-button", CustomizableUI.AREA_NAVBAR);
-
- // Check what version we're on:
- let CustomizableUIBSPass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
-
- is(CustomizableUIBSPass.gFuturePlacements.size, 0,
- "All future placements should be dealt with by now.");
-
- let {CustomizableUIInternal, gFuturePlacements, gPalette} = CustomizableUIBSPass;
- CustomizableUIInternal._introduceNewBuiltinWidgets();
- is(gFuturePlacements.size, 0,
- "No change to future placements initially.");
-
- let currentVersion = CustomizableUIBSPass.kVersion;
-
-
- // Add our widget to the defaults:
- let testWidgetNew = {
- id: "test-messing-with-default-placements-new",
- label: "Test messing with default placements - should be inserted",
- defaultArea: CustomizableUI.AREA_NAVBAR,
- introducedInVersion: currentVersion + 1,
- };
-
- let normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetNew,
- CustomizableUI.SOURCE_BUILTIN);
- ok(normalizedWidget, "Widget should be normalizable");
- if (!normalizedWidget) {
- return;
- }
- CustomizableUIBSPass.gPalette.set(testWidgetNew.id, normalizedWidget);
-
- let testWidgetOld = {
- id: "test-messing-with-default-placements-old",
- label: "Test messing with default placements - should NOT be inserted",
- defaultArea: CustomizableUI.AREA_NAVBAR,
- introducedInVersion: currentVersion,
- };
-
- normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetOld,
- CustomizableUI.SOURCE_BUILTIN);
- ok(normalizedWidget, "Widget should be normalizable");
- if (!normalizedWidget) {
- return;
- }
- CustomizableUIBSPass.gPalette.set(testWidgetOld.id, normalizedWidget);
-
-
- // Now increase the version in the module:
- CustomizableUIBSPass.kVersion++;
-
- let hadSavedState = !!CustomizableUIBSPass.gSavedState
- if (!hadSavedState) {
- CustomizableUIBSPass.gSavedState = {currentVersion: CustomizableUIBSPass.kVersion - 1};
- }
-
- // Then call the re-init routine so we re-add the builtin widgets
- CustomizableUIInternal._introduceNewBuiltinWidgets();
- is(gFuturePlacements.size, 1,
- "Should have 1 more future placement");
- let haveNavbarPlacements = gFuturePlacements.has(CustomizableUI.AREA_NAVBAR);
- ok(haveNavbarPlacements, "Should have placements for nav-bar");
- if (haveNavbarPlacements) {
- let placements = [...gFuturePlacements.get(CustomizableUI.AREA_NAVBAR)];
-
- // Ignore widgets that are placed using the pref facility and not the
- // versioned facility. They're independent of kVersion and the saved
- // state's current version, so they may be present in the placements.
- for (let i = 0; i < placements.length; ) {
- if (placements[i] == testWidgetNew.id) {
- i++;
- continue;
- }
- let pref = "browser.toolbarbuttons.introduced." + placements[i];
- let introduced = false;
- try {
- introduced = Services.prefs.getBoolPref(pref);
- } catch (ex) {}
- if (!introduced) {
- i++;
- continue;
- }
- placements.splice(i, 1);
- }
-
- is(placements.length, 1, "Should have 1 newly placed widget in nav-bar");
- is(placements[0], testWidgetNew.id, "Should have our test widget to be placed in nav-bar");
- }
-
- gFuturePlacements.delete(CustomizableUI.AREA_NAVBAR);
- CustomizableUIBSPass.kVersion--;
- gPalette.delete(testWidgetNew.id);
- gPalette.delete(testWidgetOld.id);
- if (!hadSavedState) {
- CustomizableUIBSPass.gSavedState = null;
- }
-}
-
diff --git a/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js b/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js
deleted file mode 100644
index 42a032ff8..000000000
--- a/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check that toggleable toolbars dropdown in always shown");
-
- info("Remove all possible custom toolbars");
- yield removeCustomToolbars();
-
- info("Enter customization mode");
- yield startCustomizing();
-
- let toolbarsToggle = document.getElementById("customization-toolbar-visibility-button");
- ok(toolbarsToggle, "The toolbars toggle dropdown exists");
- ok(!toolbarsToggle.hasAttribute("hidden"),
- "The toolbars toggle dropdown is displayed");
-});
-
-add_task(function* asyncCleanup() {
- info("Exit customization mode");
- yield endCustomizing();
-});
diff --git a/browser/components/customizableui/test/browser_1087303_button_fullscreen.js b/browser/components/customizableui/test/browser_1087303_button_fullscreen.js
deleted file mode 100644
index c6b87d6ab..000000000
--- a/browser/components/customizableui/test/browser_1087303_button_fullscreen.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check fullscreen button existence and functionality");
-
- yield PanelUI.show();
-
- let fullscreenButton = document.getElementById("fullscreen-button");
- ok(fullscreenButton, "Fullscreen button appears in Panel Menu");
-
- let fullscreenPromise = promiseFullscreenChange();
- fullscreenButton.click();
- yield fullscreenPromise;
-
- ok(window.fullScreen, "Fullscreen mode was opened");
-
- // exit full screen mode
- fullscreenPromise = promiseFullscreenChange();
- window.fullScreen = !window.fullScreen;
- yield fullscreenPromise;
-
- ok(!window.fullScreen, "Successfully exited fullscreen");
-});
-
-function promiseFullscreenChange() {
- let deferred = Promise.defer();
- info("Wait for fullscreen change");
-
- let timeoutId = setTimeout(() => {
- window.removeEventListener("fullscreen", onFullscreenChange, true);
- deferred.reject("Fullscreen change did not happen within " + 20000 + "ms");
- }, 20000);
-
- function onFullscreenChange(event) {
- clearTimeout(timeoutId);
- window.removeEventListener("fullscreen", onFullscreenChange, true);
- info("Fullscreen event received");
- deferred.resolve();
- }
- window.addEventListener("fullscreen", onFullscreenChange, true);
- return deferred.promise;
-}
diff --git a/browser/components/customizableui/test/browser_1087303_button_preferences.js b/browser/components/customizableui/test/browser_1087303_button_preferences.js
deleted file mode 100644
index b1fdb85b6..000000000
--- a/browser/components/customizableui/test/browser_1087303_button_preferences.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var newTab = null;
-
-add_task(function*() {
- info("Check preferences button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let preferencesButton = document.getElementById("preferences-button");
- ok(preferencesButton, "Preferences button exists in Panel Menu");
- preferencesButton.click();
-
- newTab = gBrowser.selectedTab;
- yield waitForPageLoad(newTab);
-
- let openedPage = gBrowser.currentURI.spec;
- is(openedPage, "about:preferences", "Preferences page was opened");
-});
-
-add_task(function asyncCleanup() {
- if (gBrowser.tabs.length == 1)
- gBrowser.addTab("about:blank");
-
- gBrowser.removeTab(gBrowser.selectedTab);
- info("Tabs were restored");
-});
-
-function waitForPageLoad(aTab) {
- let deferred = Promise.defer();
-
- let timeoutId = setTimeout(() => {
- aTab.linkedBrowser.removeEventListener("load", onTabLoad, true);
- deferred.reject("Page didn't load within " + 20000 + "ms");
- }, 20000);
-
- function onTabLoad(event) {
- clearTimeout(timeoutId);
- aTab.linkedBrowser.removeEventListener("load", onTabLoad, true);
- info("Tab event received: " + "load");
- deferred.resolve();
- }
- aTab.linkedBrowser.addEventListener("load", onTabLoad, true, true);
- return deferred.promise;
-}
diff --git a/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js b/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js
deleted file mode 100644
index 1f502e8e2..000000000
--- a/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js
+++ /dev/null
@@ -1,24 +0,0 @@
-"use strict";
-
-// Dragging the elements again after a reset should work
-add_task(function* () {
- yield startCustomizing();
- let historyButton = document.getElementById("wrapper-history-panelmenu");
- let devButton = document.getElementById("wrapper-developer-button");
-
- ok(historyButton && devButton, "Draggable elements should exist");
- simulateItemDrag(historyButton, devButton);
- yield gCustomizeMode.reset();
- ok(CustomizableUI.inDefaultState, "Should be back in default state");
-
- historyButton = document.getElementById("wrapper-history-panelmenu");
- devButton = document.getElementById("wrapper-developer-button");
- ok(historyButton && devButton, "Draggable elements should exist");
- simulateItemDrag(historyButton, devButton);
-
- yield endCustomizing();
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js b/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js
deleted file mode 100644
index b5a325afb..000000000
--- a/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js
+++ /dev/null
@@ -1,31 +0,0 @@
-"use strict";
-
-const BUTTONID = "test-seenwidget-post-reset";
-
-add_task(function*() {
- CustomizableUI.createWidget({
- id: BUTTONID,
- label: "Test widget seen post reset",
- defaultArea: CustomizableUI.AREA_NAVBAR
- });
-
- const kPrefCustomizationState = "browser.uiCustomization.state";
- let bsPass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
- ok(bsPass.gSeenWidgets.has(BUTTONID), "Widget should be seen after createWidget is called.");
- CustomizableUI.reset();
- ok(bsPass.gSeenWidgets.has(BUTTONID), "Widget should still be seen after reset.");
- ok(!Services.prefs.prefHasUserValue(kPrefCustomizationState), "Pref shouldn't be set right now, because that'd break undo.");
- CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR);
- gCustomizeMode.removeFromArea(document.getElementById(BUTTONID));
- let hasUserValue = Services.prefs.prefHasUserValue(kPrefCustomizationState);
- ok(hasUserValue, "Pref should be set right now.");
- if (hasUserValue) {
- let seenArray = JSON.parse(Services.prefs.getCharPref(kPrefCustomizationState)).seen;
- isnot(seenArray.indexOf(BUTTONID), -1, "Widget should be in saved 'seen' list.");
- }
-});
-
-registerCleanupFunction(function() {
- CustomizableUI.destroyWidget(BUTTONID);
- CustomizableUI.reset();
-});
diff --git a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js b/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
deleted file mode 100644
index 42768debf..000000000
--- a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
+++ /dev/null
@@ -1,78 +0,0 @@
-"use strict";
-
-// NB: This uses some ugly hacks to get into the CUI module from elsewhere...
-// don't try this at home, kids.
-function test() {
- // Customize something to make sure stuff changed:
- CustomizableUI.addWidgetToArea("feed-button", CustomizableUI.AREA_NAVBAR);
-
- let CustomizableUIBSPass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
-
- is(CustomizableUIBSPass.gFuturePlacements.size, 0,
- "All future placements should be dealt with by now.");
-
- let {CustomizableUIInternal, gFuturePlacements, gPalette} = CustomizableUIBSPass;
-
- // Force us to have a saved state:
- CustomizableUIInternal.saveState();
- CustomizableUIInternal.loadSavedState();
-
- CustomizableUIInternal._introduceNewBuiltinWidgets();
- is(gFuturePlacements.size, 0,
- "No change to future placements initially.");
-
- // Add our widget to the defaults:
- let testWidgetNew = {
- id: "test-messing-with-default-placements-new-pref",
- label: "Test messing with default placements - pref-based",
- defaultArea: CustomizableUI.AREA_NAVBAR,
- introducedInVersion: "pref",
- };
-
- let normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetNew,
- CustomizableUI.SOURCE_BUILTIN);
- ok(normalizedWidget, "Widget should be normalizable");
- if (!normalizedWidget) {
- return;
- }
- CustomizableUIBSPass.gPalette.set(testWidgetNew.id, normalizedWidget);
-
- // Now adjust default placements for area:
- let navbarArea = CustomizableUIBSPass.gAreas.get(CustomizableUI.AREA_NAVBAR);
- let navbarPlacements = navbarArea.get("defaultPlacements");
- navbarPlacements.splice(navbarPlacements.indexOf("bookmarks-menu-button") + 1, 0, testWidgetNew.id);
-
- let savedPlacements = CustomizableUIBSPass.gSavedState.placements[CustomizableUI.AREA_NAVBAR];
- // Then call the re-init routine so we re-add the builtin widgets
- CustomizableUIInternal._introduceNewBuiltinWidgets();
- is(gFuturePlacements.size, 1,
- "Should have 1 more future placement");
- let futureNavbarPlacements = gFuturePlacements.get(CustomizableUI.AREA_NAVBAR);
- ok(futureNavbarPlacements, "Should have placements for nav-bar");
- if (futureNavbarPlacements) {
- ok(futureNavbarPlacements.has(testWidgetNew.id), "widget should be in future placements");
- }
- CustomizableUIInternal._placeNewDefaultWidgetsInArea(CustomizableUI.AREA_NAVBAR);
-
- let indexInSavedPlacements = savedPlacements.indexOf(testWidgetNew.id);
- info("Saved placements: " + savedPlacements.join(', '));
- isnot(indexInSavedPlacements, -1, "Widget should have been inserted");
- is(indexInSavedPlacements, savedPlacements.indexOf("bookmarks-menu-button") + 1,
- "Widget should be in the right place.");
-
- if (futureNavbarPlacements) {
- ok(!futureNavbarPlacements.has(testWidgetNew.id), "widget should be out of future placements");
- }
-
- if (indexInSavedPlacements != -1) {
- savedPlacements.splice(indexInSavedPlacements, 1);
- }
-
- gFuturePlacements.delete(CustomizableUI.AREA_NAVBAR);
- let indexInDefaultPlacements = navbarPlacements.indexOf(testWidgetNew.id);
- if (indexInDefaultPlacements != -1) {
- navbarPlacements.splice(indexInDefaultPlacements, 1);
- }
- gPalette.delete(testWidgetNew.id);
- CustomizableUI.reset();
-}
diff --git a/browser/components/customizableui/test/browser_873501_handle_specials.js b/browser/components/customizableui/test/browser_873501_handle_specials.js
deleted file mode 100644
index b07c8e0d7..000000000
--- a/browser/components/customizableui/test/browser_873501_handle_specials.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarName = "test-specials-toolbar";
-
-registerCleanupFunction(removeCustomToolbars);
-
-// Add a toolbar with two springs and the downloads button.
-add_task(function* addToolbarWith2SpringsAndDownloadsButton() {
- // Create the toolbar with a single spring:
- createToolbarWithPlacements(kToolbarName, ["spring"]);
- ok(document.getElementById(kToolbarName), "Toolbar should be created.");
-
- // Check it's there with a generated ID:
- assertAreaPlacements(kToolbarName, [/customizableui-special-spring\d+/]);
- let [springId] = getAreaWidgetIds(kToolbarName);
-
- // Add a second spring, check if that's there and doesn't share IDs
- CustomizableUI.addWidgetToArea("spring", kToolbarName);
- assertAreaPlacements(kToolbarName, [springId,
- /customizableui-special-spring\d+/]);
- let [, spring2Id] = getAreaWidgetIds(kToolbarName);
-
- isnot(springId, spring2Id, "Springs shouldn't have identical IDs.");
-
- // Try moving the downloads button to this new toolbar, between the two springs:
- CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1);
- assertAreaPlacements(kToolbarName, [springId, "downloads-button", spring2Id]);
- yield removeCustomToolbars();
-});
-
-// Add separators around the downloads button.
-add_task(function* addSeparatorsAroundDownloadsButton() {
- createToolbarWithPlacements(kToolbarName, ["separator"]);
- ok(document.getElementById(kToolbarName), "Toolbar should be created.");
-
- // Check it's there with a generated ID:
- assertAreaPlacements(kToolbarName, [/customizableui-special-separator\d+/]);
- let [separatorId] = getAreaWidgetIds(kToolbarName);
-
- CustomizableUI.addWidgetToArea("separator", kToolbarName);
- assertAreaPlacements(kToolbarName, [separatorId,
- /customizableui-special-separator\d+/]);
- let [, separator2Id] = getAreaWidgetIds(kToolbarName);
-
- isnot(separatorId, separator2Id, "Separator ids shouldn't be equal.");
-
- CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1);
- assertAreaPlacements(kToolbarName, [separatorId, "downloads-button", separator2Id]);
- yield removeCustomToolbars();
-});
-
-// Add spacers around the downloads button.
-add_task(function* addSpacersAroundDownloadsButton() {
- createToolbarWithPlacements(kToolbarName, ["spacer"]);
- ok(document.getElementById(kToolbarName), "Toolbar should be created.");
-
- // Check it's there with a generated ID:
- assertAreaPlacements(kToolbarName, [/customizableui-special-spacer\d+/]);
- let [spacerId] = getAreaWidgetIds(kToolbarName);
-
- CustomizableUI.addWidgetToArea("spacer", kToolbarName);
- assertAreaPlacements(kToolbarName, [spacerId,
- /customizableui-special-spacer\d+/]);
- let [, spacer2Id] = getAreaWidgetIds(kToolbarName);
-
- isnot(spacerId, spacer2Id, "Spacer ids shouldn't be equal.");
-
- CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1);
- assertAreaPlacements(kToolbarName, [spacerId, "downloads-button", spacer2Id]);
- yield removeCustomToolbars();
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js b/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js
deleted file mode 100644
index a3204c271..000000000
--- a/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js
+++ /dev/null
@@ -1,185 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kXULWidgetId = "a-test-button"; // we'll create a button with this ID.
-const kAPIWidgetId = "feed-button";
-const kPanel = CustomizableUI.AREA_PANEL;
-const kToolbar = CustomizableUI.AREA_NAVBAR;
-const kVisiblePalette = "customization-palette";
-const kPlaceholderClass = "panel-customization-placeholder";
-
-function checkWrapper(id) {
- is(document.querySelectorAll("#wrapper-" + id).length, 1, "There should be exactly 1 wrapper for " + id + " in the customizing window.");
-}
-
-var move = {
- "drag": function(id, target) {
- let targetNode = document.getElementById(target);
- if (targetNode.customizationTarget) {
- targetNode = targetNode.customizationTarget;
- }
- simulateItemDrag(document.getElementById(id), targetNode);
- },
- "dragToItem": function(id, target) {
- let targetNode = document.getElementById(target);
- if (targetNode.customizationTarget) {
- targetNode = targetNode.customizationTarget;
- }
- let items = targetNode.querySelectorAll("toolbarpaletteitem:not(." + kPlaceholderClass + ")");
- if (target == kPanel) {
- targetNode = items[items.length - 1];
- } else {
- targetNode = items[0];
- }
- simulateItemDrag(document.getElementById(id), targetNode);
- },
- "API": function(id, target) {
- if (target == kVisiblePalette) {
- return CustomizableUI.removeWidgetFromArea(id);
- }
- return CustomizableUI.addWidgetToArea(id, target, null);
- }
-};
-
-function isLast(containerId, defaultPlacements, id) {
- assertAreaPlacements(containerId, defaultPlacements.concat([id]));
- is(document.getElementById(containerId).customizationTarget.lastChild.firstChild.id, id,
- "Widget " + id + " should be in " + containerId + " in customizing window.");
- is(otherWin.document.getElementById(containerId).customizationTarget.lastChild.id, id,
- "Widget " + id + " should be in " + containerId + " in other window.");
-}
-
-function getLastVisibleNodeInToolbar(containerId, win=window) {
- let container = win.document.getElementById(containerId).customizationTarget;
- let rv = container.lastChild;
- while (rv && (rv.getAttribute('hidden') == 'true' || (rv.firstChild && rv.firstChild.getAttribute('hidden') == 'true'))) {
- rv = rv.previousSibling;
- }
- return rv;
-}
-
-function isLastVisibleInToolbar(containerId, defaultPlacements, id) {
- let newPlacements;
- for (let i = defaultPlacements.length - 1; i >= 0; i--) {
- let el = document.getElementById(defaultPlacements[i]);
- if (el && el.getAttribute('hidden') != 'true') {
- newPlacements = [...defaultPlacements];
- newPlacements.splice(i + 1, 0, id);
- break;
- }
- }
- if (!newPlacements) {
- assertAreaPlacements(containerId, defaultPlacements.concat([id]));
- } else {
- assertAreaPlacements(containerId, newPlacements);
- }
- is(getLastVisibleNodeInToolbar(containerId).firstChild.id, id,
- "Widget " + id + " should be in " + containerId + " in customizing window.");
- is(getLastVisibleNodeInToolbar(containerId, otherWin).id, id,
- "Widget " + id + " should be in " + containerId + " in other window.");
-}
-
-function isFirst(containerId, defaultPlacements, id) {
- assertAreaPlacements(containerId, [id].concat(defaultPlacements));
- is(document.getElementById(containerId).customizationTarget.firstChild.firstChild.id, id,
- "Widget " + id + " should be in " + containerId + " in customizing window.");
- is(otherWin.document.getElementById(containerId).customizationTarget.firstChild.id, id,
- "Widget " + id + " should be in " + containerId + " in other window.");
-}
-
-function checkToolbar(id, method) {
- // Place at start of the toolbar:
- let toolbarPlacements = getAreaWidgetIds(kToolbar);
- move[method](id, kToolbar);
- if (method == "dragToItem") {
- isFirst(kToolbar, toolbarPlacements, id);
- } else if (method == "drag") {
- isLastVisibleInToolbar(kToolbar, toolbarPlacements, id);
- } else {
- isLast(kToolbar, toolbarPlacements, id);
- }
- checkWrapper(id);
-}
-
-function checkPanel(id, method) {
- let panelPlacements = getAreaWidgetIds(kPanel);
- move[method](id, kPanel);
- let children = document.getElementById(kPanel).querySelectorAll("toolbarpaletteitem:not(." + kPlaceholderClass + ")");
- let otherChildren = otherWin.document.getElementById(kPanel).children;
- let newPlacements = panelPlacements.concat([id]);
- // Relative position of the new item from the end:
- let position = -1;
- // For the drag to item case, we drag to the last item, making the dragged item the
- // penultimate item. We can't well use the first item because the panel has complicated
- // rules about rearranging wide items (which, by default, the first two items are).
- if (method == "dragToItem") {
- newPlacements.pop();
- newPlacements.splice(panelPlacements.length - 1, 0, id);
- position = -2;
- }
- assertAreaPlacements(kPanel, newPlacements);
- is(children[children.length + position].firstChild.id, id,
- "Widget " + id + " should be in " + kPanel + " in customizing window.");
- is(otherChildren[otherChildren.length + position].id, id,
- "Widget " + id + " should be in " + kPanel + " in other window.");
- checkWrapper(id);
-}
-
-function checkPalette(id, method) {
- // Move back to palette:
- move[method](id, kVisiblePalette);
- ok(CustomizableUI.inDefaultState, "Should end in default state");
- let visibleChildren = gCustomizeMode.visiblePalette.children;
- let expectedChild = method == "dragToItem" ? visibleChildren[0] : visibleChildren[visibleChildren.length - 1];
- is(expectedChild.firstChild.id, id, "Widget " + id + " was moved using " + method + " and should now be wrapped in palette in customizing window.");
- if (id == kXULWidgetId) {
- ok(otherWin.gNavToolbox.palette.querySelector("#" + id), "Widget " + id + " should be in invisible palette in other window.");
- }
- checkWrapper(id);
-}
-
-// This test needs a XUL button that's in the palette by default. No such
-// button currently exists, so we create a simple one.
-function createXULButtonForWindow(win) {
- createDummyXULButton(kXULWidgetId, "test-button", win);
-}
-
-function removeXULButtonForWindow(win) {
- win.gNavToolbox.palette.querySelector(`#${kXULWidgetId}`).remove();
-}
-
-var otherWin;
-
-// Moving widgets in two windows, one with customize mode and one without, should work.
-add_task(function* MoveWidgetsInTwoWindows() {
- yield startCustomizing();
- otherWin = yield openAndLoadWindow(null, true);
- yield otherWin.PanelUI.ensureReady();
- // Create the XUL button to use in the test in both windows.
- createXULButtonForWindow(window);
- createXULButtonForWindow(otherWin);
- ok(CustomizableUI.inDefaultState, "Should start in default state");
-
- for (let widgetId of [kXULWidgetId, kAPIWidgetId]) {
- for (let method of ["API", "drag", "dragToItem"]) {
- info("Moving widget " + widgetId + " using " + method);
- checkToolbar(widgetId, method);
- checkPanel(widgetId, method);
- checkPalette(widgetId, method);
- checkPanel(widgetId, method);
- checkToolbar(widgetId, method);
- checkPalette(widgetId, method);
- }
- }
- yield promiseWindowClosed(otherWin);
- otherWin = null;
- yield endCustomizing();
- removeXULButtonForWindow(window);
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js b/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js
deleted file mode 100644
index ec454dc8d..000000000
--- a/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kTestWidget1 = "test-customize-mode-create-destroy1";
-const kTestWidget2 = "test-customize-mode-create-destroy2";
-
-// Creating and destroying a widget should correctly wrap/unwrap stuff
-add_task(function* testWrapUnwrap() {
- yield startCustomizing();
- CustomizableUI.createWidget({id: kTestWidget1, label: 'Pretty label', tooltiptext: 'Pretty tooltip'});
- let elem = document.getElementById(kTestWidget1);
- let wrapper = document.getElementById("wrapper-" + kTestWidget1);
- ok(elem, "There should be an item");
- ok(wrapper, "There should be a wrapper");
- is(wrapper.firstChild.id, kTestWidget1, "Wrapper should have test widget");
- is(wrapper.parentNode.id, "customization-palette", "Wrapper should be in palette");
- CustomizableUI.destroyWidget(kTestWidget1);
- wrapper = document.getElementById("wrapper-" + kTestWidget1);
- ok(!wrapper, "There should be a wrapper");
- let item = document.getElementById(kTestWidget1);
- ok(!item, "There should no longer be an item");
-});
-
-// Creating and destroying a widget should correctly deal with panel placeholders
-add_task(function* testPanelPlaceholders() {
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- // The value of expectedPlaceholders depends on the default palette layout.
- // Bug 1229236 is for these tests to be smarter so the test doesn't need to
- // change when the default placements change.
- let expectedPlaceholders = 1 + (isInDevEdition() ? 1 : 0);
- is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct.");
- CustomizableUI.createWidget({id: kTestWidget2, label: 'Pretty label', tooltiptext: 'Pretty tooltip', defaultArea: CustomizableUI.AREA_PANEL});
- let elem = document.getElementById(kTestWidget2);
- let wrapper = document.getElementById("wrapper-" + kTestWidget2);
- ok(elem, "There should be an item");
- ok(wrapper, "There should be a wrapper");
- is(wrapper.firstChild.id, kTestWidget2, "Wrapper should have test widget");
- is(wrapper.parentNode, panel, "Wrapper should be in panel");
- expectedPlaceholders = isInDevEdition() ? 1 : 3;
- is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct.");
- CustomizableUI.destroyWidget(kTestWidget2);
- wrapper = document.getElementById("wrapper-" + kTestWidget2);
- ok(!wrapper, "There should be a wrapper");
- let item = document.getElementById(kTestWidget2);
- ok(!item, "There should no longer be an item");
- yield endCustomizing();
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- try {
- CustomizableUI.destroyWidget(kTestWidget1);
- } catch (ex) {}
- try {
- CustomizableUI.destroyWidget(kTestWidget2);
- } catch (ex) {}
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_877006_missing_view.js b/browser/components/customizableui/test/browser_877006_missing_view.js
deleted file mode 100644
index a1495c1fe..000000000
--- a/browser/components/customizableui/test/browser_877006_missing_view.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Should be able to add broken view widget
-add_task(function testAddbrokenViewWidget() {
- const kWidgetId = 'test-877006-broken-widget';
- let widgetSpec = {
- id: kWidgetId,
- type: 'view',
- viewId: 'idontexist',
- /* Empty handler so we try to attach it maybe? */
- onViewShowing: function() {
- }
- };
-
- let noError = true;
- try {
- CustomizableUI.createWidget(widgetSpec);
- CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Should not throw an exception trying to add a broken view widget.");
-
- noError = true;
- try {
- CustomizableUI.destroyWidget(kWidgetId);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Should not throw an exception trying to remove the broken view widget.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_877178_unregisterArea.js b/browser/components/customizableui/test/browser_877178_unregisterArea.js
deleted file mode 100644
index 28037787b..000000000
--- a/browser/components/customizableui/test/browser_877178_unregisterArea.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-registerCleanupFunction(removeCustomToolbars);
-
-// Sanity checks
-add_task(function sanityChecks() {
- SimpleTest.doesThrow(() => CustomizableUI.registerArea("@foo"),
- "Registering areas with an invalid ID should throw.");
-
- SimpleTest.doesThrow(() => CustomizableUI.registerArea([]),
- "Registering areas with an invalid ID should throw.");
-
- SimpleTest.doesThrow(() => CustomizableUI.unregisterArea("@foo"),
- "Unregistering areas with an invalid ID should throw.");
-
- SimpleTest.doesThrow(() => CustomizableUI.unregisterArea([]),
- "Unregistering areas with an invalid ID should throw.");
-
- SimpleTest.doesThrow(() => CustomizableUI.unregisterArea("unknown"),
- "Unregistering an area that's not registered should throw.");
-});
-
-// Check areas are loaded with their default placements.
-add_task(function checkLoadedAres() {
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
-});
-
-// Check registering and unregistering a new area.
-add_task(function checkRegisteringAndUnregistering() {
- const kToolbarId = "test-registration-toolbar";
- const kButtonId = "test-registration-button";
- createDummyXULButton(kButtonId);
- createToolbarWithPlacements(kToolbarId, ["spring", kButtonId, "spring"]);
- assertAreaPlacements(kToolbarId,
- [/customizableui-special-spring\d+/,
- kButtonId,
- /customizableui-special-spring\d+/]);
- ok(!CustomizableUI.inDefaultState, "With a new toolbar it is no longer in a default state.");
- removeCustomToolbars(); // Will call unregisterArea for us
- ok(CustomizableUI.inDefaultState, "When the toolbar is unregistered, " +
- "everything will return to the default state.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_877447_skip_missing_ids.js b/browser/components/customizableui/test/browser_877447_skip_missing_ids.js
deleted file mode 100644
index 0cba7ae4f..000000000
--- a/browser/components/customizableui/test/browser_877447_skip_missing_ids.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-registerCleanupFunction(removeCustomToolbars);
-
-add_task(function skipMissingIDS() {
- const kButtonId = "look-at-me-disappear-button";
- CustomizableUI.reset();
- ok(CustomizableUI.inDefaultState, "Should be in the default state.");
- let btn = createDummyXULButton(kButtonId, "Gone!");
- CustomizableUI.addWidgetToArea(kButtonId, CustomizableUI.AREA_NAVBAR);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in the default state.");
- is(btn.parentNode.parentNode.id, CustomizableUI.AREA_NAVBAR, "Button should be in navbar");
- btn.remove();
- is(btn.parentNode, null, "Button is no longer in the navbar");
- ok(CustomizableUI.inDefaultState, "Should be back in the default state, " +
- "despite unknown button ID in placements.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_878452_drag_to_panel.js b/browser/components/customizableui/test/browser_878452_drag_to_panel.js
deleted file mode 100644
index 8a8d82294..000000000
--- a/browser/components/customizableui/test/browser_878452_drag_to_panel.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Dragging an item from the palette to another button in the panel should work.
-add_task(function*() {
- yield startCustomizing();
- let btn = document.getElementById("feed-button");
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
-
- let lastButtonIndex = placements.length - 1;
- let lastButton = placements[lastButtonIndex];
- let placementsAfterInsert = placements.slice(0, lastButtonIndex).concat(["feed-button", lastButton]);
- let lastButtonNode = document.getElementById(lastButton);
- simulateItemDrag(btn, lastButtonNode);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(btn, palette);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging an item from the palette to the panel itself should also work.
-add_task(function*() {
- yield startCustomizing();
- let btn = document.getElementById("feed-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
-
- let placementsAfterAppend = placements.concat(["feed-button"]);
- simulateItemDrag(btn, panel);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(btn, palette);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging an item from the palette to an empty panel should also work.
-add_task(function*() {
- let widgetIds = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
- while (widgetIds.length) {
- CustomizableUI.removeWidgetFromArea(widgetIds.shift());
- }
- yield startCustomizing();
- let btn = document.getElementById("feed-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
-
- assertAreaPlacements(panel.id, []);
-
- let placementsAfterAppend = ["feed-button"];
- simulateItemDrag(btn, panel);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(btn, palette);
- assertAreaPlacements(panel.id, []);
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_880164_customization_context_menus.js b/browser/components/customizableui/test/browser_880164_customization_context_menus.js
deleted file mode 100644
index 57a0db773..000000000
--- a/browser/components/customizableui/test/browser_880164_customization_context_menus.js
+++ /dev/null
@@ -1,414 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-const isOSX = (Services.appinfo.OS === "Darwin");
-
-// Right-click on the home button should
-// show a context menu with options to move it.
-add_task(function*() {
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownPromise = popupShown(contextMenu);
- let homeButton = document.getElementById("home-button");
- EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2 });
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToPanel", true],
- [".customize-context-removeFromToolbar", true],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
-});
-
-// Right-click on an empty bit of tabstrip should
-// show a context menu without options to move it,
-// but with tab-specific options instead.
-add_task(function*() {
- // ensure there are tabs to reload/bookmark:
- let extraTab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(extraTab, "http://example.com/");
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownPromise = popupShown(contextMenu);
- let tabstrip = document.getElementById("tabbrowser-tabs");
- let rect = tabstrip.getBoundingClientRect();
- EventUtils.synthesizeMouse(tabstrip, rect.width - 2, 2, {type: "contextmenu", button: 2 });
- yield shownPromise;
-
- let closedTabsAvailable = SessionStore.getClosedTabCount(window) == 0;
- info("Closed tabs: " + closedTabsAvailable);
- let expectedEntries = [
- ["#toolbar-context-reloadAllTabs", true],
- ["#toolbar-context-bookmarkAllTabs", true],
- ["#toolbar-context-undoCloseTab", !closedTabsAvailable],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
- gBrowser.removeTab(extraTab);
-});
-
-// Right-click on an empty bit of extra toolbar should
-// show a context menu with moving options disabled,
-// and a toggle option for the extra toolbar
-add_task(function*() {
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownPromise = popupShown(contextMenu);
- let toolbar = createToolbarWithPlacements("880164_empty_toolbar", []);
- toolbar.setAttribute("context", "toolbar-context-menu");
- toolbar.setAttribute("toolbarname", "Fancy Toolbar for Context Menu");
- EventUtils.synthesizeMouseAtCenter(toolbar, {type: "contextmenu", button: 2 });
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToPanel", false],
- [".customize-context-removeFromToolbar", false],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["#toggle_880164_empty_toolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
- removeCustomToolbars();
-});
-
-
-// Right-click on the urlbar-container should
-// show a context menu with disabled options to move it.
-add_task(function*() {
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownPromise = popupShown(contextMenu);
- let urlBarContainer = document.getElementById("urlbar-container");
- // Need to make sure not to click within an edit field.
- EventUtils.synthesizeMouse(urlBarContainer, 100, 1, {type: "contextmenu", button: 2 });
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToPanel", false],
- [".customize-context-removeFromToolbar", false],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
-});
-
-// Right-click on the searchbar and moving it to the menu
-// and back should move the search-container instead.
-add_task(function*() {
- let searchbar = document.getElementById("searchbar");
- gCustomizeMode.addToPanel(searchbar);
- let placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel");
-
- let shownPanelPromise = promisePanelShown(window);
- PanelUI.toggle({type: "command"});
- yield shownPanelPromise;
- let hiddenPanelPromise = promisePanelHidden(window);
- PanelUI.toggle({type: "command"});
- yield hiddenPanelPromise;
-
- gCustomizeMode.addToToolbar(searchbar);
- placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in navbar");
- gCustomizeMode.removeFromArea(searchbar);
- placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement, null, "Should be in palette");
- CustomizableUI.reset();
- placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in navbar");
-});
-
-// Right-click on an item within the menu panel should
-// show a context menu with options to move it.
-add_task(function*() {
- let shownPanelPromise = promisePanelShown(window);
- PanelUI.toggle({type: "command"});
- yield shownPanelPromise;
-
- let contextMenu = document.getElementById("customizationPanelItemContextMenu");
- let shownContextPromise = popupShown(contextMenu);
- let newWindowButton = document.getElementById("new-window-button");
- ok(newWindowButton, "new-window-button was found");
- EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownContextPromise;
-
- is(PanelUI.panel.state, "open", "The PanelUI should still be open.");
-
- let expectedEntries = [
- [".customize-context-moveToToolbar", true],
- [".customize-context-removeFromPanel", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- ];
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
-
- let hiddenPromise = promisePanelHidden(window);
- PanelUI.toggle({type: "command"});
- yield hiddenPromise;
-});
-
-// Right-click on the home button while in customization mode
-// should show a context menu with options to move it.
-add_task(function*() {
- yield startCustomizing();
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownPromise = popupShown(contextMenu);
- let homeButton = document.getElementById("wrapper-home-button");
- EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToPanel", true],
- [".customize-context-removeFromToolbar", true],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", false]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
-});
-
-// Right-click on an item in the palette should
-// show a context menu with options to move it.
-add_task(function*() {
- let contextMenu = document.getElementById("customizationPaletteItemContextMenu");
- let shownPromise = popupShown(contextMenu);
- let openFileButton = document.getElementById("wrapper-open-file-button");
- EventUtils.synthesizeMouse(openFileButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-addToToolbar", true],
- [".customize-context-addToPanel", true]
- ];
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
-});
-
-// Right-click on an item in the panel while in customization mode
-// should show a context menu with options to move it.
-add_task(function*() {
- let contextMenu = document.getElementById("customizationPanelItemContextMenu");
- let shownPromise = popupShown(contextMenu);
- let newWindowButton = document.getElementById("wrapper-new-window-button");
- EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToToolbar", true],
- [".customize-context-removeFromPanel", true],
- ["---"],
- [".viewCustomizeToolbar", false]
- ];
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
- yield endCustomizing();
-});
-
-// Test the toolbarbutton panel context menu in customization mode
-// without opening the panel before customization mode
-add_task(function*() {
- this.otherWin = yield openAndLoadWindow(null, true);
-
- yield new Promise(resolve => waitForFocus(resolve, this.otherWin));
-
- yield startCustomizing(this.otherWin);
-
- let contextMenu = this.otherWin.document.getElementById("customizationPanelItemContextMenu");
- let shownPromise = popupShown(contextMenu);
- let newWindowButton = this.otherWin.document.getElementById("wrapper-new-window-button");
- EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}, this.otherWin);
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToToolbar", true],
- [".customize-context-removeFromPanel", true],
- ["---"],
- [".viewCustomizeToolbar", false]
- ];
- checkContextMenu(contextMenu, expectedEntries, this.otherWin);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
- yield endCustomizing(this.otherWin);
- yield promiseWindowClosed(this.otherWin);
- this.otherWin = null;
-
- yield new Promise(resolve => waitForFocus(resolve, window));
-});
-
-// Bug 945191 - Combined buttons show wrong context menu options
-// when they are in the toolbar.
-add_task(function*() {
- yield startCustomizing();
- let contextMenu = document.getElementById("customizationPanelItemContextMenu");
- let shownPromise = popupShown(contextMenu);
- let zoomControls = document.getElementById("wrapper-zoom-controls");
- EventUtils.synthesizeMouse(zoomControls, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
- // Execute the command to move the item from the panel to the toolbar.
- contextMenu.childNodes[0].doCommand();
- let hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
- yield endCustomizing();
-
- zoomControls = document.getElementById("zoom-controls");
- is(zoomControls.parentNode.id, "nav-bar-customization-target", "Zoom-controls should be on the nav-bar");
-
- contextMenu = document.getElementById("toolbar-context-menu");
- shownPromise = popupShown(contextMenu);
- EventUtils.synthesizeMouse(zoomControls, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
-
- let expectedEntries = [
- [".customize-context-moveToPanel", true],
- [".customize-context-removeFromToolbar", true],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- hiddenPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenPromise;
- yield resetCustomization();
-});
-
-// Bug 947586 - After customization, panel items show wrong context menu options
-add_task(function*() {
- yield startCustomizing();
- yield endCustomizing();
-
- yield PanelUI.show();
-
- let contextMenu = document.getElementById("customizationPanelItemContextMenu");
- let shownContextPromise = popupShown(contextMenu);
- let newWindowButton = document.getElementById("new-window-button");
- ok(newWindowButton, "new-window-button was found");
- EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownContextPromise;
-
- is(PanelUI.panel.state, "open", "The PanelUI should still be open.");
-
- let expectedEntries = [
- [".customize-context-moveToToolbar", true],
- [".customize-context-removeFromPanel", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- ];
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
-
- let hiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield hiddenPromise;
-});
-
-
-// Bug 982027 - moving icon around removes custom context menu.
-add_task(function*() {
- let widgetId = "custom-context-menu-toolbarbutton";
- let expectedContext = "myfancycontext";
- let widget = createDummyXULButton(widgetId, "Test ctxt menu");
- widget.setAttribute("context", expectedContext);
- CustomizableUI.addWidgetToArea(widgetId, CustomizableUI.AREA_NAVBAR);
- is(widget.getAttribute("context"), expectedContext, "Should have context menu when added to the toolbar.");
-
- yield startCustomizing();
- is(widget.getAttribute("context"), "", "Should not have own context menu in the toolbar now that we're customizing.");
- is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped when in toolbar.");
-
- let panel = PanelUI.contents;
- simulateItemDrag(widget, panel);
- is(widget.getAttribute("context"), "", "Should not have own context menu when in the panel.");
- is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped now that we're in the panel.");
-
- simulateItemDrag(widget, document.getElementById("nav-bar").customizationTarget);
- is(widget.getAttribute("context"), "", "Should not have own context menu when back in toolbar because we're still customizing.");
- is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped now that we're back in the toolbar.");
-
- yield endCustomizing();
- is(widget.getAttribute("context"), expectedContext, "Should have context menu again now that we're out of customize mode.");
- CustomizableUI.removeWidgetFromArea(widgetId);
- widget.remove();
- ok(CustomizableUI.inDefaultState, "Should be in default state after removing button.");
-});
diff --git a/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js b/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js
deleted file mode 100644
index 9057d0557..000000000
--- a/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js
+++ /dev/null
@@ -1,497 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(5);
-
-// Dragging the zoom controls to be before the print button should not move any controls.
-add_task(function*() {
- yield startCustomizing();
- let zoomControls = document.getElementById("zoom-controls");
- let printButton = document.getElementById("print-button");
- let placementsAfterMove = ["edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "zoom-controls",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(zoomControls, printButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let newWindowButton = document.getElementById("new-window-button");
- simulateItemDrag(zoomControls, newWindowButton);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging the zoom controls to be before the save button should not move any controls.
-add_task(function*() {
- yield startCustomizing();
- let zoomControls = document.getElementById("zoom-controls");
- let savePageButton = document.getElementById("save-page-button");
- let placementsAfterMove = ["edit-controls",
- "zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(zoomControls, savePageButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(CustomizableUI.inDefaultState, "Should be in default state.");
-});
-
-
-// Dragging the zoom controls to be before the new-window button should not move any widgets.
-add_task(function*() {
- yield startCustomizing();
- let zoomControls = document.getElementById("zoom-controls");
- let newWindowButton = document.getElementById("new-window-button");
- let placementsAfterMove = ["edit-controls",
- "zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(zoomControls, newWindowButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the zoom controls to be before the history-panelmenu should move the zoom-controls in to the row higher than the history-panelmenu.
-add_task(function*() {
- yield startCustomizing();
- let zoomControls = document.getElementById("zoom-controls");
- let historyPanelMenu = document.getElementById("history-panelmenu");
- let placementsAfterMove = ["edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "zoom-controls",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(zoomControls, historyPanelMenu);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let newWindowButton = document.getElementById("new-window-button");
- simulateItemDrag(zoomControls, newWindowButton);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging the zoom controls to be before the preferences-button should move the zoom-controls
-// in to the row higher than the preferences-button.
-add_task(function*() {
- yield startCustomizing();
- let zoomControls = document.getElementById("zoom-controls");
- let preferencesButton = document.getElementById("preferences-button");
- let placementsAfterMove = ["edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "zoom-controls",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(zoomControls, preferencesButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let newWindowButton = document.getElementById("new-window-button");
- simulateItemDrag(zoomControls, newWindowButton);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging an item from the palette to before the zoom-controls should move it and two other buttons before the zoom controls.
-add_task(function*() {
- yield startCustomizing();
- let openFileButton = document.getElementById("open-file-button");
- let zoomControls = document.getElementById("zoom-controls");
- let placementsAfterInsert = ["edit-controls",
- "open-file-button",
- "new-window-button",
- "privatebrowsing-button",
- "zoom-controls",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterInsert);
- simulateItemDrag(openFileButton, zoomControls);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let palette = document.getElementById("customization-palette");
- // Check that the palette items are re-wrapped correctly.
- let feedWrapper = document.getElementById("wrapper-feed-button");
- let feedButton = document.getElementById("feed-button");
- is(feedButton.parentNode, feedWrapper,
- "feed-button should be a child of wrapper-feed-button");
- is(feedWrapper.getAttribute("place"), "palette",
- "The feed-button wrapper should have it's place set to 'palette'");
- simulateItemDrag(openFileButton, palette);
- is(openFileButton.parentNode.tagName, "toolbarpaletteitem",
- "The open-file-button should be wrapped by a toolbarpaletteitem");
- let newWindowButton = document.getElementById("new-window-button");
- simulateItemDrag(zoomControls, newWindowButton);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging an item from the palette to before the edit-controls
-// should move it and two other buttons before the edit and zoom controls.
-add_task(function*() {
- yield startCustomizing();
- let openFileButton = document.getElementById("open-file-button");
- let editControls = document.getElementById("edit-controls");
- let placementsAfterInsert = ["open-file-button",
- "new-window-button",
- "privatebrowsing-button",
- "edit-controls",
- "zoom-controls",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterInsert);
- simulateItemDrag(openFileButton, editControls);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- let palette = document.getElementById("customization-palette");
- // Check that the palette items are re-wrapped correctly.
- let feedWrapper = document.getElementById("wrapper-feed-button");
- let feedButton = document.getElementById("feed-button");
- is(feedButton.parentNode, feedWrapper,
- "feed-button should be a child of wrapper-feed-button");
- is(feedWrapper.getAttribute("place"), "palette",
- "The feed-button wrapper should have it's place set to 'palette'");
- simulateItemDrag(openFileButton, palette);
- is(openFileButton.parentNode.tagName, "toolbarpaletteitem",
- "The open-file-button should be wrapped by a toolbarpaletteitem");
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Dragging the edit-controls to be before the zoom-controls button
-// should not move any widgets.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let zoomControls = document.getElementById("zoom-controls");
- let placementsAfterMove = ["edit-controls",
- "zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, zoomControls);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to be before the new-window-button should
-// move the zoom-controls before the edit-controls.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let newWindowButton = document.getElementById("new-window-button");
- let placementsAfterMove = ["zoom-controls",
- "edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, newWindowButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to be before the privatebrowsing-button
-// should move the edit-controls in to the row higher than the
-// privatebrowsing-button.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let privateBrowsingButton = document.getElementById("privatebrowsing-button");
- let placementsAfterMove = ["zoom-controls",
- "edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, privateBrowsingButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to be before the save-page-button
-// should move the edit-controls in to the row higher than the
-// save-page-button.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let savePageButton = document.getElementById("save-page-button");
- let placementsAfterMove = ["zoom-controls",
- "edit-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, savePageButton);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to the panel itself should append
-// the edit controls to the bottom of the panel.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let placementsAfterMove = ["zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "edit-controls",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, panel);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to the customization-palette and
-// back should work.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let palette = document.getElementById("customization-palette");
- let placementsAfterMove = ["zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "developer-button",
- "sync-button",
- ];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- let paletteChildElementCount = palette.childElementCount;
- simulateItemDrag(editControls, palette);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- is(paletteChildElementCount + 1, palette.childElementCount,
- "The palette should have a new child, congratulations!");
- is(editControls.parentNode.id, "wrapper-edit-controls",
- "The edit-controls should be properly wrapped.");
- is(editControls.parentNode.getAttribute("place"), "palette",
- "The edit-controls should have the place of 'palette'.");
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- is(paletteChildElementCount, palette.childElementCount,
- "The palette child count should have returned to its prior value.");
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging the edit-controls to each of the panel placeholders
-// should append the edit-controls to the bottom of the panel.
-add_task(function*() {
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let numPlaceholders = 2;
- for (let i = 0; i < numPlaceholders; i++) {
- // This test relies on there being a specific number of widgets in the
- // panel. The addition of sync-button screwed this up, so we remove it
- // here. We should either fix the tests to not rely on the specific layout,
- // or fix bug 1007910 which would change the placeholder logic in different
- // ways. Bug 1229236 is for these tests to be smarter.
- CustomizableUI.removeWidgetFromArea("sync-button");
- // NB: We can't just iterate over all of the placeholders
- // because each drag-drop action recreates them.
- let placeholder = panel.getElementsByClassName("panel-customization-placeholder")[i];
- let placementsAfterMove = ["zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "edit-controls",
- "developer-button"];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, placeholder);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(editControls, zoomControls);
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
- }
-});
-
-// Dragging the open-file-button back on to itself should work.
-add_task(function*() {
- yield startCustomizing();
- let openFileButton = document.getElementById("open-file-button");
- is(openFileButton.parentNode.tagName, "toolbarpaletteitem",
- "open-file-button should be wrapped by a toolbarpaletteitem");
- simulateItemDrag(openFileButton, openFileButton);
- is(openFileButton.parentNode.tagName, "toolbarpaletteitem",
- "open-file-button should be wrapped by a toolbarpaletteitem");
- let editControls = document.getElementById("edit-controls");
- is(editControls.parentNode.tagName, "toolbarpaletteitem",
- "edit-controls should be wrapped by a toolbarpaletteitem");
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-// Dragging a small button onto the last big button should work.
-add_task(function*() {
- // Bug 1007910 requires there be a placeholder on the final row for this
- // test to work as written. The addition of sync-button meant that's not true
- // so we remove it from here. Bug 1229236 is for these tests to be smarter.
- CustomizableUI.removeWidgetFromArea("sync-button");
- yield startCustomizing();
- let editControls = document.getElementById("edit-controls");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let target = panel.getElementsByClassName("panel-customization-placeholder")[0];
- let placementsAfterMove = ["zoom-controls",
- "new-window-button",
- "privatebrowsing-button",
- "save-page-button",
- "print-button",
- "history-panelmenu",
- "fullscreen-button",
- "find-button",
- "preferences-button",
- "add-ons-button",
- "edit-controls",
- "developer-button"];
- removeDeveloperButtonIfDevEdition(placementsAfterMove);
- simulateItemDrag(editControls, target);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
- let itemToDrag = "email-link-button"; // any button in the palette by default.
- let button = document.getElementById(itemToDrag);
- placementsAfterMove.splice(11, 0, itemToDrag);
- simulateItemDrag(button, editControls);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove);
-
- // Put stuff back:
- let palette = document.getElementById("customization-palette");
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(button, palette);
- simulateItemDrag(editControls, zoomControls);
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_884402_customize_from_overflow.js b/browser/components/customizableui/test/browser_884402_customize_from_overflow.js
deleted file mode 100644
index f50767c06..000000000
--- a/browser/components/customizableui/test/browser_884402_customize_from_overflow.js
+++ /dev/null
@@ -1,81 +0,0 @@
-"use strict";
-
-var overflowPanel = document.getElementById("widget-overflow");
-
-const isOSX = (Services.appinfo.OS === "Darwin");
-
-var originalWindowWidth;
-registerCleanupFunction(function() {
- overflowPanel.removeAttribute("animate");
- window.resizeTo(originalWindowWidth, window.outerHeight);
-});
-
-// Right-click on an item within the overflow panel should
-// show a context menu with options to move it.
-add_task(function*() {
-
- overflowPanel.setAttribute("animate", "false");
-
- originalWindowWidth = window.outerWidth;
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- window.resizeTo(400, window.outerHeight);
-
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- let chevron = document.getElementById("nav-bar-overflow-button");
- let shownPanelPromise = promisePanelElementShown(window, overflowPanel);
- chevron.click();
- yield shownPanelPromise;
-
- let contextMenu = document.getElementById("toolbar-context-menu");
- let shownContextPromise = popupShown(contextMenu);
- let homeButton = document.getElementById("home-button");
- ok(homeButton, "home-button was found");
- is(homeButton.getAttribute("overflowedItem"), "true", "Home button is overflowing");
- EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownContextPromise;
-
- is(overflowPanel.state, "open", "The widget overflow panel should still be open.");
-
- let expectedEntries = [
- [".customize-context-moveToPanel", true],
- [".customize-context-removeFromToolbar", true],
- ["---"]
- ];
- if (!isOSX) {
- expectedEntries.push(["#toggle_toolbar-menubar", true]);
- }
- expectedEntries.push(
- ["#toggle_PersonalToolbar", true],
- ["---"],
- [".viewCustomizeToolbar", true]
- );
- checkContextMenu(contextMenu, expectedEntries);
-
- let hiddenContextPromise = popupHidden(contextMenu);
- let hiddenPromise = promisePanelElementHidden(window, overflowPanel);
- let moveToPanel = contextMenu.querySelector(".customize-context-moveToPanel");
- if (moveToPanel) {
- moveToPanel.click();
- }
- contextMenu.hidePopup();
- yield hiddenContextPromise;
- yield hiddenPromise;
-
- let homeButtonPlacement = CustomizableUI.getPlacementOfWidget("home-button");
- ok(homeButtonPlacement, "Home button should still have a placement");
- is(homeButtonPlacement && homeButtonPlacement.area, "PanelUI-contents", "Home button should be in the panel now");
- CustomizableUI.reset();
-
- // In some cases, it can take a tick for the navbar to overflow again. Wait for it:
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- homeButtonPlacement = CustomizableUI.getPlacementOfWidget("home-button");
- ok(homeButtonPlacement, "Home button should still have a placement");
- is(homeButtonPlacement && homeButtonPlacement.area, "nav-bar", "Home button should be back in the navbar now");
-
- is(homeButton.getAttribute("overflowedItem"), "true", "Home button should still be overflowed");
-});
diff --git a/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js b/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js
deleted file mode 100644
index ea6f5a4e3..000000000
--- a/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-function isFullscreenSizeMode() {
- let sizemode = document.documentElement.getAttribute("sizemode");
- return sizemode == "fullscreen";
-}
-
-// Observers should be disabled when in customization mode.
-add_task(function*() {
- // Open and close the panel to make sure that the
- // area is generated before getting a child of the area.
- let shownPanelPromise = promisePanelShown(window);
- PanelUI.toggle({type: "command"});
- yield shownPanelPromise;
- let hiddenPanelPromise = promisePanelHidden(window);
- PanelUI.toggle({type: "command"});
- yield hiddenPanelPromise;
-
- let fullscreenButton = document.getElementById("fullscreen-button");
- ok(!fullscreenButton.checked, "Fullscreen button should not be checked when not in fullscreen.")
- ok(!isFullscreenSizeMode(), "Should not be in fullscreen sizemode before we enter fullscreen.");
-
- BrowserFullScreen();
- yield waitForCondition(() => isFullscreenSizeMode());
- ok(fullscreenButton.checked, "Fullscreen button should be checked when in fullscreen.")
-
- yield startCustomizing();
-
- let fullscreenButtonWrapper = document.getElementById("wrapper-fullscreen-button");
- ok(fullscreenButtonWrapper.hasAttribute("itemobserves"), "Observer should be moved to wrapper");
- fullscreenButton = document.getElementById("fullscreen-button");
- ok(!fullscreenButton.hasAttribute("observes"), "Observer should be removed from button");
- ok(!fullscreenButton.checked, "Fullscreen button should no longer be checked during customization mode");
-
- yield endCustomizing();
-
- BrowserFullScreen();
- fullscreenButton = document.getElementById("fullscreen-button");
- yield waitForCondition(() => !isFullscreenSizeMode());
- ok(!fullscreenButton.checked, "Fullscreen button should not be checked when not in fullscreen.")
-});
diff --git a/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js b/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js
deleted file mode 100644
index e55c21862..000000000
--- a/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "some-widget";
-
-function assertWidgetExists(aWindow, aExists) {
- if (aExists) {
- ok(aWindow.document.getElementById(kWidgetId),
- "Should have found test widget in the window");
- } else {
- is(aWindow.document.getElementById(kWidgetId), null,
- "Should not have found test widget in the window");
- }
-}
-
-// A widget that is created with showInPrivateBrowsing undefined should
-// have that value default to true.
-add_task(function() {
- let wrapper = CustomizableUI.createWidget({
- id: kWidgetId
- });
- ok(wrapper.showInPrivateBrowsing,
- "showInPrivateBrowsing should have defaulted to true.");
- CustomizableUI.destroyWidget(kWidgetId);
-});
-
-// Add a widget via the API with showInPrivateBrowsing set to false
-// and ensure it does not appear in pre-existing or newly created
-// private windows.
-add_task(function*() {
- let plain1 = yield openAndLoadWindow();
- let private1 = yield openAndLoadWindow({private: true});
- CustomizableUI.createWidget({
- id: kWidgetId,
- removable: true,
- showInPrivateBrowsing: false
- });
- CustomizableUI.addWidgetToArea(kWidgetId,
- CustomizableUI.AREA_NAVBAR);
- assertWidgetExists(plain1, true);
- assertWidgetExists(private1, false);
-
- // Now open up some new windows. The widget should exist in the new
- // plain window, but not the new private window.
- let plain2 = yield openAndLoadWindow();
- let private2 = yield openAndLoadWindow({private: true});
- assertWidgetExists(plain2, true);
- assertWidgetExists(private2, false);
-
- // Try moving the widget around and make sure it doesn't get added
- // to the private windows. We'll start by appending it to the tabstrip.
- CustomizableUI.addWidgetToArea(kWidgetId,
- CustomizableUI.AREA_TABSTRIP);
- assertWidgetExists(plain1, true);
- assertWidgetExists(plain2, true);
- assertWidgetExists(private1, false);
- assertWidgetExists(private2, false);
-
- // And then move it to the beginning of the tabstrip.
- CustomizableUI.moveWidgetWithinArea(kWidgetId, 0);
- assertWidgetExists(plain1, true);
- assertWidgetExists(plain2, true);
- assertWidgetExists(private1, false);
- assertWidgetExists(private2, false);
-
- CustomizableUI.removeWidgetFromArea("some-widget");
- assertWidgetExists(plain1, false);
- assertWidgetExists(plain2, false);
- assertWidgetExists(private1, false);
- assertWidgetExists(private2, false);
-
- yield Promise.all([plain1, plain2, private1, private2].map(promiseWindowClosed));
-
- CustomizableUI.destroyWidget("some-widget");
-});
-
-// Add a widget via the API with showInPrivateBrowsing set to true,
-// and ensure that it appears in pre-existing or newly created
-// private browsing windows.
-add_task(function*() {
- let plain1 = yield openAndLoadWindow();
- let private1 = yield openAndLoadWindow({private: true});
-
- CustomizableUI.createWidget({
- id: kWidgetId,
- removable: true,
- showInPrivateBrowsing: true
- });
- CustomizableUI.addWidgetToArea(kWidgetId,
- CustomizableUI.AREA_NAVBAR);
- assertWidgetExists(plain1, true);
- assertWidgetExists(private1, true);
-
- // Now open up some new windows. The widget should exist in the new
- // plain window, but not the new private window.
- let plain2 = yield openAndLoadWindow();
- let private2 = yield openAndLoadWindow({private: true});
-
- assertWidgetExists(plain2, true);
- assertWidgetExists(private2, true);
-
- // Try moving the widget around and make sure it doesn't get added
- // to the private windows. We'll start by appending it to the tabstrip.
- CustomizableUI.addWidgetToArea(kWidgetId,
- CustomizableUI.AREA_TABSTRIP);
- assertWidgetExists(plain1, true);
- assertWidgetExists(plain2, true);
- assertWidgetExists(private1, true);
- assertWidgetExists(private2, true);
-
- // And then move it to the beginning of the tabstrip.
- CustomizableUI.moveWidgetWithinArea(kWidgetId, 0);
- assertWidgetExists(plain1, true);
- assertWidgetExists(plain2, true);
- assertWidgetExists(private1, true);
- assertWidgetExists(private2, true);
-
- CustomizableUI.removeWidgetFromArea("some-widget");
- assertWidgetExists(plain1, false);
- assertWidgetExists(plain2, false);
- assertWidgetExists(private1, false);
- assertWidgetExists(private2, false);
-
- yield Promise.all([plain1, plain2, private1, private2].map(promiseWindowClosed));
-
- CustomizableUI.destroyWidget("some-widget");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js b/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js
deleted file mode 100644
index f46141c4f..000000000
--- a/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kButtonId = "test-886323-removable-moved-node";
-const kLazyAreaId = "test-886323-lazy-area-for-removability-testing";
-
-var gNavBar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-var gLazyArea;
-
-// Removable nodes shouldn't be moved by buildArea
-add_task(function*() {
- let dummyBtn = createDummyXULButton(kButtonId, "Dummy");
- dummyBtn.setAttribute("removable", "true");
- gNavBar.customizationTarget.appendChild(dummyBtn);
- let popupSet = document.getElementById("mainPopupSet");
- gLazyArea = document.createElementNS(kNSXUL, "panel");
- gLazyArea.id = kLazyAreaId;
- gLazyArea.setAttribute("hidden", "true");
- popupSet.appendChild(gLazyArea);
- CustomizableUI.registerArea(kLazyAreaId, {
- type: CustomizableUI.TYPE_MENU_PANEL,
- defaultPlacements: []
- });
- CustomizableUI.addWidgetToArea(kButtonId, kLazyAreaId);
- assertAreaPlacements(kLazyAreaId, [kButtonId],
- "Placements should have changed because widget is removable.");
- let btn = document.getElementById(kButtonId);
- btn.setAttribute("removable", "false");
- gLazyArea.customizationTarget = gLazyArea;
- CustomizableUI.registerToolbarNode(gLazyArea, []);
- assertAreaPlacements(kLazyAreaId, [], "Placements should no longer include widget.");
- is(btn.parentNode.id, gNavBar.customizationTarget.id,
- "Button shouldn't actually have moved as it's not removable");
- btn = document.getElementById(kButtonId);
- if (btn) btn.remove();
- CustomizableUI.removeWidgetFromArea(kButtonId);
- CustomizableUI.unregisterArea(kLazyAreaId);
- gLazyArea.remove();
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_887438_currentset_shim.js b/browser/components/customizableui/test/browser_887438_currentset_shim.js
deleted file mode 100644
index a04299819..000000000
--- a/browser/components/customizableui/test/browser_887438_currentset_shim.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var navbar = document.getElementById("nav-bar");
-var navbarCT = navbar.customizationTarget;
-var overflowPanelList = document.getElementById("widget-overflow-list");
-
-// Reading currentset
-add_task(function() {
- let nodeIds = [];
- for (let node of navbarCT.childNodes) {
- if (node.getAttribute("skipintoolbarset") != "true") {
- nodeIds.push(node.id);
- }
- }
- for (let node of overflowPanelList.childNodes) {
- if (node.getAttribute("skipintoolbarset") != "true") {
- nodeIds.push(node.id);
- }
- }
- let currentSet = navbar.currentSet;
- is(currentSet.split(',').length, nodeIds.length, "Should be just as many nodes as there are.");
- is(currentSet, nodeIds.join(','), "Current set and node IDs should match.");
-});
-
-// Insert, then remove items
-add_task(function() {
- let currentSet = navbar.currentSet;
- let newCurrentSet = currentSet.replace('home-button', 'feed-button,sync-button,home-button');
- navbar.currentSet = newCurrentSet;
- is(newCurrentSet, navbar.currentSet, "Current set should match expected current set.");
- let feedBtn = document.getElementById("feed-button");
- let syncBtn = document.getElementById("sync-button");
- ok(feedBtn, "Feed button should have been added.");
- ok(syncBtn, "Sync button should have been added.");
- if (feedBtn && syncBtn) {
- let feedParent = feedBtn.parentNode;
- let syncParent = syncBtn.parentNode;
- ok(feedParent == navbarCT || feedParent == overflowPanelList,
- "Feed button should be in navbar or overflow");
- ok(syncParent == navbarCT || syncParent == overflowPanelList,
- "Feed button should be in navbar or overflow");
- is(feedBtn.nextElementSibling, syncBtn, "Feed button should be next to sync button.");
- let homeBtn = document.getElementById("home-button");
- is(syncBtn.nextElementSibling, homeBtn, "Sync button should be next to home button.");
- }
- navbar.currentSet = currentSet;
- is(currentSet, navbar.currentSet, "Should be able to remove the added items.");
-});
-
-// Simultaneous insert/remove:
-add_task(function() {
- let currentSet = navbar.currentSet;
- let newCurrentSet = currentSet.replace('home-button', 'feed-button');
- navbar.currentSet = newCurrentSet;
- is(newCurrentSet, navbar.currentSet, "Current set should match expected current set.");
- let feedBtn = document.getElementById("feed-button");
- ok(feedBtn, "Feed button should have been added.");
- let homeBtn = document.getElementById("home-button");
- ok(!homeBtn, "Home button should have been removed.");
- if (feedBtn) {
- let feedParent = feedBtn.parentNode;
- ok(feedParent == navbarCT || feedParent == overflowPanelList,
- "Feed button should be in navbar or overflow");
- }
- navbar.currentSet = currentSet;
- is(currentSet, navbar.currentSet, "Should be able to return to original state.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_888817_currentset_updating.js b/browser/components/customizableui/test/browser_888817_currentset_updating.js
deleted file mode 100644
index 6e7c4e95a..000000000
--- a/browser/components/customizableui/test/browser_888817_currentset_updating.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Adding, moving and removing items should update the relevant currentset attributes
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Should be in the default state when we start");
- let personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS);
- setToolbarVisibility(personalbar, true);
- ok(!CustomizableUI.inDefaultState, "Making the bookmarks toolbar visible takes it out of the default state");
-
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS);
- let navbarCurrentset = navbar.getAttribute("currentset") || navbar.currentSet;
- let personalbarCurrentset = personalbar.getAttribute("currentset") || personalbar.currentSet;
-
- let otherWin = yield openAndLoadWindow();
- let otherNavbar = otherWin.document.getElementById(CustomizableUI.AREA_NAVBAR);
- let otherPersonalbar = otherWin.document.getElementById(CustomizableUI.AREA_BOOKMARKS);
-
- CustomizableUI.moveWidgetWithinArea("home-button", 0);
- navbarCurrentset = "home-button," + navbarCurrentset.replace(",home-button", "");
- is(navbar.getAttribute("currentset"), navbarCurrentset,
- "Should have updated currentSet after move.");
- is(otherNavbar.getAttribute("currentset"), navbarCurrentset,
- "Should have updated other window's currentSet after move.");
-
- CustomizableUI.addWidgetToArea("home-button", CustomizableUI.AREA_BOOKMARKS);
- navbarCurrentset = navbarCurrentset.replace("home-button,", "");
- personalbarCurrentset = personalbarCurrentset + ",home-button";
- is(navbar.getAttribute("currentset"), navbarCurrentset,
- "Should have updated navbar currentSet after implied remove.");
- is(otherNavbar.getAttribute("currentset"), navbarCurrentset,
- "Should have updated other window's navbar currentSet after implied remove.");
- is(personalbar.getAttribute("currentset"), personalbarCurrentset,
- "Should have updated personalbar currentSet after add.");
- is(otherPersonalbar.getAttribute("currentset"), personalbarCurrentset,
- "Should have updated other window's personalbar currentSet after add.");
-
- CustomizableUI.removeWidgetFromArea("home-button");
- personalbarCurrentset = personalbarCurrentset.replace(",home-button", "");
- is(personalbar.getAttribute("currentset"), personalbarCurrentset,
- "Should have updated currentSet after remove.");
- is(otherPersonalbar.getAttribute("currentset"), personalbarCurrentset,
- "Should have updated other window's currentSet after remove.");
-
- yield promiseWindowClosed(otherWin);
- // Reset in asyncCleanup will put our button back for us.
-});
-
-add_task(function* asyncCleanup() {
- let personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS);
- setToolbarVisibility(personalbar, false);
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js b/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js
deleted file mode 100644
index 84b126a9b..000000000
--- a/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-// One orphaned item should have two placeholders next to it.
-add_task(function*() {
- yield startCustomizing();
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- }
- if (!isInDevEdition()) {
- ok(CustomizableUI.inDefaultState, "Should be in default state.");
- } else {
- ok(!CustomizableUI.inDefaultState, "Should not be in default state if on DevEdition.");
- }
-
- // This test relies on an exact number of widgets being in the panel.
- // Remove the sync-button to satisfy that. (bug 1229236)
- CustomizableUI.removeWidgetFromArea("sync-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
-
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placements);
- is(getVisiblePlaceholderCount(panel), 2, "Should only have 2 visible placeholders before exiting");
-
- yield endCustomizing();
- yield startCustomizing();
- is(getVisiblePlaceholderCount(panel), 2, "Should only have 2 visible placeholders after re-entering");
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2);
- }
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Two orphaned items should have one placeholder next to them (case 1).
-add_task(function*() {
- yield startCustomizing();
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL);
- }
-
- // This test relies on an exact number of widgets being in the panel.
- // Remove the sync-button to satisfy that. (bug 1229236)
- CustomizableUI.removeWidgetFromArea("sync-button");
-
- let btn = document.getElementById("open-file-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
- let placementsAfterAppend = placements;
-
- placementsAfterAppend = placements.concat(["open-file-button"]);
- simulateItemDrag(btn, panel);
-
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend);
-
- ok(!CustomizableUI.inDefaultState, "Should not be in default state.");
-
- is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder before exiting");
-
- yield endCustomizing();
- yield startCustomizing();
- is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder after re-entering");
-
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(btn, palette);
-
- btn = document.getElementById("open-file-button");
- simulateItemDrag(btn, palette);
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2);
- }
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// Two orphaned items should have one placeholder next to them (case 2).
-add_task(function*() {
- yield startCustomizing();
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL);
- }
- // This test relies on an exact number of widgets being in the panel.
- // Remove the sync-button to satisfy that. (bug 1229236)
- CustomizableUI.removeWidgetFromArea("sync-button");
-
- let btn = document.getElementById("add-ons-button");
- let btn2 = document.getElementById("developer-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let palette = document.getElementById("customization-palette");
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
-
- let placementsAfterAppend = placements.filter(p => p != btn.id && p != btn2.id);
- simulateItemDrag(btn, palette);
- simulateItemDrag(btn2, palette);
-
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder before exiting");
-
- yield endCustomizing();
- yield startCustomizing();
- is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder after re-entering");
-
- simulateItemDrag(btn, panel);
- simulateItemDrag(btn2, panel);
-
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placements);
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2);
- }
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// A wide widget at the bottom of the panel should have three placeholders after it.
-add_task(function*() {
- yield startCustomizing();
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL);
- }
-
- // This test relies on an exact number of widgets being in the panel.
- // Remove the sync-button to satisfy that. (bug 1229236)
- CustomizableUI.removeWidgetFromArea("sync-button");
-
- let btn = document.getElementById("edit-controls");
- let btn2 = document.getElementById("developer-button");
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- let palette = document.getElementById("customization-palette");
- let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL);
-
- placements.pop();
- simulateItemDrag(btn2, palette);
-
- let placementsAfterAppend = placements.concat([placements.shift()]);
- simulateItemDrag(btn, panel);
- assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend);
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state.");
- is(getVisiblePlaceholderCount(panel), 3, "Should have 3 visible placeholders before exiting");
-
- yield endCustomizing();
- yield startCustomizing();
- is(getVisiblePlaceholderCount(panel), 3, "Should have 3 visible placeholders after re-entering");
-
- simulateItemDrag(btn2, panel);
-
- let zoomControls = document.getElementById("zoom-controls");
- simulateItemDrag(btn, zoomControls);
-
- if (isInDevEdition()) {
- CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2);
- }
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state again.");
-});
-
-// The default placements should have two placeholders at the bottom (or 1 in win8).
-add_task(function*() {
- yield startCustomizing();
- let numPlaceholders = -1;
-
- if (isInDevEdition()) {
- numPlaceholders = 3;
- } else {
- numPlaceholders = 2;
- }
-
- let panel = document.getElementById(CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should be in default state.");
-
- // This test relies on an exact number of widgets being in the panel.
- // Remove the sync-button to satisfy that. (bug 1229236)
- CustomizableUI.removeWidgetFromArea("sync-button");
-
- is(getVisiblePlaceholderCount(panel), numPlaceholders, "Should have " + numPlaceholders + " visible placeholders before exiting");
-
- yield endCustomizing();
- yield startCustomizing();
- is(getVisiblePlaceholderCount(panel), numPlaceholders, "Should have " + numPlaceholders + " visible placeholders after re-entering");
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- ok(CustomizableUI.inDefaultState, "Should still be in default state.");
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
-
-function getVisiblePlaceholderCount(aPanel) {
- let visiblePlaceholders = aPanel.querySelectorAll(".panel-customization-placeholder:not([hidden=true])");
- return visiblePlaceholders.length;
-}
diff --git a/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js b/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js
deleted file mode 100644
index 13f2bd7ba..000000000
--- a/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kLazyAreaId = "test-890262-lazy-area";
-const kWidget1Id = "test-890262-widget1";
-const kWidget2Id = "test-890262-widget2";
-
-setupArea();
-
-// Destroying a widget after defaulting it to a non-legacy area should work.
-add_task(function() {
- CustomizableUI.createWidget({
- id: kWidget1Id,
- removable: true,
- defaultArea: kLazyAreaId
- });
- let noError = true;
- try {
- CustomizableUI.destroyWidget(kWidget1Id);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Shouldn't throw an exception for a widget that was created in a not-yet-constructed area");
-});
-
-// Destroying a widget after moving it to a non-legacy area should work.
-add_task(function() {
- CustomizableUI.createWidget({
- id: kWidget2Id,
- removable: true,
- defaultArea: CustomizableUI.AREA_NAVBAR
- });
-
- CustomizableUI.addWidgetToArea(kWidget2Id, kLazyAreaId);
- let noError = true;
- try {
- CustomizableUI.destroyWidget(kWidget2Id);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Shouldn't throw an exception for a widget that was added to a not-yet-constructed area");
-});
-
-add_task(function* asyncCleanup() {
- let lazyArea = document.getElementById(kLazyAreaId);
- if (lazyArea) {
- lazyArea.remove();
- }
- try {
- CustomizableUI.unregisterArea(kLazyAreaId);
- } catch (ex) {} // If we didn't register successfully for some reason
- yield resetCustomization();
-});
-
-function setupArea() {
- let lazyArea = document.createElementNS(kNSXUL, "hbox");
- lazyArea.id = kLazyAreaId;
- document.getElementById("nav-bar").appendChild(lazyArea);
- CustomizableUI.registerArea(kLazyAreaId, {
- type: CustomizableUI.TYPE_TOOLBAR,
- defaultPlacements: []
- });
-}
diff --git a/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js b/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js
deleted file mode 100644
index 67ef82b82..000000000
--- a/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-892955-remove-widget";
-
-// Removing a destroyed widget should work.
-add_task(function*() {
- let widgetSpec = {
- id: kWidgetId,
- defaultArea: CustomizableUI.AREA_NAVBAR
- };
-
- CustomizableUI.createWidget(widgetSpec);
- CustomizableUI.destroyWidget(kWidgetId);
- let noError = true;
- try {
- CustomizableUI.removeWidgetFromArea(kWidgetId);
- } catch (ex) {
- noError = false;
- Cu.reportError(ex);
- }
- ok(noError, "Shouldn't throw an error removing a destroyed widget.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js b/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js
deleted file mode 100644
index c7047c797..000000000
--- a/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-892956-destroyWidget-defaultPlacement";
-
-// destroyWidget should clean up defaultPlacements if the widget had a defaultArea
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Should be in the default state when we start");
-
- let widgetSpec = {
- id: kWidgetId,
- defaultArea: CustomizableUI.AREA_NAVBAR
- };
- CustomizableUI.createWidget(widgetSpec);
- CustomizableUI.destroyWidget(kWidgetId);
- ok(CustomizableUI.inDefaultState, "Should be in the default state when we finish");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js b/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js
deleted file mode 100644
index 3bc449add..000000000
--- a/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-logActiveElement();
-
-function* waitForSearchBarFocus()
-{
- let searchbar = document.getElementById("searchbar");
- yield waitForCondition(function () {
- logActiveElement();
- return document.activeElement === searchbar.textbox.inputField;
- });
-}
-
-// Ctrl+K should open the menu panel and focus the search bar if the search bar is in the panel.
-add_task(function*() {
- let searchbar = document.getElementById("searchbar");
- gCustomizeMode.addToPanel(searchbar);
- let placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel");
-
- let shownPanelPromise = promisePanelShown(window);
- sendWebSearchKeyCommand();
- yield shownPanelPromise;
-
- yield waitForSearchBarFocus();
-
- let hiddenPanelPromise = promisePanelHidden(window);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield hiddenPanelPromise;
- CustomizableUI.reset();
-});
-
-// Ctrl+K should give focus to the searchbar when the searchbar is in the menupanel and the panel is already opened.
-add_task(function*() {
- let searchbar = document.getElementById("searchbar");
- gCustomizeMode.addToPanel(searchbar);
- let placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel");
-
- let shownPanelPromise = promisePanelShown(window);
- PanelUI.toggle({type: "command"});
- yield shownPanelPromise;
-
- sendWebSearchKeyCommand();
-
- yield waitForSearchBarFocus();
-
- let hiddenPanelPromise = promisePanelHidden(window);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield hiddenPanelPromise;
- CustomizableUI.reset();
-});
-
-// Ctrl+K should open the overflow panel and focus the search bar if the search bar is overflowed.
-add_task(function*() {
- this.originalWindowWidth = window.outerWidth;
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
-
- window.resizeTo(360, window.outerHeight);
- yield waitForCondition(() => navbar.getAttribute("overflowing") == "true");
- ok(!navbar.querySelector("#search-container"), "Search container should be overflowing");
-
- let shownPanelPromise = promiseOverflowShown(window);
- sendWebSearchKeyCommand();
- yield shownPanelPromise;
-
- let chevron = document.getElementById("nav-bar-overflow-button");
- yield waitForCondition(() => chevron.open);
-
- yield waitForSearchBarFocus();
-
- let hiddenPanelPromise = promiseOverflowHidden(window);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield hiddenPanelPromise;
- navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- window.resizeTo(this.originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar.");
-});
-
-// Ctrl+K should focus the search bar if it is in the navbar and not overflowing.
-add_task(function*() {
- let placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in nav-bar");
-
- sendWebSearchKeyCommand();
-
- yield waitForSearchBarFocus();
-});
-
-
-function sendWebSearchKeyCommand() {
- if (Services.appinfo.OS === "Darwin")
- EventUtils.synthesizeKey("k", { accelKey: true });
- else
- EventUtils.synthesizeKey("k", { ctrlKey: true });
-}
-
-function logActiveElement() {
- let element = document.activeElement;
- let str = "";
- while (element && element.parentNode) {
- str = " (" + element.localName + "#" + element.id + "." + [...element.classList].join(".") + ") >" + str;
- element = element.parentNode;
- }
- info("Active element: " + element ? str : "null");
-}
diff --git a/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js b/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js
deleted file mode 100644
index f39d13ff4..000000000
--- a/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Resize to a small window, open a new window, check that new window handles overflow properly
-add_task(function*() {
- let originalWindowWidth = window.outerWidth;
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- let oldChildCount = navbar.customizationTarget.childElementCount;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- ok(navbar.customizationTarget.childElementCount < oldChildCount, "Should have fewer children.");
- let newWindow = yield openAndLoadWindow();
- let otherNavBar = newWindow.document.getElementById(CustomizableUI.AREA_NAVBAR);
- yield waitForCondition(() => otherNavBar.hasAttribute("overflowing"));
- ok(otherNavBar.hasAttribute("overflowing"), "Other window should have an overflowing toolbar.");
- yield promiseWindowClosed(newWindow);
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should no longer have an overflowing toolbar.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_913972_currentset_overflow.js b/browser/components/customizableui/test/browser_913972_currentset_overflow.js
deleted file mode 100644
index 7d754d79b..000000000
--- a/browser/components/customizableui/test/browser_913972_currentset_overflow.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
-// Resize to a small window, resize back, shouldn't affect currentSet
-add_task(function*() {
- let originalWindowWidth = window.outerWidth;
- let oldCurrentSet = navbar.currentSet;
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
- let oldChildCount = navbar.customizationTarget.childElementCount;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
- is(navbar.currentSet, oldCurrentSet, "Currentset should be the same when overflowing.");
- ok(CustomizableUI.inDefaultState, "Should still be in default state when overflowing.");
- ok(navbar.customizationTarget.childElementCount < oldChildCount, "Should have fewer children.");
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should no longer have an overflowing toolbar.");
- is(navbar.currentSet, oldCurrentSet, "Currentset should still be the same now we're no longer overflowing.");
- ok(CustomizableUI.inDefaultState, "Should still be in default state now we're no longer overflowing.");
-
- // Verify actual physical placements match those of the placement array:
- let placementCounter = 0;
- let placements = CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR);
- for (let node of navbar.customizationTarget.childNodes) {
- if (node.getAttribute("skipintoolbarset") == "true") {
- continue;
- }
- is(placements[placementCounter++], node.id, "Nodes should match after overflow");
- }
- is(placements.length, placementCounter, "Should have as many nodes as expected");
- is(navbar.customizationTarget.childElementCount, oldChildCount, "Number of nodes should match");
-});
-
-// Enter and exit customization mode, check that currentSet works
-add_task(function*() {
- let oldCurrentSet = navbar.currentSet;
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
- yield startCustomizing();
- ok(CustomizableUI.inDefaultState, "Should be in default state in customization mode.");
- is(navbar.currentSet, oldCurrentSet, "Currentset should be the same in customization mode.");
- yield endCustomizing();
- ok(CustomizableUI.inDefaultState, "Should be in default state after customization mode.");
- is(navbar.currentSet, oldCurrentSet, "Currentset should be the same after customization mode.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js b/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js
deleted file mode 100644
index 35ba79bec..000000000
--- a/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-var overflowList = document.getElementById(navbar.getAttribute("overflowtarget"));
-
-const kTestBtn1 = "test-addWidgetToArea-overflow";
-const kTestBtn2 = "test-removeWidgetFromArea-overflow";
-const kTestBtn3 = "test-createWidget-overflow";
-const kHomeBtn = "home-button";
-const kDownloadsBtn = "downloads-button";
-const kSearchBox = "search-container";
-const kStarBtn = "bookmarks-menu-button";
-
-var originalWindowWidth;
-
-// Adding a widget should add it next to the widget it's being inserted next to.
-add_task(function*() {
- originalWindowWidth = window.outerWidth;
- createDummyXULButton(kTestBtn1, "Test");
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
-
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
- ok(!navbar.querySelector("#" + kHomeBtn), "Home button should no longer be in the navbar");
- let homeBtnNode = overflowList.querySelector("#" + kHomeBtn);
- ok(homeBtnNode, "Home button should be overflowing");
- ok(homeBtnNode && homeBtnNode.getAttribute("overflowedItem") == "true", "Home button should have overflowedItem attribute");
-
- let placementOfHomeButton = CustomizableUI.getWidgetIdsInArea(navbar.id).indexOf(kHomeBtn);
- CustomizableUI.addWidgetToArea(kTestBtn1, navbar.id, placementOfHomeButton);
- ok(!navbar.querySelector("#" + kTestBtn1), "New button should not be in the navbar");
- let newButtonNode = overflowList.querySelector("#" + kTestBtn1);
- ok(newButtonNode, "New button should be overflowing");
- ok(newButtonNode && newButtonNode.getAttribute("overflowedItem") == "true", "New button should have overflowedItem attribute");
- let nextEl = newButtonNode && newButtonNode.nextSibling;
- is(nextEl && nextEl.id, kHomeBtn, "Test button should be next to home button.");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar.");
- ok(navbar.querySelector("#" + kHomeBtn), "Home button should be in the navbar");
- ok(homeBtnNode && (homeBtnNode.getAttribute("overflowedItem") != "true"), "Home button should no longer have overflowedItem attribute");
- ok(!overflowList.querySelector("#" + kHomeBtn), "Home button should no longer be overflowing");
- ok(navbar.querySelector("#" + kTestBtn1), "Test button should be in the navbar");
- ok(!overflowList.querySelector("#" + kTestBtn1), "Test button should no longer be overflowing");
- ok(newButtonNode && (newButtonNode.getAttribute("overflowedItem") != "true"), "New button should no longer have overflowedItem attribute");
- let el = document.getElementById(kTestBtn1);
- if (el) {
- CustomizableUI.removeWidgetFromArea(kTestBtn1);
- el.remove();
- }
- window.resizeTo(originalWindowWidth, window.outerHeight);
-});
-
-// Removing a widget should remove it from the overflow list if that is where it is, and update it accordingly.
-add_task(function*() {
- createDummyXULButton(kTestBtn2, "Test");
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
- CustomizableUI.addWidgetToArea(kTestBtn2, navbar.id);
- ok(!navbar.hasAttribute("overflowing"), "Should still have a non-overflowing toolbar.");
-
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
- ok(!navbar.querySelector("#" + kTestBtn2), "Test button should not be in the navbar");
- ok(overflowList.querySelector("#" + kTestBtn2), "Test button should be overflowing");
-
- CustomizableUI.removeWidgetFromArea(kTestBtn2);
-
- ok(!overflowList.querySelector("#" + kTestBtn2), "Test button should not be overflowing.");
- ok(!navbar.querySelector("#" + kTestBtn2), "Test button should not be in the navbar");
- ok(gNavToolbox.palette.querySelector("#" + kTestBtn2), "Test button should be in the palette");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar.");
- let el = document.getElementById(kTestBtn2);
- if (el) {
- CustomizableUI.removeWidgetFromArea(kTestBtn2);
- el.remove();
- }
- window.resizeTo(originalWindowWidth, window.outerHeight);
-});
-
-// Constructing a widget while overflown should set the right class on it.
-add_task(function*() {
- originalWindowWidth = window.outerWidth;
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
-
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
- ok(!navbar.querySelector("#" + kHomeBtn), "Home button should no longer be in the navbar");
- let homeBtnNode = overflowList.querySelector("#" + kHomeBtn);
- ok(homeBtnNode, "Home button should be overflowing");
- ok(homeBtnNode && homeBtnNode.getAttribute("overflowedItem") == "true", "Home button should have overflowedItem class");
-
- let testBtnSpec = {id: kTestBtn3, label: "Overflowable widget test", defaultArea: "nav-bar"};
- CustomizableUI.createWidget(testBtnSpec);
- let testNode = overflowList.querySelector("#" + kTestBtn3);
- ok(testNode, "Test button should be overflowing");
- ok(testNode && testNode.getAttribute("overflowedItem") == "true", "Test button should have overflowedItem class");
-
- CustomizableUI.destroyWidget(kTestBtn3);
- testNode = document.getElementById(kTestBtn3);
- ok(!testNode, "Test button should be gone");
-
- CustomizableUI.createWidget(testBtnSpec);
- testNode = overflowList.querySelector("#" + kTestBtn3);
- ok(testNode, "Test button should be overflowing");
- ok(testNode && testNode.getAttribute("overflowedItem") == "true", "Test button should have overflowedItem class");
-
- CustomizableUI.removeWidgetFromArea(kTestBtn3);
- testNode = document.getElementById(kTestBtn3);
- ok(!testNode, "Test button should be gone");
- CustomizableUI.destroyWidget(kTestBtn3);
- window.resizeTo(originalWindowWidth, window.outerHeight);
-});
-
-add_task(function* asyncCleanup() {
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js b/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js
deleted file mode 100644
index b5757eabb..000000000
--- a/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js
+++ /dev/null
@@ -1,16 +0,0 @@
-/* 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/. */
-
-// Entering then exiting customization mode should reenable the Help and Exit buttons.
-add_task(function*() {
- yield startCustomizing();
- let helpButton = document.getElementById("PanelUI-help");
- let quitButton = document.getElementById("PanelUI-quit");
- ok(helpButton.getAttribute("disabled") == "true", "Help button should be disabled while in customization mode.");
- ok(quitButton.getAttribute("disabled") == "true", "Quit button should be disabled while in customization mode.");
- yield endCustomizing();
-
- ok(!helpButton.hasAttribute("disabled"), "Help button should not be disabled.");
- ok(!quitButton.hasAttribute("disabled"), "Quit button should not be disabled.");
-});
diff --git a/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js b/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js
deleted file mode 100644
index dffe388dc..000000000
--- a/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var navbar;
-var skippedItem;
-
-// Attempting to drag a skipintoolbarset item should work.
-add_task(function*() {
- navbar = document.getElementById("nav-bar");
- skippedItem = document.createElement("toolbarbutton");
- skippedItem.id = "test-skipintoolbarset-item";
- skippedItem.setAttribute("label", "Test");
- skippedItem.setAttribute("skipintoolbarset", "true");
- skippedItem.setAttribute("removable", "true");
- navbar.customizationTarget.appendChild(skippedItem);
- let downloadsButton = document.getElementById("downloads-button");
- yield startCustomizing();
- ok(CustomizableUI.inDefaultState, "Should still be in default state");
- simulateItemDrag(skippedItem, downloadsButton);
- ok(CustomizableUI.inDefaultState, "Should still be in default state");
- let skippedItemWrapper = skippedItem.parentNode;
- is(skippedItemWrapper.nextSibling && skippedItemWrapper.nextSibling.id,
- downloadsButton.parentNode.id, "Should be next to downloads button");
- simulateItemDrag(downloadsButton, skippedItem);
- let downloadWrapper = downloadsButton.parentNode;
- is(downloadWrapper.nextSibling && downloadWrapper.nextSibling.id,
- skippedItem.parentNode.id, "Should be next to skipintoolbarset item");
- ok(CustomizableUI.inDefaultState, "Should still be in default state");
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- skippedItem.remove();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js b/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js
deleted file mode 100644
index 87aca51eb..000000000
--- a/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Customize mode reset button should revert correctly
-add_task(function*() {
- yield startCustomizing();
- let devButton = document.getElementById("developer-button");
- let downloadsButton = document.getElementById("downloads-button");
- let searchBox = document.getElementById("search-container");
- let palette = document.getElementById("customization-palette");
- ok(devButton && downloadsButton && searchBox && palette, "Stuff should exist");
- simulateItemDrag(devButton, downloadsButton);
- simulateItemDrag(searchBox, palette);
- yield gCustomizeMode.reset();
- ok(CustomizableUI.inDefaultState, "Should be back in default state");
- yield endCustomizing();
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js b/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js
deleted file mode 100644
index d79f6e364..000000000
--- a/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kTestToolbarId = "test-empty-drag";
-
-// Attempting to drag an item to an empty container should work.
-add_task(function*() {
- yield createToolbarWithPlacements(kTestToolbarId, []);
- yield startCustomizing();
- let downloadButton = document.getElementById("downloads-button");
- let customToolbar = document.getElementById(kTestToolbarId);
- simulateItemDrag(downloadButton, customToolbar);
- assertAreaPlacements(kTestToolbarId, ["downloads-button"]);
- ok(downloadButton.parentNode && downloadButton.parentNode.parentNode == customToolbar,
- "Button should really be in toolbar");
- yield endCustomizing();
- removeCustomToolbars();
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js b/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js
deleted file mode 100644
index 3cbf6be42..000000000
--- a/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// There should be an advert to get more addons when the palette is empty.
-add_task(function*() {
- yield startCustomizing();
- let visiblePalette = document.getElementById("customization-palette");
- let emptyPaletteNotice = document.getElementById("customization-empty");
- is(emptyPaletteNotice.hidden, true, "The empty palette notice should not be shown when there are items in the palette.");
-
- while (visiblePalette.childElementCount) {
- gCustomizeMode.addToToolbar(visiblePalette.children[0]);
- }
- is(visiblePalette.childElementCount, 0, "There shouldn't be any items remaining in the visible palette.");
- is(emptyPaletteNotice.hidden, false, "The empty palette notice should be shown when there are no items in the palette.");
-
- yield endCustomizing();
- yield startCustomizing();
- visiblePalette = document.getElementById("customization-palette");
- emptyPaletteNotice = document.getElementById("customization-empty");
- is(emptyPaletteNotice.hidden, false,
- "The empty palette notice should be shown when there are no items in the palette and cust. mode is re-entered.");
-
- gCustomizeMode.removeFromArea(document.getElementById("wrapper-home-button"));
- is(emptyPaletteNotice.hidden, true,
- "The empty palette notice should not be shown when there is at least one item in the palette.");
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_934113_menubar_removable.js b/browser/components/customizableui/test/browser_934113_menubar_removable.js
deleted file mode 100644
index 1d788bced..000000000
--- a/browser/components/customizableui/test/browser_934113_menubar_removable.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Attempting to drag the menubar to the navbar shouldn't work.
-add_task(function*() {
- yield startCustomizing();
- let menuItems = document.getElementById("menubar-items");
- let navbar = document.getElementById("nav-bar");
- let menubar = document.getElementById("toolbar-menubar");
- // Force the menu to be shown.
- const kAutohide = menubar.getAttribute("autohide");
- menubar.setAttribute("autohide", "false");
- simulateItemDrag(menuItems, navbar.customizationTarget);
-
- is(getAreaWidgetIds("nav-bar").indexOf("menubar-items"), -1, "Menu bar shouldn't be in the navbar.");
- ok(!navbar.querySelector("#menubar-items"), "Shouldn't find menubar items in the navbar.");
- ok(menubar.querySelector("#menubar-items"), "Should find menubar items in the menubar.");
- isnot(getAreaWidgetIds("toolbar-menubar").indexOf("menubar-items"), -1,
- "Menubar items shouldn't be missing from the navbar.");
- menubar.setAttribute("autohide", kAutohide);
- yield endCustomizing();
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js b/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js
deleted file mode 100644
index dcc183051..000000000
--- a/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kTimeoutInMS = 20000;
-
-// Bug 934951 - Zoom controls percentage label doesn't update when it's in the toolbar and you navigate.
-add_task(function*() {
- CustomizableUI.addWidgetToArea("zoom-controls", CustomizableUI.AREA_NAVBAR);
- let tab1 = gBrowser.addTab("about:mozilla");
- yield BrowserTestUtils.browserLoaded(tab1.linkedBrowser);
- let tab2 = gBrowser.addTab("about:robots");
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
- gBrowser.selectedTab = tab1;
- let zoomResetButton = document.getElementById("zoom-reset-button");
-
- registerCleanupFunction(() => {
- info("Cleaning up.");
- CustomizableUI.reset();
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab1);
- });
-
- is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:mozilla");
- let zoomChangePromise = promiseObserverNotification("browser-fullZoom:zoomChange");
- FullZoom.enlarge();
- yield zoomChangePromise;
- is(parseInt(zoomResetButton.label, 10), 110, "Zoom is changed to 110% for about:mozilla");
-
- let tabSelectPromise = promiseTabSelect();
- gBrowser.selectedTab = tab2;
- yield tabSelectPromise;
- is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:robots");
-
- gBrowser.selectedTab = tab1;
- let zoomResetPromise = promiseObserverNotification("browser-fullZoom:zoomReset");
- FullZoom.reset();
- yield zoomResetPromise;
- is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:mozilla");
-
- // Test zoom label updates while navigating pages in the same tab.
- FullZoom.enlarge();
- yield zoomChangePromise;
- is(parseInt(zoomResetButton.label, 10), 110, "Zoom is changed to 110% for about:mozilla");
- let attributeChangePromise = promiseAttributeMutation(zoomResetButton, "label", (v) => {
- return parseInt(v, 10) == 100;
- });
- yield promiseTabLoadEvent(tab1, "about:home");
- yield attributeChangePromise;
- is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:home");
- yield promiseTabHistoryNavigation(-1, function() {
- return parseInt(zoomResetButton.label, 10) == 110;
- });
- is(parseInt(zoomResetButton.label, 10), 110, "Zoom is still 110% for about:mozilla");
- FullZoom.reset();
-});
-
-function promiseObserverNotification(aObserver) {
- let deferred = Promise.defer();
- function notificationCallback(e) {
- Services.obs.removeObserver(notificationCallback, aObserver, false);
- clearTimeout(timeoutId);
- deferred.resolve();
- }
- let timeoutId = setTimeout(() => {
- Services.obs.removeObserver(notificationCallback, aObserver, false);
- deferred.reject("Notification '" + aObserver + "' did not happen within 20 seconds.");
- }, kTimeoutInMS);
- Services.obs.addObserver(notificationCallback, aObserver, false);
- return deferred.promise;
-}
-
-function promiseTabSelect() {
- let deferred = Promise.defer();
- let container = window.gBrowser.tabContainer;
- let timeoutId = setTimeout(() => {
- container.removeEventListener("TabSelect", callback);
- deferred.reject("TabSelect did not happen within 20 seconds");
- }, kTimeoutInMS);
- function callback(e) {
- container.removeEventListener("TabSelect", callback);
- clearTimeout(timeoutId);
- executeSoon(deferred.resolve);
- }
- container.addEventListener("TabSelect", callback);
- return deferred.promise;
-}
diff --git a/browser/components/customizableui/test/browser_938980_navbar_collapsed.js b/browser/components/customizableui/test/browser_938980_navbar_collapsed.js
deleted file mode 100644
index fc7fa1a0a..000000000
--- a/browser/components/customizableui/test/browser_938980_navbar_collapsed.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-var bookmarksToolbar = document.getElementById("PersonalToolbar");
-var navbar = document.getElementById("nav-bar");
-var tabsToolbar = document.getElementById("TabsToolbar");
-
-// Customization reset should restore visibility to default-visible toolbars.
-add_task(function*() {
- is(navbar.collapsed, false, "Test should start with navbar visible");
- setToolbarVisibility(navbar, false);
- is(navbar.collapsed, true, "navbar should be hidden now");
-
- yield resetCustomization();
-
- is(navbar.collapsed, false, "Customization reset should restore visibility to the navbar");
-});
-
-// Customization reset should restore collapsed-state to default-collapsed toolbars.
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state");
-
- is(bookmarksToolbar.collapsed, true, "Test should start with bookmarks toolbar collapsed");
- ok(bookmarksToolbar.collapsed, "bookmarksToolbar should be collapsed");
- ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed");
- is(navbar.collapsed, false, "The nav-bar should be shown by default");
-
- setToolbarVisibility(bookmarksToolbar, true);
- setToolbarVisibility(navbar, false);
- ok(!bookmarksToolbar.collapsed, "bookmarksToolbar should be visible now");
- ok(navbar.collapsed, "navbar should be collapsed");
- is(CustomizableUI.inDefaultState, false, "Should no longer be in default state");
-
- yield startCustomizing();
- yield gCustomizeMode.reset();
- yield endCustomizing();
-
- is(bookmarksToolbar.collapsed, true, "Customization reset should restore collapsed-state to the bookmarks toolbar");
- ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed");
- ok(bookmarksToolbar.collapsed, "The bookmarksToolbar should be collapsed after reset");
- ok(CustomizableUI.inDefaultState, "Everything should be back to default state");
-});
-
-// Check that the menubar will be collapsed by resetting, if the platform supports it.
-add_task(function*() {
- let menubar = document.getElementById("toolbar-menubar");
- const canMenubarCollapse = CustomizableUI.isToolbarDefaultCollapsed(menubar.id);
- if (!canMenubarCollapse) {
- return;
- }
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state");
-
- is(menubar.getBoundingClientRect().height, 0, "menubar should be hidden by default");
- setToolbarVisibility(menubar, true);
- isnot(menubar.getBoundingClientRect().height, 0, "menubar should be visible now");
-
- yield startCustomizing();
- yield gCustomizeMode.reset();
-
- is(menubar.getAttribute("autohide"), "true", "The menubar should have autohide=true after reset in customization mode");
- is(menubar.getBoundingClientRect().height, 0, "The menubar should have height=0 after reset in customization mode");
-
- yield endCustomizing();
-
- is(menubar.getAttribute("autohide"), "true", "The menubar should have autohide=true after reset");
- is(menubar.getBoundingClientRect().height, 0, "The menubar should have height=0 after reset");
-});
-
-// Customization reset should restore collapsed-state to default-collapsed toolbars.
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state");
- ok(bookmarksToolbar.collapsed, "bookmarksToolbar should be collapsed");
- ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed");
-
- setToolbarVisibility(bookmarksToolbar, true);
- ok(!bookmarksToolbar.collapsed, "bookmarksToolbar should be visible now");
- is(CustomizableUI.inDefaultState, false, "Should no longer be in default state");
-
- yield startCustomizing();
-
- ok(!bookmarksToolbar.collapsed, "The bookmarksToolbar should be visible before reset");
- ok(!navbar.collapsed, "The navbar should be visible before reset");
- ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed");
-
- yield gCustomizeMode.reset();
-
- ok(bookmarksToolbar.collapsed, "The bookmarksToolbar should be collapsed after reset");
- ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed");
- ok(!navbar.collapsed, "The navbar should still be visible after reset");
- ok(CustomizableUI.inDefaultState, "Everything should be back to default state");
- yield endCustomizing();
-});
-
-// Check that the menubar will be collapsed by resetting, if the platform supports it.
-add_task(function*() {
- let menubar = document.getElementById("toolbar-menubar");
- const canMenubarCollapse = CustomizableUI.isToolbarDefaultCollapsed(menubar.id);
- if (!canMenubarCollapse) {
- return;
- }
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state");
- yield startCustomizing();
- let resetButton = document.getElementById("customization-reset-button");
- is(resetButton.disabled, true, "The reset button should be disabled when in default state");
-
- setToolbarVisibility(menubar, true);
- is(resetButton.disabled, false, "The reset button should be enabled when not in default state")
- ok(!CustomizableUI.inDefaultState, "No longer in default state when the menubar is shown");
-
- yield gCustomizeMode.reset();
-
- is(resetButton.disabled, true, "The reset button should be disabled when in default state");
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state");
-
- yield endCustomizing();
-});
diff --git a/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js b/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js
deleted file mode 100644
index 1f06c1aac..000000000
--- a/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-non-removable-widget";
-
-// Adding non-removable items to a toolbar or the panel shouldn't change inDefaultState
-add_task(function() {
- ok(CustomizableUI.inDefaultState, "Should start in default state");
-
- let button = createDummyXULButton(kWidgetId, "Test non-removable inDefaultState handling");
- CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR);
- button.setAttribute("removable", "false");
- ok(CustomizableUI.inDefaultState, "Should still be in default state after navbar addition");
- button.remove();
-
- button = createDummyXULButton(kWidgetId, "Test non-removable inDefaultState handling");
- CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_PANEL);
- button.setAttribute("removable", "false");
- ok(CustomizableUI.inDefaultState, "Should still be in default state after panel addition");
- button.remove();
- ok(CustomizableUI.inDefaultState, "Should be in default state after destroying both widgets");
-});
diff --git a/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js b/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js
deleted file mode 100644
index c554bffab..000000000
--- a/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarId = "test-registerToolbarNode-toolbar";
-const kButtonId = "test-registerToolbarNode-button";
-registerCleanupFunction(cleanup);
-
-// Registering a toolbar with defaultset attribute should work
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
- let btn = createDummyXULButton(kButtonId);
- let toolbar = document.createElement("toolbar");
- toolbar.id = kToolbarId;
- toolbar.setAttribute("customizable", true);
- toolbar.setAttribute("defaultset", kButtonId);
- gNavToolbox.appendChild(toolbar);
- ok(CustomizableUI.areas.indexOf(kToolbarId) != -1,
- "Toolbar should have been registered automatically.");
- is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR,
- "Area should be registered as toolbar");
- assertAreaPlacements(kToolbarId, [kButtonId]);
- ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible.");
- CustomizableUI.unregisterArea(kToolbarId, true);
- toolbar.remove();
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
- btn.remove();
-});
-
-// Registering a toolbar without a defaultset attribute should
-// wait for the registerArea call
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
- let btn = createDummyXULButton(kButtonId);
- let toolbar = document.createElement("toolbar");
- toolbar.id = kToolbarId;
- toolbar.setAttribute("customizable", true);
- gNavToolbox.appendChild(toolbar);
- ok(CustomizableUI.areas.indexOf(kToolbarId) == -1,
- "Toolbar should not yet have been registered automatically.");
- CustomizableUI.registerArea(kToolbarId, {defaultPlacements: [kButtonId]});
- ok(CustomizableUI.areas.indexOf(kToolbarId) != -1,
- "Toolbar should have been registered now.");
- is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR,
- "Area should be registered as toolbar");
- assertAreaPlacements(kToolbarId, [kButtonId]);
- ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible.");
- CustomizableUI.unregisterArea(kToolbarId, true);
- toolbar.remove();
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
- btn.remove();
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
-
-function cleanup() {
- let toolbar = document.getElementById(kToolbarId);
- if (toolbar) {
- toolbar.remove();
- }
- let btn = document.getElementById(kButtonId) ||
- gNavToolbox.querySelector("#" + kButtonId);
- if (btn) {
- btn.remove();
- }
-}
diff --git a/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js b/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js
deleted file mode 100644
index 944879a1b..000000000
--- a/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var button, menuButton;
-/* Clicking a button should close the panel */
-add_task(function*() {
- button = document.createElement("toolbarbutton");
- button.id = "browser_940307_button";
- button.setAttribute("label", "Button");
- PanelUI.contents.appendChild(button);
- yield PanelUI.show();
- let hiddenAgain = promisePanelHidden(window);
- EventUtils.synthesizeMouseAtCenter(button, {});
- yield hiddenAgain;
- button.remove();
-});
-
-/* Clicking a menu button should close the panel, opening the popup shouldn't. */
-add_task(function*() {
- menuButton = document.createElement("toolbarbutton");
- menuButton.setAttribute("type", "menu-button");
- menuButton.id = "browser_940307_menubutton";
- menuButton.setAttribute("label", "Menu button");
-
- let menuPopup = document.createElement("menupopup");
- menuPopup.id = "browser_940307_menupopup";
-
- let menuItem = document.createElement("menuitem");
- menuItem.setAttribute("label", "Menu item");
- menuItem.id = "browser_940307_menuitem";
-
- menuPopup.appendChild(menuItem);
- menuButton.appendChild(menuPopup);
- PanelUI.contents.appendChild(menuButton);
-
- yield PanelUI.show();
- let hiddenAgain = promisePanelHidden(window);
- let innerButton = document.getAnonymousElementByAttribute(menuButton, "anonid", "button");
- EventUtils.synthesizeMouseAtCenter(innerButton, {});
- yield hiddenAgain;
-
- // Now click the dropmarker to show the menu
- yield PanelUI.show();
- hiddenAgain = promisePanelHidden(window);
- let menuShown = promisePanelElementShown(window, menuPopup);
- let dropmarker = document.getAnonymousElementByAttribute(menuButton, "type", "menu-button");
- EventUtils.synthesizeMouseAtCenter(dropmarker, {});
- yield menuShown;
- // Panel should stay open:
- ok(isPanelUIOpen(), "Panel should still be open");
- let menuHidden = promisePanelElementHidden(window, menuPopup);
- // Then click the menu item to close all the things
- EventUtils.synthesizeMouseAtCenter(menuItem, {});
- yield menuHidden;
- yield hiddenAgain;
- menuButton.remove();
-});
-
-add_task(function*() {
- let searchbar = document.getElementById("searchbar");
- gCustomizeMode.addToPanel(searchbar);
- let placement = CustomizableUI.getPlacementOfWidget("search-container");
- is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel");
- yield PanelUI.show();
- yield waitForCondition(() => "value" in searchbar && searchbar.value === "");
-
- // Focusing a non-empty searchbox will cause us to open the
- // autocomplete panel and search for suggestions, which would
- // trigger network requests. Temporarily disable suggestions.
- yield SpecialPowers.pushPrefEnv({set: [["browser.search.suggest.enabled", false]]});
-
- searchbar.value = "foo";
- searchbar.focus();
- // Reaching into this context menu is pretty evil, but hey... it's a test.
- let textbox = document.getAnonymousElementByAttribute(searchbar.textbox, "anonid", "textbox-input-box");
- let contextmenu = document.getAnonymousElementByAttribute(textbox, "anonid", "input-box-contextmenu");
- let contextMenuShown = promisePanelElementShown(window, contextmenu);
- EventUtils.synthesizeMouseAtCenter(searchbar, {type: "contextmenu", button: 2});
- yield contextMenuShown;
-
- ok(isPanelUIOpen(), "Panel should still be open");
-
- let selectAll = contextmenu.querySelector("[cmd='cmd_selectAll']");
- let contextMenuHidden = promisePanelElementHidden(window, contextmenu);
- EventUtils.synthesizeMouseAtCenter(selectAll, {});
- yield contextMenuHidden;
-
- // Hide the suggestion panel.
- searchbar.textbox.popup.hidePopup();
-
- ok(isPanelUIOpen(), "Panel should still be open");
-
- let hiddenPanelPromise = promisePanelHidden(window);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield hiddenPanelPromise;
- ok(!isPanelUIOpen(), "Panel should no longer be open");
-
- // We focused the search bar earlier - ensure we don't keep doing that.
- gURLBar.select();
-
- CustomizableUI.reset();
-});
-
-add_task(function*() {
- button = document.createElement("toolbarbutton");
- button.id = "browser_946166_button_disabled";
- button.setAttribute("disabled", "true");
- button.setAttribute("label", "Button");
- PanelUI.contents.appendChild(button);
- yield PanelUI.show();
- EventUtils.synthesizeMouseAtCenter(button, {});
- is(PanelUI.panel.state, "open", "Popup stays open");
- button.removeAttribute("disabled");
- let hiddenAgain = promisePanelHidden(window);
- EventUtils.synthesizeMouseAtCenter(button, {});
- yield hiddenAgain;
- button.remove();
-});
-
-registerCleanupFunction(function() {
- if (button && button.parentNode) {
- button.remove();
- }
- if (menuButton && menuButton.parentNode) {
- menuButton.remove();
- }
- // Sadly this isn't task.jsm-enabled, so we can't wait for this to happen. But we should
- // definitely close it here and hope it won't interfere with other tests.
- // Of course, all the tests are meant to do this themselves, but if they fail...
- if (isPanelUIOpen()) {
- PanelUI.hide();
- }
-});
diff --git a/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js b/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js
deleted file mode 100644
index c81b004c1..000000000
--- a/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kTestBtnId = "test-removable-navbar-customize-mode";
-
-// Items without the removable attribute in the navbar should be considered non-removable
-add_task(function*() {
- let btn = createDummyXULButton(kTestBtnId, "Test removable in navbar in customize mode");
- document.getElementById("nav-bar").customizationTarget.appendChild(btn);
- yield startCustomizing();
- ok(!CustomizableUI.isWidgetRemovable(kTestBtnId), "Widget should not be considered removable");
- yield endCustomizing();
- document.getElementById(kTestBtnId).remove();
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js b/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js
deleted file mode 100644
index 1d7f86fd2..000000000
--- a/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// See https://bugzilla.mozilla.org/show_bug.cgi?id=941083
-
-const kWidgetId = "test-invalidate-wrapper-cache";
-
-// Check createWidget invalidates the widget cache
-add_task(function() {
- let groupWrapper = CustomizableUI.getWidget(kWidgetId);
- ok(groupWrapper, "Should get group wrapper.");
- let singleWrapper = groupWrapper.forWindow(window);
- ok(singleWrapper, "Should get single wrapper.");
-
- CustomizableUI.createWidget({id: kWidgetId, label: "Test invalidating widgets caching"});
-
- let newGroupWrapper = CustomizableUI.getWidget(kWidgetId);
- ok(newGroupWrapper, "Should get a group wrapper again.");
- isnot(newGroupWrapper, groupWrapper, "Wrappers shouldn't be the same.");
- isnot(newGroupWrapper.provider, groupWrapper.provider, "Wrapper providers shouldn't be the same.");
-
- let newSingleWrapper = newGroupWrapper.forWindow(window);
- isnot(newSingleWrapper, singleWrapper, "Single wrappers shouldn't be the same.");
- isnot(newSingleWrapper.provider, singleWrapper.provider, "Single wrapper providers shouldn't be the same.");
-
- CustomizableUI.destroyWidget(kWidgetId);
- ok(!CustomizableUI.getWidget(kWidgetId), "Shouldn't get a wrapper after destroying the widget.");
-});
diff --git a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js
deleted file mode 100644
index 61adac982..000000000
--- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarName = "test-unregisterArea-placements-toolbar";
-const kTestWidgetPfx = "test-widget-for-unregisterArea-placements-";
-const kTestWidgetCount = 3;
-registerCleanupFunction(removeCustomToolbars);
-
-// unregisterArea should keep placements by default and restore them when re-adding the area
-add_task(function*() {
- let widgetIds = [];
- for (let i = 0; i < kTestWidgetCount; i++) {
- let id = kTestWidgetPfx + i;
- widgetIds.push(id);
- let spec = {id: id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- }
- for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) {
- let id = kTestWidgetPfx + i;
- widgetIds.push(id);
- createDummyXULButton(id, "unregisterArea XUL test " + i);
- }
- let toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds);
- checkAbstractAndRealPlacements(toolbarNode, widgetIds);
-
- // Now move one of them:
- CustomizableUI.moveWidgetWithinArea(kTestWidgetPfx + kTestWidgetCount, 0);
- // Clone the array so we know this is the modified one:
- let modifiedWidgetIds = [...widgetIds];
- let movedWidget = modifiedWidgetIds.splice(kTestWidgetCount, 1)[0];
- modifiedWidgetIds.unshift(movedWidget);
-
- // Check it:
- checkAbstractAndRealPlacements(toolbarNode, modifiedWidgetIds);
-
- // Then unregister
- CustomizableUI.unregisterArea(kToolbarName);
-
- // Check we tell the outside world no dangerous things:
- checkWidgetFates(widgetIds);
- // Only then remove the real node
- toolbarNode.remove();
-
- // Now move one of the items to the palette, and another to the navbar:
- let lastWidget = modifiedWidgetIds.pop();
- CustomizableUI.removeWidgetFromArea(lastWidget);
- lastWidget = modifiedWidgetIds.pop();
- CustomizableUI.addWidgetToArea(lastWidget, CustomizableUI.AREA_NAVBAR);
-
- // Recreate ourselves with the default placements being the same:
- toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds);
- // Then check that after doing this, our actual placements match
- // the modified list, not the default one.
- checkAbstractAndRealPlacements(toolbarNode, modifiedWidgetIds);
-
- // Now remove completely:
- CustomizableUI.unregisterArea(kToolbarName, true);
- checkWidgetFates(modifiedWidgetIds);
- toolbarNode.remove();
-
- // One more time:
- // Recreate ourselves with the default placements being the same:
- toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds);
- // Should now be back to default:
- checkAbstractAndRealPlacements(toolbarNode, widgetIds);
- CustomizableUI.unregisterArea(kToolbarName, true);
- checkWidgetFates(widgetIds);
- toolbarNode.remove();
-
- // XXXgijs: ensure cleanup function doesn't barf:
- gAddedToolbars.delete(kToolbarName);
-
- // Remove all the XUL widgets, destroy the others:
- for (let widget of widgetIds) {
- let widgetWrapper = CustomizableUI.getWidget(widget);
- if (widgetWrapper.provider == CustomizableUI.PROVIDER_XUL) {
- gNavToolbox.palette.querySelector("#" + widget).remove();
- } else {
- CustomizableUI.destroyWidget(widget);
- }
- }
-});
-
-function checkAbstractAndRealPlacements(aNode, aExpectedPlacements) {
- assertAreaPlacements(kToolbarName, aExpectedPlacements);
- let physicalWidgetIds = Array.from(aNode.childNodes, (node) => node.id);
- placementArraysEqual(aNode.id, physicalWidgetIds, aExpectedPlacements);
-}
-
-function checkWidgetFates(aWidgetIds) {
- for (let widget of aWidgetIds) {
- ok(!CustomizableUI.getPlacementOfWidget(widget), "Widget should be in palette");
- ok(!document.getElementById(widget), "Widget should not be in the DOM");
- let widgetInPalette = !!gNavToolbox.palette.querySelector("#" + widget);
- let widgetProvider = CustomizableUI.getWidget(widget).provider;
- let widgetIsXULWidget = widgetProvider == CustomizableUI.PROVIDER_XUL;
- is(widgetInPalette, widgetIsXULWidget, "Just XUL Widgets should be in the palette");
- }
-}
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_943683_migration_test.js b/browser/components/customizableui/test/browser_943683_migration_test.js
deleted file mode 100644
index fe30df9e3..000000000
--- a/browser/components/customizableui/test/browser_943683_migration_test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-addonbar-migration";
-const kWidgetId2 = "test-addonbar-migration2";
-
-var addonbar = document.getElementById(CustomizableUI.AREA_ADDONBAR);
-var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
-var btn;
-var btn2;
-
-// Check we migrate normal stuff to the navbar
-add_task(function*() {
- btn = createDummyXULButton(kWidgetId, "Test");
- btn2 = createDummyXULButton(kWidgetId2, "Test2");
- addonbar.insertItem(btn.id);
- ok(btn.parentNode == navbar.customizationTarget, "Button should end up in navbar");
- let migrationArray = addonbar.getMigratedItems();
- is(migrationArray.length, 1, "Should have migrated 1 item");
- is(migrationArray[0], kWidgetId, "Should have migrated our 1 item");
-
- addonbar.currentSet = addonbar.currentSet + "," + kWidgetId2;
- ok(btn2.parentNode == navbar.customizationTarget, "Second button should end up in the navbar");
- migrationArray = addonbar.getMigratedItems();
- is(migrationArray.length, 2, "Should have migrated 2 items");
- isnot(migrationArray.indexOf(kWidgetId2), -1, "Should have migrated our second item");
-
- let otherWindow = yield openAndLoadWindow(undefined, true);
- try {
- let addonBar = otherWindow.document.getElementById("addon-bar");
- let otherMigrationArray = addonBar.getMigratedItems();
- is(migrationArray.length, otherMigrationArray.length,
- "Other window should have the same number of migrated items.");
- if (migrationArray.length == otherMigrationArray.length) {
- for (let widget of migrationArray) {
- isnot(otherMigrationArray.indexOf(widget), -1,
- "Migrated widget " + widget + " should also be listed as migrated in the other window.");
- }
- }
- } finally {
- yield promiseWindowClosed(otherWindow);
- }
- btn.remove();
- btn2.remove();
- CustomizableUI.reset();
-});
diff --git a/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js b/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js
deleted file mode 100644
index a724b0c7f..000000000
--- a/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-destroy-in-palette";
-
-// Check destroyWidget destroys the node if it's in the palette
-add_task(function*() {
- CustomizableUI.createWidget({id: kWidgetId, label: "Test destroying widgets in palette."});
- yield startCustomizing();
- yield endCustomizing();
- ok(gNavToolbox.palette.querySelector("#" + kWidgetId), "Widget still exists in palette.");
- CustomizableUI.destroyWidget(kWidgetId);
- ok(!gNavToolbox.palette.querySelector("#" + kWidgetId), "Widget no longer exists in palette.");
-});
diff --git a/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js b/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js
deleted file mode 100644
index 6b8acbee0..000000000
--- a/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kWidgetId = "test-private-browsing-customize-mode-widget";
-
-// Add a widget via the API with showInPrivateBrowsing set to false
-// and ensure it does not appear in the list of unused widgets in private
-// windows.
-add_task(function* testPrivateBrowsingCustomizeModeWidget() {
- CustomizableUI.createWidget({
- id: kWidgetId,
- showInPrivateBrowsing: false
- });
-
- let normalWidgetArray = CustomizableUI.getUnusedWidgets(gNavToolbox.palette);
- normalWidgetArray = normalWidgetArray.map((w) => w.id);
- ok(normalWidgetArray.indexOf(kWidgetId) > -1,
- "Widget should appear as unused in non-private window");
-
- let privateWindow = yield openAndLoadWindow({private: true});
- let privateWidgetArray = CustomizableUI.getUnusedWidgets(privateWindow.gNavToolbox.palette);
- privateWidgetArray = privateWidgetArray.map((w) => w.id);
- is(privateWidgetArray.indexOf(kWidgetId), -1,
- "Widget should not appear as unused in private window");
- yield promiseWindowClosed(privateWindow);
-
- CustomizableUI.destroyWidget(kWidgetId);
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_addons.js b/browser/components/customizableui/test/browser_947914_button_addons.js
deleted file mode 100644
index b942ee771..000000000
--- a/browser/components/customizableui/test/browser_947914_button_addons.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialLocation = gBrowser.currentURI.spec;
-var newTab = null;
-
-add_task(function*() {
- info("Check addons button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let addonsButton = document.getElementById("add-ons-button");
- ok(addonsButton, "Add-ons button exists in Panel Menu");
- addonsButton.click();
-
- newTab = gBrowser.selectedTab;
- yield waitForCondition(() => gBrowser.currentURI &&
- gBrowser.currentURI.spec == "about:addons");
-
- let addonsPage = gBrowser.selectedBrowser.contentWindow.document.
- getElementById("addons-page");
- ok(addonsPage, "Add-ons page was opened");
-});
-
-add_task(function* asyncCleanup() {
- gBrowser.addTab(initialLocation);
- gBrowser.removeTab(gBrowser.selectedTab);
- info("Tabs were restored");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_copy.js b/browser/components/customizableui/test/browser_947914_button_copy.js
deleted file mode 100644
index c778c956f..000000000
--- a/browser/components/customizableui/test/browser_947914_button_copy.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialLocation = gBrowser.currentURI.spec;
-var globalClipboard;
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() {
- info("Check copy button existence and functionality");
-
- let testText = "copy text test";
-
- gURLBar.focus();
- info("The URL bar was focused");
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let copyButton = document.getElementById("copy-button");
- ok(copyButton, "Copy button exists in Panel Menu");
- ok(copyButton.getAttribute("disabled"), "Copy button is initially disabled");
-
- // copy text from URL bar
- gURLBar.value = testText;
- gURLBar.focus();
- gURLBar.select();
- yield PanelUI.show();
- info("Menu panel was opened");
-
- ok(!copyButton.hasAttribute("disabled"), "Copy button is enabled when selecting");
-
- copyButton.click();
- is(gURLBar.value, testText, "Selected text is unaltered when clicking copy");
-
- // check that the text was added to the clipboard
- let clipboard = Services.clipboard;
- let transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
- globalClipboard = clipboard.kGlobalClipboard;
-
- transferable.init(null);
- transferable.addDataFlavor("text/unicode");
- clipboard.getData(transferable, globalClipboard);
- let str = {}, strLength = {};
- transferable.getTransferData("text/unicode", str, strLength);
- let clipboardValue = "";
-
- if (str.value) {
- str.value.QueryInterface(Ci.nsISupportsString);
- clipboardValue = str.value.data;
- }
- is(clipboardValue, testText, "Data was copied to the clipboard.");
- });
-});
-
-registerCleanupFunction(function cleanup() {
- Services.clipboard.emptyClipboard(globalClipboard);
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_cut.js b/browser/components/customizableui/test/browser_947914_button_cut.js
deleted file mode 100644
index e6e614368..000000000
--- a/browser/components/customizableui/test/browser_947914_button_cut.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialLocation = gBrowser.currentURI.spec;
-var globalClipboard;
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() {
- info("Check cut button existence and functionality");
-
- let testText = "cut text test";
-
- gURLBar.focus();
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let cutButton = document.getElementById("cut-button");
- ok(cutButton, "Cut button exists in Panel Menu");
- ok(cutButton.hasAttribute("disabled"), "Cut button is disabled");
-
- // cut text from URL bar
- gURLBar.value = testText;
- gURLBar.focus();
- gURLBar.select();
- yield PanelUI.show();
- info("Menu panel was opened");
-
- ok(!cutButton.hasAttribute("disabled"), "Cut button is enabled when selecting");
- cutButton.click();
- is(gURLBar.value, "", "Selected text is removed from source when clicking on cut");
-
- // check that the text was added to the clipboard
- let clipboard = Services.clipboard;
- let transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
- globalClipboard = clipboard.kGlobalClipboard;
-
- transferable.init(null);
- transferable.addDataFlavor("text/unicode");
- clipboard.getData(transferable, globalClipboard);
- let str = {}, strLength = {};
- transferable.getTransferData("text/unicode", str, strLength);
- let clipboardValue = "";
-
- if (str.value) {
- str.value.QueryInterface(Ci.nsISupportsString);
- clipboardValue = str.value.data;
- }
- is(clipboardValue, testText, "Data was copied to the clipboard.");
- });
-});
-
-registerCleanupFunction(function cleanup() {
- Services.clipboard.emptyClipboard(globalClipboard);
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_find.js b/browser/components/customizableui/test/browser_947914_button_find.js
deleted file mode 100644
index cf3b79e34..000000000
--- a/browser/components/customizableui/test/browser_947914_button_find.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check find button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let findButton = document.getElementById("find-button");
- ok(findButton, "Find button exists in Panel Menu");
-
- findButton.click();
- ok(!gFindBar.hasAttribute("hidden"), "Findbar opened successfully");
-
- // close find bar
- gFindBar.close();
- info("Findbar was closed");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_history.js b/browser/components/customizableui/test/browser_947914_button_history.js
deleted file mode 100644
index 64080fcc3..000000000
--- a/browser/components/customizableui/test/browser_947914_button_history.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check history button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let historyButton = document.getElementById("history-panelmenu");
- ok(historyButton, "History button appears in Panel Menu");
-
- historyButton.click();
- let historyPanel = document.getElementById("PanelUI-history");
- ok(historyPanel.getAttribute("current"), "History Panel is in view");
-
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise
- info("Menu panel was closed");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js
deleted file mode 100644
index c2006bef0..000000000
--- a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check private browsing button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let windowWasHandled = false;
- let privateWindow = null;
-
- let observerWindowOpened = {
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- privateWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
- privateWindow.addEventListener("load", function newWindowHandler() {
- privateWindow.removeEventListener("load", newWindowHandler, false);
- is(privateWindow.location.href, "chrome://browser/content/browser.xul",
- "A new browser window was opened");
- ok(PrivateBrowsingUtils.isWindowPrivate(privateWindow), "Window is private");
- windowWasHandled = true;
- }, false);
- }
- }
- }
-
- Services.ww.registerNotification(observerWindowOpened);
-
- let privateBrowsingButton = document.getElementById("privatebrowsing-button");
- ok(privateBrowsingButton, "Private browsing button exists in Panel Menu");
- privateBrowsingButton.click();
-
- try {
- yield waitForCondition(() => windowWasHandled);
- yield promiseWindowClosed(privateWindow);
- info("The new private window was closed");
- }
- catch (e) {
- ok(false, "The new private browser window was not properly handled");
- }
- finally {
- Services.ww.unregisterNotification(observerWindowOpened);
- }
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_newWindow.js b/browser/components/customizableui/test/browser_947914_button_newWindow.js
deleted file mode 100644
index 47162ee86..000000000
--- a/browser/components/customizableui/test/browser_947914_button_newWindow.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check new window button existence and functionality");
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let windowWasHandled = false;
- let newWindow = null;
-
- let observerWindowOpened = {
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- newWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
- newWindow.addEventListener("load", function newWindowHandler() {
- newWindow.removeEventListener("load", newWindowHandler, false);
- is(newWindow.location.href, "chrome://browser/content/browser.xul",
- "A new browser window was opened");
- ok(!PrivateBrowsingUtils.isWindowPrivate(newWindow), "Window is not private");
- windowWasHandled = true;
- }, false);
- }
- }
- }
-
- Services.ww.registerNotification(observerWindowOpened);
-
- let newWindowButton = document.getElementById("new-window-button");
- ok(newWindowButton, "New Window button exists in Panel Menu");
- newWindowButton.click();
-
- try {
- yield waitForCondition(() => windowWasHandled);
- yield promiseWindowClosed(newWindow);
- info("The new window was closed");
- }
- catch (e) {
- ok(false, "The new browser window was not properly handled");
- }
- finally {
- Services.ww.unregisterNotification(observerWindowOpened);
- }
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_paste.js b/browser/components/customizableui/test/browser_947914_button_paste.js
deleted file mode 100644
index fc83ead56..000000000
--- a/browser/components/customizableui/test/browser_947914_button_paste.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialLocation = gBrowser.currentURI.spec;
-var globalClipboard;
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() {
- info("Check paste button existence and functionality");
-
- let clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
- globalClipboard = Services.clipboard.kGlobalClipboard;
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let pasteButton = document.getElementById("paste-button");
- ok(pasteButton, "Paste button exists in Panel Menu");
-
- // add text to clipboard
- let text = "Sample text for testing";
- clipboard.copyString(text);
-
- // test paste button by pasting text to URL bar
- gURLBar.focus();
- yield PanelUI.show();
- info("Menu panel was opened");
-
- ok(!pasteButton.hasAttribute("disabled"), "Paste button is enabled");
- pasteButton.click();
-
- is(gURLBar.value, text, "Text pasted successfully");
- });
-});
-
-registerCleanupFunction(function cleanup() {
- Services.clipboard.emptyClipboard(globalClipboard);
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_print.js b/browser/components/customizableui/test/browser_947914_button_print.js
deleted file mode 100644
index af7abcaeb..000000000
--- a/browser/components/customizableui/test/browser_947914_button_print.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const isOSX = (Services.appinfo.OS === "Darwin");
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/",
- }, function* () {
- info("Check print button existence and functionality");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- yield waitForCondition(() => document.getElementById("print-button") != null);
-
- let printButton = document.getElementById("print-button");
- ok(printButton, "Print button exists in Panel Menu");
-
- if (isOSX) {
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- info("Menu panel was closed");
- }
- else {
- printButton.click();
- yield waitForCondition(() => gInPrintPreviewMode);
-
- ok(gInPrintPreviewMode, "Entered print preview mode");
-
- // close print preview
- if (gInPrintPreviewMode) {
- PrintUtils.exitPrintPreview();
- yield waitForCondition(() => !window.gInPrintPreviewMode);
- info("Exited print preview")
- }
- }
- });
-});
-
diff --git a/browser/components/customizableui/test/browser_947914_button_savePage.js b/browser/components/customizableui/test/browser_947914_button_savePage.js
deleted file mode 100644
index 543ff3ca6..000000000
--- a/browser/components/customizableui/test/browser_947914_button_savePage.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- info("Check save page button existence");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let savePageButton = document.getElementById("save-page-button");
- ok(savePageButton, "Save Page button exists in Panel Menu");
-
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- info("Menu panel was closed");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_zoomIn.js b/browser/components/customizableui/test/browser_947914_button_zoomIn.js
deleted file mode 100644
index 4463d87d6..000000000
--- a/browser/components/customizableui/test/browser_947914_button_zoomIn.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialPageZoom = ZoomManager.zoom;
-
-add_task(function*() {
- info("Check zoom in button existence and functionality");
-
- is(initialPageZoom, 1, "Initial zoom factor should be 1");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let zoomInButton = document.getElementById("zoom-in-button");
- ok(zoomInButton, "Zoom in button exists in Panel Menu");
-
- zoomInButton.click();
- let pageZoomLevel = parseInt(ZoomManager.zoom * 100);
- let zoomResetButton = document.getElementById("zoom-reset-button");
- let expectedZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10);
- ok(pageZoomLevel > 100 && pageZoomLevel == expectedZoomLevel, "Page zoomed in correctly");
-
- // close the Panel
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- info("Menu panel was closed");
-});
-
-add_task(function* asyncCleanup() {
- // reset zoom level
- ZoomManager.zoom = initialPageZoom;
- info("Zoom level was restored");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_zoomOut.js b/browser/components/customizableui/test/browser_947914_button_zoomOut.js
deleted file mode 100644
index f9f51ac9a..000000000
--- a/browser/components/customizableui/test/browser_947914_button_zoomOut.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialPageZoom = ZoomManager.zoom;
-
-add_task(function*() {
- info("Check zoom out button existence and functionality");
-
- is(initialPageZoom, 1, "Initial zoom factor should be 1");
-
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let zoomOutButton = document.getElementById("zoom-out-button");
- ok(zoomOutButton, "Zoom out button exists in Panel Menu");
-
- zoomOutButton.click();
- let pageZoomLevel = Math.round(ZoomManager.zoom * 100);
-
- let zoomResetButton = document.getElementById("zoom-reset-button");
- let expectedZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10);
- ok(pageZoomLevel < 100 && pageZoomLevel == expectedZoomLevel, "Page zoomed out correctly");
-
- // close the panel
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- info("Menu panel was closed");
-});
-
-add_task(function* asyncCleanup() {
- // reset zoom level
- ZoomManager.zoom = initialPageZoom;
- info("Zoom level was restored");
-});
diff --git a/browser/components/customizableui/test/browser_947914_button_zoomReset.js b/browser/components/customizableui/test/browser_947914_button_zoomReset.js
deleted file mode 100644
index 372097665..000000000
--- a/browser/components/customizableui/test/browser_947914_button_zoomReset.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialPageZoom = ZoomManager.zoom;
-
-add_task(function*() {
- info("Check zoom reset button existence and functionality");
-
- is(initialPageZoom, 1, "Page zoom reset correctly");
- ZoomManager.zoom = 0.5;
- yield PanelUI.show();
- info("Menu panel was opened");
-
- let zoomResetButton = document.getElementById("zoom-reset-button");
- ok(zoomResetButton, "Zoom reset button exists in Panel Menu");
-
- zoomResetButton.click();
- yield new Promise(SimpleTest.executeSoon);
-
- let pageZoomLevel = Math.floor(ZoomManager.zoom * 100);
- let expectedZoomLevel = 100;
- let buttonZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10);
- is(pageZoomLevel, expectedZoomLevel, "Page zoom reset correctly");
- is(pageZoomLevel, buttonZoomLevel, "Button displays the correct zoom level");
-
- // close the panel
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- info("Menu panel was closed");
-});
-
-add_task(function* asyncCleanup() {
- // reset zoom level
- ZoomManager.zoom = initialPageZoom;
- info("Zoom level was restored");
-});
diff --git a/browser/components/customizableui/test/browser_947987_removable_default.js b/browser/components/customizableui/test/browser_947987_removable_default.js
deleted file mode 100644
index 98325ec2a..000000000
--- a/browser/components/customizableui/test/browser_947987_removable_default.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var kWidgetId = "test-removable-widget-default";
-const kNavBar = CustomizableUI.AREA_NAVBAR;
-var widgetCounter = 0;
-
-registerCleanupFunction(removeCustomToolbars);
-
-// Sanity checks
-add_task(function() {
- let brokenSpec = {id: kWidgetId + (widgetCounter++), removable: false};
- SimpleTest.doesThrow(() => CustomizableUI.createWidget(brokenSpec),
- "Creating non-removable widget without defaultArea should throw.");
-
- // Widget without removable set should be removable:
- let wrapper = CustomizableUI.createWidget({id: kWidgetId + (widgetCounter++)});
- ok(CustomizableUI.isWidgetRemovable(wrapper.id), "Should be removable by default.");
- CustomizableUI.destroyWidget(wrapper.id);
-});
-
-// Test non-removable widget with defaultArea
-add_task(function*() {
- // Non-removable widget with defaultArea should work:
- let spec = {id: kWidgetId + (widgetCounter++), removable: false,
- defaultArea: kNavBar};
- let widgetWrapper;
- try {
- widgetWrapper = CustomizableUI.createWidget(spec);
- } catch (ex) {
- ok(false, "Creating a non-removable widget with a default area should not throw.");
- return;
- }
-
- let placement = CustomizableUI.getPlacementOfWidget(spec.id);
- ok(placement, "Widget should be placed.");
- is(placement.area, kNavBar, "Widget should be in navbar");
- let singleWrapper = widgetWrapper.forWindow(window);
- ok(singleWrapper, "Widget should exist in window.");
- ok(singleWrapper.node, "Widget node should exist in window.");
- let expectedParent = CustomizableUI.getCustomizeTargetForArea(kNavBar, window);
- is(singleWrapper.node.parentNode, expectedParent, "Widget should be in navbar.");
-
- let otherWin = yield openAndLoadWindow(true);
- placement = CustomizableUI.getPlacementOfWidget(spec.id);
- ok(placement, "Widget should be placed.");
- is(placement && placement.area, kNavBar, "Widget should be in navbar");
-
- singleWrapper = widgetWrapper.forWindow(otherWin);
- ok(singleWrapper, "Widget should exist in other window.");
- if (singleWrapper) {
- ok(singleWrapper.node, "Widget node should exist in other window.");
- if (singleWrapper.node) {
- let expectedParent = CustomizableUI.getCustomizeTargetForArea(kNavBar, otherWin);
- is(singleWrapper.node.parentNode, expectedParent,
- "Widget should be in navbar in other window.");
- }
- }
- CustomizableUI.destroyWidget(spec.id);
- yield promiseWindowClosed(otherWin);
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js b/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js
deleted file mode 100644
index 456c9ed02..000000000
--- a/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* 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/. */
-
-const kWidgetId = "test-destroy-non-removable-defaultArea";
-
-add_task(function() {
- let spec = {id: kWidgetId, label: "Test non-removable defaultArea re-adding.",
- removable: false, defaultArea: CustomizableUI.AREA_NAVBAR};
- CustomizableUI.createWidget(spec);
- let placement = CustomizableUI.getPlacementOfWidget(kWidgetId);
- ok(placement, "Should have placed the widget.");
- is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar");
- CustomizableUI.destroyWidget(kWidgetId);
- CustomizableUI.removeWidgetFromArea(kWidgetId);
-
- CustomizableUI.createWidget(spec);
- ok(placement, "Should have placed the widget.");
- is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar");
- CustomizableUI.destroyWidget(kWidgetId);
- CustomizableUI.removeWidgetFromArea(kWidgetId);
-
- const kPrefCustomizationAutoAdd = "browser.uiCustomization.autoAdd";
- Services.prefs.setBoolPref(kPrefCustomizationAutoAdd, false);
- CustomizableUI.createWidget(spec);
- ok(placement, "Should have placed the widget.");
- is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar");
- CustomizableUI.destroyWidget(kWidgetId);
- CustomizableUI.removeWidgetFromArea(kWidgetId);
- Services.prefs.clearUserPref(kPrefCustomizationAutoAdd);
-});
-
diff --git a/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js b/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js
deleted file mode 100644
index fc05a99fd..000000000
--- a/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarName = "test-unregisterArea-areaType";
-const kUnregisterAreaTestWidget = "test-widget-for-unregisterArea-areaType";
-const kTestWidget = "test-widget-no-area-areaType";
-registerCleanupFunction(removeCustomToolbars);
-
-function checkAreaType(widget) {
- try {
- is(widget.areaType, null, "areaType should be null");
- } catch (ex) {
- info("Fetching areaType threw: " + ex);
- ok(false, "areaType getter shouldn't throw.");
- }
-}
-
-// widget wrappers in unregisterArea'd areas and nowhere shouldn't throw when checking areaTypes.
-add_task(function*() {
- // Using the ID before it's been created will imply a XUL wrapper; we'll test
- // an API-based wrapper below
- let toolbarNode = createToolbarWithPlacements(kToolbarName, [kUnregisterAreaTestWidget]);
- CustomizableUI.unregisterArea(kToolbarName);
- toolbarNode.remove();
-
- let w = CustomizableUI.getWidget(kUnregisterAreaTestWidget);
- checkAreaType(w);
-
- w = CustomizableUI.getWidget(kTestWidget);
- checkAreaType(w);
-
- let spec = {id: kUnregisterAreaTestWidget, type: 'button', removable: true,
- label: "areaType test", tooltiptext: "areaType test"};
- CustomizableUI.createWidget(spec);
- toolbarNode = createToolbarWithPlacements(kToolbarName, [kUnregisterAreaTestWidget]);
- CustomizableUI.unregisterArea(kToolbarName);
- toolbarNode.remove();
- w = CustomizableUI.getWidget(spec.id);
- checkAreaType(w);
- CustomizableUI.removeWidgetFromArea(kUnregisterAreaTestWidget);
- checkAreaType(w);
- // XXXgijs: ensure cleanup function doesn't barf:
- gAddedToolbars.delete(kToolbarName);
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
-
diff --git a/browser/components/customizableui/test/browser_956602_remove_special_widget.js b/browser/components/customizableui/test/browser_956602_remove_special_widget.js
deleted file mode 100644
index f87b2e4c8..000000000
--- a/browser/components/customizableui/test/browser_956602_remove_special_widget.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-
-// Adding a separator and then dragging it out of the navbar shouldn't throw
-add_task(function*() {
- try {
- let navbar = document.getElementById("nav-bar");
- let separatorSelector = "toolbarseparator[id^=customizableui-special-separator]";
- ok(!navbar.querySelector(separatorSelector), "Shouldn't be a separator in the navbar");
- CustomizableUI.addWidgetToArea('separator', 'nav-bar');
- yield startCustomizing();
- let separator = navbar.querySelector(separatorSelector);
- ok(separator, "There should be a separator in the navbar now.");
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(separator, palette);
- ok(!palette.querySelector(separatorSelector), "No separator in the palette.");
- } catch (ex) {
- Cu.reportError(ex);
- ok(false, "Shouldn't throw an exception moving an item to the navbar.");
- } finally {
- yield endCustomizing();
- }
-});
-
-add_task(function* asyncCleanup() {
- resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js b/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js
deleted file mode 100644
index 7c4f6cfa4..000000000
--- a/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var originalWindowWidth;
-
-// Drag to overflow chevron should open the overflow panel.
-add_task(function*() {
- originalWindowWidth = window.outerWidth;
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
- ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- let widgetOverflowPanel = document.getElementById("widget-overflow");
- let panelShownPromise = promisePanelElementShown(window, widgetOverflowPanel);
- let identityBox = document.getElementById("identity-box");
- let overflowChevron = document.getElementById("nav-bar-overflow-button");
-
- // Listen for hiding immediately so we don't miss the event because of the
- // async-ness of the 'shown' yield...
- let panelHiddenPromise = promisePanelElementHidden(window, widgetOverflowPanel);
-
- var ds = Components.classes["@mozilla.org/widget/dragservice;1"].
- getService(Components.interfaces.nsIDragService);
-
- ds.startDragSession();
- try {
- var [result, dataTransfer] = EventUtils.synthesizeDragOver(identityBox, overflowChevron);
-
- // Wait for showing panel before ending drag session.
- yield panelShownPromise;
-
- EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, overflowChevron);
- } finally {
- ds.endDragSession(true);
- }
-
- info("Overflow panel is shown.");
-
- widgetOverflowPanel.hidePopup();
- yield panelHiddenPromise;
-});
-
-add_task(function*() {
- window.resizeTo(originalWindowWidth, window.outerHeight);
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
- ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar.");
-});
diff --git a/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js b/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js
deleted file mode 100644
index cf2603999..000000000
--- a/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- const kNormalLabel = "Character Encoding";
- CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_NAVBAR);
- let characterEncoding = document.getElementById("characterencoding-button");
- const kOriginalLabel = characterEncoding.getAttribute("label");
- characterEncoding.setAttribute("label", "\u00ad" + kNormalLabel);
- CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_PANEL);
-
- yield PanelUI.show();
-
- is(characterEncoding.getAttribute("auto-hyphens"), "off",
- "Hyphens should be disabled if the &shy; character is present in the label");
- let multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text");
- let multilineTextCS = getComputedStyle(multilineText);
- is(multilineTextCS.MozHyphens, "manual", "-moz-hyphens should be set to manual when the &shy; character is present.")
-
- let hiddenPanelPromise = promisePanelHidden(window);
- PanelUI.toggle();
- yield hiddenPanelPromise;
-
- characterEncoding.setAttribute("label", kNormalLabel);
-
- yield PanelUI.show();
-
- isnot(characterEncoding.getAttribute("auto-hyphens"), "off",
- "Hyphens should not be disabled if the &shy; character is not present in the label");
- multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text");
- multilineTextCS = getComputedStyle(multilineText);
- is(multilineTextCS.MozHyphens, "auto", "-moz-hyphens should be set to auto by default.")
-
- hiddenPanelPromise = promisePanelHidden(window);
- PanelUI.toggle();
- yield hiddenPanelPromise;
-
- characterEncoding.setAttribute("label", "\u00ad" + kNormalLabel);
- CustomizableUI.removeWidgetFromArea("characterencoding-button");
- yield startCustomizing();
-
- isnot(characterEncoding.getAttribute("auto-hyphens"), "off",
- "Hyphens should not be disabled when the widget is in the palette");
-
- gCustomizeMode.addToPanel(characterEncoding);
- is(characterEncoding.getAttribute("auto-hyphens"), "off",
- "Hyphens should be disabled if the &shy; character is present in the label in customization mode");
- multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text");
- multilineTextCS = getComputedStyle(multilineText);
- is(multilineTextCS.MozHyphens, "manual", "-moz-hyphens should be set to manual when the &shy; character is present in customization mode.")
-
- yield endCustomizing();
-
- CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_NAVBAR);
- ok(!characterEncoding.hasAttribute("auto-hyphens"),
- "Removing the widget from the panel should remove the auto-hyphens attribute");
-
- characterEncoding.setAttribute("label", kOriginalLabel);
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js b/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js
deleted file mode 100644
index e5710c50a..000000000
--- a/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbar = "test-toolbar-963639-non-customizable-customizing-attribute";
-
-add_task(function*() {
- info("Test for Bug 963639 - CustomizeMode _onToolbarVisibilityChange sets @customizing on non-customizable toolbars");
-
- let toolbar = document.createElement("toolbar");
- toolbar.id = kToolbar;
- gNavToolbox.appendChild(toolbar);
-
- let testToolbar = document.getElementById(kToolbar)
- ok(testToolbar, "Toolbar was created.");
- is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 1,
- "Toolbar was added to the navigator toolbox");
-
- toolbar.setAttribute("toolbarname", "NonCustomizableToolbarCustomizingAttribute");
- toolbar.setAttribute("collapsed", "true");
-
- yield startCustomizing();
- window.setToolbarVisibility(toolbar, "true");
- isnot(toolbar.getAttribute("customizing"), "true",
- "Toolbar doesn't have the customizing attribute");
-
- yield endCustomizing();
- gNavToolbox.removeChild(toolbar);
-
- is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 0,
- "Toolbar was removed from the navigator toolbox");
-});
diff --git a/browser/components/customizableui/test/browser_967000_button_charEncoding.js b/browser/components/customizableui/test/browser_967000_button_charEncoding.js
deleted file mode 100644
index 0688ebbd6..000000000
--- a/browser/components/customizableui/test/browser_967000_button_charEncoding.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/customizableui/test/support/test_967000_charEncoding_page.html";
-
-add_task(function*() {
- info("Check Character Encoding button functionality");
-
- // add the Character Encoding button to the panel
- CustomizableUI.addWidgetToArea("characterencoding-button",
- CustomizableUI.AREA_PANEL);
-
- // check the button's functionality
- yield PanelUI.show();
-
- let charEncodingButton = document.getElementById("characterencoding-button");
- ok(charEncodingButton, "The Character Encoding button was added to the Panel Menu");
- is(charEncodingButton.getAttribute("disabled"), "true",
- "The Character encoding button is initially disabled");
-
- let panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
-
- let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_PAGE, true, true);
-
- yield PanelUI.show();
- ok(!charEncodingButton.hasAttribute("disabled"), "The Character encoding button gets enabled");
- let characterEncodingView = document.getElementById("PanelUI-characterEncodingView");
- let subviewShownPromise = subviewShown(characterEncodingView);
- charEncodingButton.click();
- yield subviewShownPromise;
-
- ok(characterEncodingView.hasAttribute("current"), "The Character encoding panel is displayed");
-
- let pinnedEncodings = document.getElementById("PanelUI-characterEncodingView-pinned");
- let charsetsList = document.getElementById("PanelUI-characterEncodingView-charsets");
- ok(pinnedEncodings, "Pinned charsets are available");
- ok(charsetsList, "Charsets list is available");
-
- let checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']");
- is(checkedButtons.length, 2, "There should be 2 checked items (1 charset, 1 detector).");
- is(checkedButtons[0].getAttribute("label"), "Unicode", "The unicode encoding is correctly selected");
- is(characterEncodingView.querySelectorAll("#PanelUI-characterEncodingView-autodetect toolbarbutton[checked='true']").length,
- 1,
- "There should be 1 checked detector.");
-
- panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
-
- yield BrowserTestUtils.removeTab(newTab);
-});
-
-add_task(function* asyncCleanup() {
- // reset the panel to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The UI is in default state again.");
-});
diff --git a/browser/components/customizableui/test/browser_967000_button_feeds.js b/browser/components/customizableui/test/browser_967000_button_feeds.js
deleted file mode 100644
index 8f391941a..000000000
--- a/browser/components/customizableui/test/browser_967000_button_feeds.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/customizableui/test/support/feeds_test_page.html";
-const TEST_FEED = "http://mochi.test:8888/browser/browser/components/customizableui/test/support/test-feed.xml"
-
-var newTab = null;
-var initialLocation = gBrowser.currentURI.spec;
-
-add_task(function*() {
- info("Check Subscribe button functionality");
-
- // add the Subscribe button to the panel
- CustomizableUI.addWidgetToArea("feed-button",
- CustomizableUI.AREA_PANEL);
-
- // check the button's functionality
- yield PanelUI.show();
-
- let feedButton = document.getElementById("feed-button");
- ok(feedButton, "The Subscribe button was added to the Panel Menu");
- is(feedButton.getAttribute("disabled"), "true", "The Subscribe button is initially disabled");
-
- let panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
-
- newTab = gBrowser.selectedTab;
- yield promiseTabLoadEvent(newTab, TEST_PAGE);
-
- yield PanelUI.show();
-
- yield waitForCondition(() => !feedButton.hasAttribute("disabled"));
- ok(!feedButton.hasAttribute("disabled"), "The Subscribe button gets enabled");
-
- feedButton.click();
- yield promiseTabLoadEvent(newTab, TEST_FEED);
-
- is(gBrowser.currentURI.spec, TEST_FEED, "Subscribe page opened");
- ok(!isPanelUIOpen(), "Panel is closed");
-
- if (isPanelUIOpen()) {
- panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
- }
-});
-
-add_task(function* asyncCleanup() {
- // reset the panel UI to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The UI is in default state again.");
-
- // restore the initial location
- gBrowser.addTab(initialLocation);
- gBrowser.removeTab(newTab);
-});
diff --git a/browser/components/customizableui/test/browser_967000_button_sync.js b/browser/components/customizableui/test/browser_967000_button_sync.js
deleted file mode 100644
index 15a3235e0..000000000
--- a/browser/components/customizableui/test/browser_967000_button_sync.js
+++ /dev/null
@@ -1,335 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-let {SyncedTabs} = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-
-XPCOMUtils.defineLazyModuleGetter(this, "UITour", "resource:///modules/UITour.jsm");
-
-// These are available on the widget implementation, but it seems impossible
-// to grab that impl at runtime.
-const DECKINDEX_TABS = 0;
-const DECKINDEX_TABSDISABLED = 1;
-const DECKINDEX_FETCHING = 2;
-const DECKINDEX_NOCLIENTS = 3;
-
-var initialLocation = gBrowser.currentURI.spec;
-var newTab = null;
-
-// A helper to notify there are new tabs. Returns a promise that is resolved
-// once the UI has been updated.
-function updateTabsPanel() {
- let promiseTabsUpdated = promiseObserverNotified("synced-tabs-menu:test:tabs-updated");
- Services.obs.notifyObservers(null, SyncedTabs.TOPIC_TABS_CHANGED, null);
- return promiseTabsUpdated;
-}
-
-// This is the mock we use for SyncedTabs.jsm - tests may override various
-// functions.
-let mockedInternal = {
- get isConfiguredToSyncTabs() { return true; },
- getTabClients() { return []; },
- syncTabs() {},
- hasSyncedThisSession: false,
-};
-
-
-add_task(function* setup() {
- let oldInternal = SyncedTabs._internal;
- SyncedTabs._internal = mockedInternal;
-
- registerCleanupFunction(() => {
- SyncedTabs._internal = oldInternal;
- });
-});
-
-// The test expects the about:preferences#sync page to open in the current tab
-function* openPrefsFromMenuPanel(expectedPanelId, entryPoint) {
- info("Check Sync button functionality");
- Services.prefs.setCharPref("identity.fxaccounts.remote.signup.uri", "http://example.com/");
-
- // add the Sync button to the panel
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
-
- // check the button's functionality
- yield PanelUI.show();
-
- if (entryPoint == "uitour") {
- UITour.tourBrowsersByWindow.set(window, new Set());
- UITour.tourBrowsersByWindow.get(window).add(gBrowser.selectedBrowser);
- }
-
- let syncButton = document.getElementById("sync-button");
- ok(syncButton, "The Sync button was added to the Panel Menu");
-
- syncButton.click();
- let syncPanel = document.getElementById("PanelUI-remotetabs");
- ok(syncPanel.getAttribute("current"), "Sync Panel is in view");
-
- // Sync is not configured - verify that state is reflected.
- let subpanel = document.getElementById(expectedPanelId)
- ok(!subpanel.hidden, "sync setup element is visible");
-
- // Find and click the "setup" button.
- let setupButton = subpanel.querySelector(".PanelUI-remotetabs-prefs-button");
- setupButton.click();
-
- let deferred = Promise.defer();
- let handler = (e) => {
- if (e.originalTarget != gBrowser.selectedBrowser.contentDocument ||
- e.target.location.href == "about:blank") {
- info("Skipping spurious 'load' event for " + e.target.location.href);
- return;
- }
- gBrowser.selectedBrowser.removeEventListener("load", handler, true);
- deferred.resolve();
- }
- gBrowser.selectedBrowser.addEventListener("load", handler, true);
-
- yield deferred.promise;
- newTab = gBrowser.selectedTab;
-
- is(gBrowser.currentURI.spec, "about:preferences?entrypoint=" + entryPoint + "#sync",
- "Firefox Sync preference page opened with `menupanel` entrypoint");
- ok(!isPanelUIOpen(), "The panel closed");
-
- if (isPanelUIOpen()) {
- let panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
- }
-}
-
-function* asyncCleanup() {
- Services.prefs.clearUserPref("identity.fxaccounts.remote.signup.uri");
- // reset the panel UI to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The panel UI is in default state again.");
-
- // restore the tabs
- gBrowser.addTab(initialLocation);
- gBrowser.removeTab(newTab);
- UITour.tourBrowsersByWindow.delete(window);
-}
-
-// When Sync is not setup.
-add_task(() => openPrefsFromMenuPanel("PanelUI-remotetabs-setupsync", "synced-tabs"));
-add_task(asyncCleanup);
-
-// When Sync is configured in a "needs reauthentication" state.
-add_task(function* () {
- // configure our broadcasters so we are in the right state.
- document.getElementById("sync-reauth-state").hidden = false;
- document.getElementById("sync-setup-state").hidden = true;
- document.getElementById("sync-syncnow-state").hidden = true;
- yield openPrefsFromMenuPanel("PanelUI-remotetabs-reauthsync", "synced-tabs")
-});
-
-// Test the mobile promo links
-add_task(function* () {
- // change the preferences for the mobile links.
- Services.prefs.setCharPref("identity.mobilepromo.android", "http://example.com/?os=android&tail=");
- Services.prefs.setCharPref("identity.mobilepromo.ios", "http://example.com/?os=ios&tail=");
-
- mockedInternal.getTabClients = () => [];
- mockedInternal.syncTabs = () => Promise.resolve();
-
- document.getElementById("sync-reauth-state").hidden = true;
- document.getElementById("sync-setup-state").hidden = true;
- document.getElementById("sync-syncnow-state").hidden = false;
-
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
-
- let syncPanel = document.getElementById("PanelUI-remotetabs");
- let links = syncPanel.querySelectorAll(".remotetabs-promo-link");
-
- is(links.length, 2, "found 2 links as expected");
-
- // test each link and left and middle mouse buttons
- for (let link of links) {
- for (let button = 0; button < 2; button++) {
- yield PanelUI.show();
- EventUtils.sendMouseEvent({ type: "click", button }, link, window);
- // the panel should have been closed.
- ok(!isPanelUIOpen(), "click closed the panel");
- // should be a new tab - wait for the load.
- is(gBrowser.tabs.length, 2, "there's a new tab");
- yield new Promise(resolve => {
- if (gBrowser.selectedBrowser.currentURI.spec == "about:blank") {
- gBrowser.selectedBrowser.addEventListener("load", function listener(e) {
- gBrowser.selectedBrowser.removeEventListener("load", listener, true);
- resolve();
- }, true);
- return;
- }
- // the new tab has already transitioned away from about:blank so we
- // are good to go.
- resolve();
- });
-
- let os = link.getAttribute("mobile-promo-os");
- let expectedUrl = `http://example.com/?os=${os}&tail=synced-tabs`;
- is(gBrowser.selectedBrowser.currentURI.spec, expectedUrl, "correct URL");
- gBrowser.removeTab(gBrowser.selectedTab);
- }
- }
-
- // test each link and right mouse button - should be a noop.
- yield PanelUI.show();
- for (let link of links) {
- EventUtils.sendMouseEvent({ type: "click", button: 2 }, link, window);
- // the panel should still be open
- ok(isPanelUIOpen(), "panel remains open after right-click");
- is(gBrowser.tabs.length, 1, "no new tab was opened");
- }
- PanelUI.hide();
-
- Services.prefs.clearUserPref("identity.mobilepromo.android");
- Services.prefs.clearUserPref("identity.mobilepromo.ios");
-});
-
-// Test the "Sync Now" button
-add_task(function* () {
- mockedInternal.getTabClients = () => [];
- mockedInternal.syncTabs = () => {
- return Promise.resolve();
- }
-
- // configure our broadcasters so we are in the right state.
- document.getElementById("sync-reauth-state").hidden = true;
- document.getElementById("sync-setup-state").hidden = true;
- document.getElementById("sync-syncnow-state").hidden = false;
-
- // add the Sync button to the panel
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
- yield PanelUI.show();
- document.getElementById("sync-button").click();
- let syncPanel = document.getElementById("PanelUI-remotetabs");
- ok(syncPanel.getAttribute("current"), "Sync Panel is in view");
-
- let subpanel = document.getElementById("PanelUI-remotetabs-main")
- ok(!subpanel.hidden, "main pane is visible");
- let deck = document.getElementById("PanelUI-remotetabs-deck");
-
- // The widget is still fetching tabs, as we've neutered everything that
- // provides them
- is(deck.selectedIndex, DECKINDEX_FETCHING, "first deck entry is visible");
-
- let syncNowButton = document.getElementById("PanelUI-remotetabs-syncnow");
-
- let didSync = false;
- let oldDoSync = gSyncUI.doSync;
- gSyncUI.doSync = function() {
- didSync = true;
- mockedInternal.hasSyncedThisSession = true;
- gSyncUI.doSync = oldDoSync;
- }
- syncNowButton.click();
- ok(didSync, "clicking the button called the correct function");
-
- // Tell the widget there are tabs available, but with zero clients.
- mockedInternal.getTabClients = () => {
- return Promise.resolve([]);
- }
- yield updateTabsPanel();
- // The UI should be showing the "no clients" pane.
- is(deck.selectedIndex, DECKINDEX_NOCLIENTS, "no-clients deck entry is visible");
-
- // Tell the widget there are tabs available - we have 3 clients, one with no
- // tabs.
- mockedInternal.getTabClients = () => {
- return Promise.resolve([
- {
- id: "guid_mobile",
- type: "client",
- name: "My Phone",
- tabs: [],
- },
- {
- id: "guid_desktop",
- type: "client",
- name: "My Desktop",
- tabs: [
- {
- title: "http://example.com/10",
- lastUsed: 10, // the most recent
- },
- {
- title: "http://example.com/1",
- lastUsed: 1, // the least recent.
- },
- {
- title: "http://example.com/5",
- lastUsed: 5,
- },
- ],
- },
- {
- id: "guid_second_desktop",
- name: "My Other Desktop",
- tabs: [
- {
- title: "http://example.com/6",
- lastUsed: 6,
- }
- ],
- },
- ]);
- };
- yield updateTabsPanel();
-
- // The UI should be showing tabs!
- is(deck.selectedIndex, DECKINDEX_TABS, "no-clients deck entry is visible");
- let tabList = document.getElementById("PanelUI-remotetabs-tabslist");
- let node = tabList.firstChild;
- // First entry should be the client with the most-recent tab.
- is(node.getAttribute("itemtype"), "client", "node is a client entry");
- is(node.textContent, "My Desktop", "correct client");
- // Next entry is the most-recent tab
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "tab", "node is a tab");
- is(node.getAttribute("label"), "http://example.com/10");
-
- // Next entry is the next-most-recent tab
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "tab", "node is a tab");
- is(node.getAttribute("label"), "http://example.com/5");
-
- // Next entry is the least-recent tab from the first client.
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "tab", "node is a tab");
- is(node.getAttribute("label"), "http://example.com/1");
-
- // Next is a menuseparator between the clients.
- node = node.nextSibling;
- is(node.nodeName, "menuseparator");
-
- // Next is the client with 1 tab.
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "client", "node is a client entry");
- is(node.textContent, "My Other Desktop", "correct client");
- // Its single tab
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "tab", "node is a tab");
- is(node.getAttribute("label"), "http://example.com/6");
-
- // Next is a menuseparator between the clients.
- node = node.nextSibling;
- is(node.nodeName, "menuseparator");
-
- // Next is the client with no tab.
- node = node.nextSibling;
- is(node.getAttribute("itemtype"), "client", "node is a client entry");
- is(node.textContent, "My Phone", "correct client");
- // There is a single node saying there's no tabs for the client.
- node = node.nextSibling;
- is(node.nodeName, "label", "node is a label");
- is(node.getAttribute("itemtype"), "", "node is neither a tab nor a client");
-
- node = node.nextSibling;
- is(node, null, "no more entries");
-});
diff --git a/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js b/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js
deleted file mode 100644
index 88c30bf81..000000000
--- a/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Bug 968447 - The Bookmarks Toolbar Items doesn't appear as a
-// normal menu panel button in new windows.
-add_task(function*() {
- const buttonId = "bookmarks-toolbar-placeholder";
- yield startCustomizing();
- CustomizableUI.addWidgetToArea("personal-bookmarks", CustomizableUI.AREA_PANEL);
- yield endCustomizing();
-
- yield PanelUI.show();
-
- let bookmarksToolbarPlaceholder = document.getElementById(buttonId);
- ok(bookmarksToolbarPlaceholder.classList.contains("toolbarbutton-1"),
- "Button should have toolbarbutton-1 class");
- is(bookmarksToolbarPlaceholder.getAttribute("wrap"), "true",
- "Button should have the 'wrap' attribute");
-
- info("Waiting for panel to close");
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
-
- info("Waiting for window to open");
- let newWin = yield openAndLoadWindow({}, true);
-
- info("Waiting for panel in new window to open");
- let hideTrace = function() {
- info(new Error().stack);
- info("Panel was hidden.");
- };
- newWin.PanelUI.panel.addEventListener("popuphidden", hideTrace);
-
- yield newWin.PanelUI.show();
- let newWinBookmarksToolbarPlaceholder = newWin.document.getElementById(buttonId);
- ok(newWinBookmarksToolbarPlaceholder.classList.contains("toolbarbutton-1"),
- "Button in new window should have toolbarbutton-1 class");
- is(newWinBookmarksToolbarPlaceholder.getAttribute("wrap"), "true",
- "Button in new window should have 'wrap' attribute");
-
- newWin.PanelUI.panel.removeEventListener("popuphidden", hideTrace);
- // XXXgijs on Linux, we're sometimes seeing the panel being hidden early
- // in the newly created window, probably because something else steals focus.
- if (newWin.PanelUI.panel.state != "closed") {
- info("Panel is still open in new window, waiting for it to close");
- panelHiddenPromise = promisePanelHidden(newWin);
- newWin.PanelUI.hide();
- yield panelHiddenPromise;
- } else {
- info("panel was already closed");
- }
-
- info("Waiting for new window to close");
- yield promiseWindowClosed(newWin);
-});
-
-add_task(function* asyncCleanUp() {
- yield endCustomizing();
- CustomizableUI.reset();
-});
-
diff --git a/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js b/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js
deleted file mode 100644
index f7504fc41..000000000
--- a/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kHidden1Id = "test-hidden-button-1";
-const kHidden2Id = "test-hidden-button-2";
-
-var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
-// When we drag an item onto a customizable area, and not over a specific target, we
-// should assume that we're appending them to the area. If doing so, we should scan
-// backwards over any hidden items and insert the item before those hidden items.
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Should be in the default state");
-
- // Iterate backwards over the items in the nav-bar until we find the first
- // one that is not hidden.
- let placements = CustomizableUI.getWidgetsInArea(CustomizableUI.AREA_NAVBAR);
- let lastVisible = null;
- for (let widgetGroup of placements.reverse()) {
- let widget = widgetGroup.forWindow(window);
- if (widget && widget.node && !widget.node.hidden) {
- lastVisible = widget.node;
- break;
- }
- }
-
- if (!lastVisible) {
- ok(false, "Apparently, there are no visible items in the nav-bar.");
- }
-
- info("The last visible item in the nav-bar has ID: " + lastVisible.id);
-
- let hidden1 = createDummyXULButton(kHidden1Id, "You can't see me");
- let hidden2 = createDummyXULButton(kHidden2Id, "You can't see me either.");
- hidden1.hidden = hidden2.hidden = true;
-
- // Make sure we have some hidden items at the end of the nav-bar.
- navbar.insertItem(hidden1.id);
- navbar.insertItem(hidden2.id);
-
- // Drag an item and drop it onto the nav-bar customization target, but
- // not over a particular item.
- yield startCustomizing();
- let downloadsButton = document.getElementById("downloads-button");
- simulateItemDrag(downloadsButton, navbar.customizationTarget);
-
- yield endCustomizing();
-
- is(downloadsButton.previousSibling.id, lastVisible.id,
- "The downloads button should be placed after the last visible item.");
-
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js b/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js
deleted file mode 100644
index b5479fcb7..000000000
--- a/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-function getPlacementArea(id) {
- let placement = CustomizableUI.getPlacementOfWidget(id);
- return placement && placement.area;
-}
-
-// Check that a destroyed widget recreated after a reset call goes to
-// the navigation bar.
-add_task(function() {
- const kWidgetId = "test-recreate-after-reset";
- let spec = {id: kWidgetId, label: "Test re-create after reset.",
- removable: true, defaultArea: CustomizableUI.AREA_NAVBAR};
-
- CustomizableUI.createWidget(spec);
- is(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR,
- "widget is in the navigation bar");
-
- CustomizableUI.destroyWidget(kWidgetId);
- isnot(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR,
- "widget removed from the navigation bar");
-
- CustomizableUI.reset();
-
- CustomizableUI.createWidget(spec);
- is(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR,
- "widget recreated and added back to the nav bar");
-
- CustomizableUI.destroyWidget(kWidgetId);
-});
diff --git a/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js b/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js
deleted file mode 100644
index 6f057a100..000000000
--- a/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-
-// Adding the character encoding menu to the panel, exiting customize mode,
-// and moving it to the nav-bar should have it enabled, not disabled.
-add_task(function*() {
- yield startCustomizing();
- CustomizableUI.addWidgetToArea("characterencoding-button", "PanelUI-contents");
- yield endCustomizing();
- yield PanelUI.show();
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
- CustomizableUI.addWidgetToArea("characterencoding-button", 'nav-bar');
- let button = document.getElementById("characterencoding-button");
- ok(!button.hasAttribute("disabled"), "Button shouldn't be disabled");
-});
-
-add_task(function asyncCleanup() {
- resetCustomization();
-});
-
diff --git a/browser/components/customizableui/test/browser_970511_undo_restore_default.js b/browser/components/customizableui/test/browser_970511_undo_restore_default.js
deleted file mode 100644
index e7b3ca674..000000000
--- a/browser/components/customizableui/test/browser_970511_undo_restore_default.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-// Restoring default should reset theme and show an "undo" option which undoes the restoring operation.
-add_task(function*() {
- let homeButtonId = "home-button";
- CustomizableUI.removeWidgetFromArea(homeButtonId);
- yield startCustomizing();
- ok(!CustomizableUI.inDefaultState, "Not in default state to begin with");
- is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette");
- let undoResetButton = document.getElementById("customization-undo-reset-button");
- is(undoResetButton.hidden, true, "The undo button is hidden before reset");
-
- let themesButton = document.getElementById("customization-lwtheme-button");
- let popup = document.getElementById("customization-lwtheme-menu");
- let popupShownPromise = popupShown(popup);
- EventUtils.synthesizeMouseAtCenter(themesButton, {});
- info("Clicked on themes button");
- yield popupShownPromise;
-
- let recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended");
- let firstLWTheme = recommendedHeader.nextSibling;
- let firstLWThemeId = firstLWTheme.theme.id;
- let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed");
- firstLWTheme.doCommand();
- info("Clicked on first theme");
- yield themeChangedPromise;
-
- is(LightweightThemeManager.currentTheme.id, firstLWThemeId, "Theme changed to first option");
-
- yield gCustomizeMode.reset();
-
- ok(CustomizableUI.inDefaultState, "In default state after reset");
- is(undoResetButton.hidden, false, "The undo button is visible after reset");
- is(LightweightThemeManager.currentTheme, null, "Theme reset to default");
-
- yield gCustomizeMode.undoReset()
-
- is(LightweightThemeManager.currentTheme.id, firstLWThemeId, "Theme has been reset from default to original choice");
- ok(!CustomizableUI.inDefaultState, "Not in default state after undo-reset");
- is(undoResetButton.hidden, true, "The undo button is hidden after clicking on the undo button");
- is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette");
-
- yield gCustomizeMode.reset();
-});
-
-// Performing an action after a reset will hide the reset button.
-add_task(function*() {
- let homeButtonId = "home-button";
- CustomizableUI.removeWidgetFromArea(homeButtonId);
- ok(!CustomizableUI.inDefaultState, "Not in default state to begin with");
- is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette");
- let undoResetButton = document.getElementById("customization-undo-reset-button");
- is(undoResetButton.hidden, true, "The undo button is hidden before reset");
-
- yield gCustomizeMode.reset();
-
- ok(CustomizableUI.inDefaultState, "In default state after reset");
- is(undoResetButton.hidden, false, "The undo button is visible after reset");
-
- CustomizableUI.addWidgetToArea(homeButtonId, CustomizableUI.AREA_PANEL);
- is(undoResetButton.hidden, true, "The undo button is hidden after another change");
-});
-
-// "Restore defaults", exiting customize, and re-entering shouldn't show the Undo button
-add_task(function*() {
- let undoResetButton = document.getElementById("customization-undo-reset-button");
- is(undoResetButton.hidden, true, "The undo button is hidden before a reset");
- ok(!CustomizableUI.inDefaultState, "The browser should not be in default state");
- yield gCustomizeMode.reset();
-
- is(undoResetButton.hidden, false, "The undo button is visible after a reset");
- yield endCustomizing();
- yield startCustomizing();
- is(undoResetButton.hidden, true, "The undo reset button should be hidden after entering customization mode");
-});
-
-// Bug 971626 - Restore Defaults should collapse the Title Bar
-add_task(function*() {
- if (Services.appinfo.OS != "WINNT" &&
- Services.appinfo.OS != "Darwin") {
- return;
- }
- let prefName = "browser.tabs.drawInTitlebar";
- let defaultValue = Services.prefs.getBoolPref(prefName);
- let restoreDefaultsButton = document.getElementById("customization-reset-button");
- let titleBarButton = document.getElementById("customization-titlebar-visibility-button");
- let undoResetButton = document.getElementById("customization-undo-reset-button");
- ok(CustomizableUI.inDefaultState, "Should be in default state at start of test");
- ok(restoreDefaultsButton.disabled, "Restore defaults button should be disabled when in default state");
- is(titleBarButton.hasAttribute("checked"), !defaultValue, "Title bar button should reflect pref value");
- is(undoResetButton.hidden, true, "Undo reset button should be hidden at start of test");
-
- Services.prefs.setBoolPref(prefName, !defaultValue);
- ok(!restoreDefaultsButton.disabled, "Restore defaults button should be enabled when pref changed");
- is(titleBarButton.hasAttribute("checked"), defaultValue, "Title bar button should reflect changed pref value");
- ok(!CustomizableUI.inDefaultState, "With titlebar flipped, no longer default");
- is(undoResetButton.hidden, true, "Undo reset button should be hidden after pref change");
-
- yield gCustomizeMode.reset();
- ok(restoreDefaultsButton.disabled, "Restore defaults button should be disabled after reset");
- is(titleBarButton.hasAttribute("checked"), !defaultValue, "Title bar button should reflect default value after reset");
- is(Services.prefs.getBoolPref(prefName), defaultValue, "Reset should reset drawInTitlebar");
- ok(CustomizableUI.inDefaultState, "In default state after titlebar reset");
- is(undoResetButton.hidden, false, "Undo reset button should be visible after reset");
- ok(!undoResetButton.disabled, "Undo reset button should be enabled after reset");
-
- yield gCustomizeMode.undoReset();
- ok(!restoreDefaultsButton.disabled, "Restore defaults button should be enabled after undo-reset");
- is(titleBarButton.hasAttribute("checked"), defaultValue, "Title bar button should reflect undo-reset value");
- ok(!CustomizableUI.inDefaultState, "No longer in default state after undo");
- is(Services.prefs.getBoolPref(prefName), !defaultValue, "Undo-reset goes back to previous pref value");
- is(undoResetButton.hidden, true, "Undo reset button should be hidden after undo-reset clicked");
-
- Services.prefs.clearUserPref(prefName);
- ok(CustomizableUI.inDefaultState, "In default state after pref cleared");
- is(undoResetButton.hidden, true, "Undo reset button should be hidden at end of test");
-});
-
-add_task(function* asyncCleanup() {
- yield gCustomizeMode.reset();
- yield endCustomizing();
-});
diff --git a/browser/components/customizableui/test/browser_972267_customizationchange_events.js b/browser/components/customizableui/test/browser_972267_customizationchange_events.js
deleted file mode 100644
index b37dbe954..000000000
--- a/browser/components/customizableui/test/browser_972267_customizationchange_events.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Create a new window, then move the home button to the menu and check both windows have
-// customizationchange events fire on the toolbox:
-add_task(function*() {
- let newWindow = yield openAndLoadWindow();
- let otherToolbox = newWindow.gNavToolbox;
-
- let handlerCalledCount = 0;
- let handler = (ev) => {
- handlerCalledCount++;
- };
-
- let homeButton = document.getElementById("home-button");
-
- gNavToolbox.addEventListener("customizationchange", handler);
- otherToolbox.addEventListener("customizationchange", handler);
-
- gCustomizeMode.addToPanel(homeButton);
-
- is(handlerCalledCount, 2, "Should be called for both windows.");
-
- // If the test is run in isolation and the panel has never been open,
- // the button will be in the palette. Deal with this case:
- if (homeButton.parentNode.id == "BrowserToolbarPalette") {
- yield PanelUI.ensureReady();
- isnot(homeButton.parentNode.id, "BrowserToolbarPalette", "Home button should now be in panel");
- }
-
- handlerCalledCount = 0;
- gCustomizeMode.addToToolbar(homeButton);
- is(handlerCalledCount, 2, "Should be called for both windows.");
-
- gNavToolbox.removeEventListener("customizationchange", handler);
- otherToolbox.removeEventListener("customizationchange", handler);
-
- yield promiseWindowClosed(newWindow);
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_973641_button_addon.js b/browser/components/customizableui/test/browser_973641_button_addon.js
deleted file mode 100755
index 796bf3d0e..000000000
--- a/browser/components/customizableui/test/browser_973641_button_addon.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kButton = "test_button_for_addon";
-var initialLocation = gBrowser.currentURI.spec;
-
-add_task(function*() {
- info("Check addon button functionality");
-
- // create mocked addon button on the navigation bar
- let widgetSpec = {
- id: kButton,
- type: 'button',
- onClick: function() {
- gBrowser.selectedTab = gBrowser.addTab("about:addons");
- }
- };
- CustomizableUI.createWidget(widgetSpec);
- CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_NAVBAR);
-
- // check the button's functionality in navigation bar
- let addonButton = document.getElementById(kButton);
- let navBar = document.getElementById("nav-bar");
- ok(addonButton, "Addon button exists");
- ok(navBar.contains(addonButton), "Addon button is in the navbar");
- yield checkButtonFunctionality(addonButton);
-
- resetTabs();
-
- // move the add-on button in the Panel Menu
- CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_PANEL);
- ok(!navBar.contains(addonButton), "Addon button was removed from the browser bar");
-
- // check the addon button's functionality in the Panel Menu
- yield PanelUI.show();
- var panelMenu = document.getElementById("PanelUI-mainView");
- let addonButtonInPanel = panelMenu.getElementsByAttribute("id", kButton);
- ok(panelMenu.contains(addonButton), "Addon button was added to the Panel Menu");
- yield checkButtonFunctionality(addonButtonInPanel[0]);
-});
-
-add_task(function* asyncCleanup() {
- resetTabs();
-
- // reset the UI to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The UI is in default state again.");
-
- // destroy the widget
- CustomizableUI.destroyWidget(kButton);
-});
-
-function resetTabs() {
- // close all opened tabs
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeTab(gBrowser.selectedTab);
- }
-
- // restore the initial tab
- gBrowser.addTab(initialLocation);
- gBrowser.removeTab(gBrowser.selectedTab);
-}
-
-function* checkButtonFunctionality(aButton) {
- aButton.click();
- yield waitForCondition(() => gBrowser.currentURI &&
- gBrowser.currentURI.spec == "about:addons");
-}
diff --git a/browser/components/customizableui/test/browser_973932_addonbar_currentset.js b/browser/components/customizableui/test/browser_973932_addonbar_currentset.js
deleted file mode 100644
index 66fa6ef47..000000000
--- a/browser/components/customizableui/test/browser_973932_addonbar_currentset.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var addonbarID = CustomizableUI.AREA_ADDONBAR;
-var addonbar = document.getElementById(addonbarID);
-
-// Check that currentset is correctly updated after a reset:
-add_task(function*() {
- let placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements");
- ok(CustomizableUI.inDefaultState, "Should be in default state");
- info("Adding a spring to add-on bar shim");
- CustomizableUI.addWidgetToArea("spring", addonbarID, 1);
- ok(addonbar.getElementsByTagName("toolbarspring").length, "There should be a spring in the toolbar");
- ok(!CustomizableUI.inDefaultState, "Should no longer be in default state");
- placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match placements after spring addition");
-
- yield startCustomizing();
- yield gCustomizeMode.reset();
- ok(CustomizableUI.inDefaultState, "Should be in default state after reset");
- placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements after reset");
- ok(!addonbar.getElementsByTagName("toolbarspring").length, "There should be no spring in the toolbar");
- yield endCustomizing();
-});
-
diff --git a/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js b/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js
deleted file mode 100644
index 73fc7c1ff..000000000
--- a/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-const kXULWidgetId = "a-test-button"; // we'll create a button with this ID.
-
-add_task(function setup() {
- // create a XUL button and add it to the palette.
- createDummyXULButton(kXULWidgetId, "test-button");
-});
-
-add_task(function* customizeToolbarAndKeepIt() {
- ok(gNavToolbox.toolbarset, "There should be a toolbarset");
- let toolbarID = "testAustralisCustomToolbar";
- gNavToolbox.appendCustomToolbar(toolbarID, "");
- let toolbarDOMID = getToolboxCustomToolbarId(toolbarID);
- let toolbarElement = document.getElementById(toolbarDOMID);
- ok(toolbarElement, "There should be a toolbar");
- if (!toolbarElement) {
- ok(false, "No toolbar created, bailing out of the test.");
- return;
- }
- is(toolbarElement.nextSibling, gNavToolbox.toolbarset,
- "Toolbar should have been inserted in toolbox, before toolbarset element");
- let cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID);
- is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR,
- "CustomizableUI should know the area and think it's a toolbar");
- if (cuiAreaType != CustomizableUI.TYPE_TOOLBAR) {
- ok(false, "Toolbar not registered successfully, bailing out of the test.");
- toolbarElement.remove();
- return;
- }
- ok(!CustomizableUI.getWidgetIdsInArea(toolbarDOMID).length, "There should be no widgets in the area yet.");
- CustomizableUI.addWidgetToArea("open-file-button", toolbarDOMID, 0);
- ok(toolbarElement.hasChildNodes(), "Toolbar should now have a button.");
- assertAreaPlacements(toolbarDOMID, ["open-file-button"]);
-
- gNavToolbox.toolbarset.setAttribute("toolbar1", toolbarID + ":open-file-button");
- document.persist(gNavToolbox.toolbarset.id, "toolbar1");
-
- yield startCustomizing();
- // First, exit customize mode without doing anything, and verify the toolbar doesn't get removed.
- yield endCustomizing();
- ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state, the toolbar should still be there.");
- cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID);
- is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR,
- "CustomizableUI should still know the area and think it's a toolbar");
- ok(toolbarElement.parentNode, "Toolbar should still be in the DOM.");
- ok(toolbarElement.hasChildNodes(), "Toolbar should still have items in it.");
- assertAreaPlacements(toolbarDOMID, ["open-file-button"]);
-
- let newWindow = yield openAndLoadWindow({}, true);
- is(newWindow.gNavToolbox.toolbarset.getAttribute("toolbar1"),
- gNavToolbox.toolbarset.getAttribute("toolbar1"),
- "Attribute should be the same in new window");
- yield promiseWindowClosed(newWindow);
-
- // Then customize again, and this time empty out the toolbar and verify it *does* get removed.
- yield startCustomizing();
- let openFileButton = document.getElementById("open-file-button");
- let palette = document.getElementById("customization-palette");
- simulateItemDrag(openFileButton, palette);
- ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state because there's still a non-collapsed toolbar.");
- ok(!toolbarElement.hasChildNodes(), "Toolbar should have no more child nodes.");
-
- toolbarElement.collapsed = true;
- ok(CustomizableUI.inDefaultState, "Should be in default state because there's now just a collapsed toolbar.");
- toolbarElement.collapsed = false;
- ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state because there's a non-collapsed toolbar again.");
- yield endCustomizing();
- ok(CustomizableUI.inDefaultState, "Should be in default state because the toolbar should have been removed.");
-
- newWindow = yield openAndLoadWindow({}, true);
- ok(!newWindow.gNavToolbox.toolbarset.hasAttribute("toolbar1"),
- "Attribute should be gone in new window");
- yield promiseWindowClosed(newWindow);
-
- ok(!toolbarElement.parentNode, "Toolbar should no longer be in the DOM.");
- cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID);
- is(cuiAreaType, null, "CustomizableUI should have forgotten all about the area");
-});
-
-add_task(function* resetShouldDealWithCustomToolbars() {
- ok(gNavToolbox.toolbarset, "There should be a toolbarset");
- let toolbarID = "testAustralisCustomToolbar";
- gNavToolbox.appendCustomToolbar(toolbarID, "");
- let toolbarDOMID = getToolboxCustomToolbarId(toolbarID);
- let toolbarElement = document.getElementById(toolbarDOMID);
- ok(toolbarElement, "There should be a toolbar");
- if (!toolbarElement) {
- ok(false, "No toolbar created, bailing out of the test.");
- return;
- }
- is(toolbarElement.nextSibling, gNavToolbox.toolbarset,
- "Toolbar should have been inserted in toolbox, before toolbarset element");
- let cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID);
- is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR,
- "CustomizableUI should know the area and think it's a toolbar");
- if (cuiAreaType != CustomizableUI.TYPE_TOOLBAR) {
- ok(false, "Toolbar not registered successfully, bailing out of the test.");
- toolbarElement.remove();
- return;
- }
- ok(!CustomizableUI.getWidgetIdsInArea(toolbarDOMID).length, "There should be no widgets in the area yet.");
- CustomizableUI.addWidgetToArea(kXULWidgetId, toolbarDOMID, 0);
- ok(toolbarElement.hasChildNodes(), "Toolbar should now have a button.");
- assertAreaPlacements(toolbarDOMID, [kXULWidgetId]);
-
- gNavToolbox.toolbarset.setAttribute("toolbar2", `${toolbarID}:${kXULWidgetId}`);
- document.persist(gNavToolbox.toolbarset.id, "toolbar2");
-
- let newWindow = yield openAndLoadWindow({}, true);
- is(newWindow.gNavToolbox.toolbarset.getAttribute("toolbar2"),
- gNavToolbox.toolbarset.getAttribute("toolbar2"),
- "Attribute should be the same in new window");
- yield promiseWindowClosed(newWindow);
-
- CustomizableUI.reset();
-
- newWindow = yield openAndLoadWindow({}, true);
- ok(!newWindow.gNavToolbox.toolbarset.hasAttribute("toolbar2"),
- "Attribute should be gone in new window");
- yield promiseWindowClosed(newWindow);
-
- ok(CustomizableUI.inDefaultState, "Should be in default state after reset.");
- let xulButton = document.getElementById(kXULWidgetId);
- ok(!xulButton, "XUL button shouldn't be in the document anymore.");
- ok(gNavToolbox.palette.querySelector(`#${kXULWidgetId}`), "XUL button should be in the palette");
- ok(!toolbarElement.hasChildNodes(), "Toolbar should have no more child nodes.");
- ok(!toolbarElement.parentNode, "Toolbar should no longer be in the DOM.");
- cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID);
- is(cuiAreaType, null, "CustomizableUI should have forgotten all about the area");
-});
-
-
-add_task(function*() {
- let newWin = yield openAndLoadWindow({}, true);
- ok(!newWin.gNavToolbox.toolbarset.hasAttribute("toolbar1"), "New window shouldn't have attribute toolbar1");
- ok(!newWin.gNavToolbox.toolbarset.hasAttribute("toolbar2"), "New window shouldn't have attribute toolbar2");
- yield promiseWindowClosed(newWin);
-});
diff --git a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js
deleted file mode 100644
index 3bfa8c25d..000000000
--- a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js
+++ /dev/null
@@ -1,414 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarName = "test-insertNodeInWindow-placements-toolbar";
-const kTestWidgetPrefix = "test-widget-for-insertNodeInWindow-placements-";
-
-
-/*
-Tries to replicate the situation of having a placement list like this:
-
-exists-1,trying-to-insert-this,doesn't-exist,exists-2
-*/
-add_task(function*() {
- let testWidgetExists = [true, false, false, true];
- let widgetIds = [];
- for (let i = 0; i < testWidgetExists.length; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- if (testWidgetExists[i]) {
- let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- }
- }
-
- let toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds);
- assertAreaPlacements(kToolbarName, widgetIds);
-
- let btnId = kTestWidgetPrefix + 1;
- let btn = createDummyXULButton(btnId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(btnId, window);
-
- is(btn.parentNode.id, kToolbarName, "New XUL widget should be placed inside new toolbar");
-
- is(btn.previousSibling.id, toolbarNode.firstChild.id,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- btn.remove();
- removeCustomToolbars();
- yield resetCustomization();
-});
-
-
-/*
-Tests nodes get placed inside the toolbar's overflow as expected. Replicates a
-situation similar to:
-
-exists-1,exists-2,overflow-1,trying-to-insert-this,overflow-2
-*/
-add_task(function*() {
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
- let widgetIds = [];
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- CustomizableUI.addWidgetToArea(id, "nav-bar");
- }
-
- for (let id of widgetIds) {
- document.getElementById(id).style.minWidth = "200px";
- }
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
-
- let testWidgetId = kTestWidgetPrefix + 3;
-
- CustomizableUI.destroyWidget(testWidgetId);
-
- let btn = createDummyXULButton(testWidgetId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window);
-
- is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar");
- is(btn.previousSibling.id, kTestWidgetPrefix + 2,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
- is(btn.nextSibling.id, kTestWidgetPrefix + 4,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
-
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName);
- btn.remove();
- yield resetCustomization();
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
-});
-
-
-/*
-Tests nodes get placed inside the toolbar's overflow as expected. Replicates a
-placements situation similar to:
-
-exists-1,exists-2,overflow-1,doesn't-exist,trying-to-insert-this,overflow-2
-*/
-add_task(function*() {
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
- let widgetIds = [];
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- CustomizableUI.addWidgetToArea(id, "nav-bar");
- }
-
- for (let id of widgetIds) {
- document.getElementById(id).style.minWidth = "200px";
- }
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
-
- let testWidgetId = kTestWidgetPrefix + 3;
-
- CustomizableUI.destroyWidget(kTestWidgetPrefix + 2);
- CustomizableUI.destroyWidget(testWidgetId);
-
- let btn = createDummyXULButton(testWidgetId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window);
-
- is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar");
- is(btn.previousSibling.id, kTestWidgetPrefix + 1,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
- is(btn.nextSibling.id, kTestWidgetPrefix + 4,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
-
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName);
- btn.remove();
- yield resetCustomization();
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
-});
-
-
-/*
-Tests nodes get placed inside the toolbar's overflow as expected. Replicates a
-placements situation similar to:
-
-exists-1,exists-2,overflow-1,doesn't-exist,trying-to-insert-this,doesn't-exist
-*/
-add_task(function*() {
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
- let widgetIds = [];
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- CustomizableUI.addWidgetToArea(id, "nav-bar");
- }
-
- for (let id of widgetIds) {
- document.getElementById(id).style.minWidth = "200px";
- }
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
-
- let testWidgetId = kTestWidgetPrefix + 3;
-
- CustomizableUI.destroyWidget(kTestWidgetPrefix + 2);
- CustomizableUI.destroyWidget(testWidgetId);
- CustomizableUI.destroyWidget(kTestWidgetPrefix + 4);
-
- let btn = createDummyXULButton(testWidgetId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window);
-
- is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar");
- is(btn.previousSibling.id, kTestWidgetPrefix + 1,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
- is(btn.nextSibling, null,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
-
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName);
- btn.remove();
- yield resetCustomization();
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
-});
-
-
-/*
-Tests nodes get placed inside the toolbar's overflow as expected. Replicates a
-placements situation similar to:
-
-exists-1,exists-2,overflow-1,can't-overflow,trying-to-insert-this,overflow-2
-*/
-add_task(function*() {
- let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-
- let widgetIds = [];
- for (let i = 5; i >= 0; i--) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- CustomizableUI.addWidgetToArea(id, "nav-bar", 0);
- }
-
- for (let i = 10; i < 15; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- CustomizableUI.addWidgetToArea(id, "nav-bar");
- }
-
- for (let id of widgetIds) {
- document.getElementById(id).style.minWidth = "200px";
- }
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => navbar.hasAttribute("overflowing"));
-
- // Find last widget that doesn't allow overflowing
- let nonOverflowing = navbar.customizationTarget.lastChild;
- is(nonOverflowing.getAttribute("overflows"), "false", "Last child is expected to not allow overflowing");
- isnot(nonOverflowing.getAttribute("skipintoolbarset"), "true", "Last child is expected to not be skipintoolbarset");
-
- let testWidgetId = kTestWidgetPrefix + 10;
- CustomizableUI.destroyWidget(testWidgetId);
-
- let btn = createDummyXULButton(testWidgetId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window);
-
- is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar");
- is(btn.nextSibling.id, kTestWidgetPrefix + 11,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
-
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName);
- btn.remove();
- yield resetCustomization();
- yield waitForCondition(() => !navbar.hasAttribute("overflowing"));
-});
-
-
-/*
-Tests nodes get placed inside the toolbar's overflow as expected. Replicates a
-placements situation similar to:
-
-exists-1,exists-2,overflow-1,trying-to-insert-this,can't-overflow,overflow-2
-*/
-add_task(function*() {
- let widgetIds = [];
- let missingId = 2;
- let nonOverflowableId = 3;
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- if (i != missingId) {
- // Setting min-width to make the overflow state not depend on styling of the button and/or
- // screen width
- let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i,
- onCreated: function(node) {
- node.style.minWidth = "200px";
- if (id == (kTestWidgetPrefix + nonOverflowableId)) {
- node.setAttribute("overflows", false);
- }
- }};
- info("Creating: " + id);
- CustomizableUI.createWidget(spec);
- }
- }
-
- let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds);
- assertAreaPlacements(kToolbarName, widgetIds);
- ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with.");
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => toolbarNode.hasAttribute("overflowing"));
- ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- let btnId = kTestWidgetPrefix + missingId;
- let btn = createDummyXULButton(btnId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(btnId, window);
-
- is(btn.parentNode.id, kToolbarName + "-overflow-list", "New XUL widget should be placed inside new toolbar's overflow");
- is(btn.previousSibling.id, kTestWidgetPrefix + 1,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
- is(btn.nextSibling.id, kTestWidgetPrefix + 4,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing"));
-
- btn.remove();
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- removeCustomToolbars();
- yield resetCustomization();
-});
-
-
-/*
-Tests nodes do *not* get placed in the toolbar's overflow. Replicates a
-plcements situation similar to:
-
-exists-1,trying-to-insert-this,exists-2,overflowed-1
-*/
-add_task(function*() {
- let widgetIds = [];
- let missingId = 1;
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- if (i != missingId) {
- // Setting min-width to make the overflow state not depend on styling of the button and/or
- // screen width
- let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i,
- onCreated: function(node) { node.style.minWidth = "100px"; }};
- info("Creating: " + id);
- CustomizableUI.createWidget(spec);
- }
- }
-
- let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds);
- assertAreaPlacements(kToolbarName, widgetIds);
- ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with.");
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => toolbarNode.hasAttribute("overflowing"));
- ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- let btnId = kTestWidgetPrefix + missingId;
- let btn = createDummyXULButton(btnId, "test");
- CustomizableUI.ensureWidgetPlacedInWindow(btnId, window);
-
- is(btn.parentNode.id, kToolbarName + "-target", "New XUL widget should be placed inside new toolbar");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing"));
-
- btn.remove();
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- removeCustomToolbars();
- yield resetCustomization();
-});
-
-
-/*
-Tests inserting a node onto the end of an overflowing toolbar *doesn't* put it in
-the overflow list when the widget disallows overflowing. ie:
-
-exists-1,exists-2,overflows-1,trying-to-insert-this
-
-Where trying-to-insert-this has overflows=false
-*/
-add_task(function*() {
- let widgetIds = [];
- let missingId = 3;
- for (let i = 0; i < 5; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- if (i != missingId) {
- // Setting min-width to make the overflow state not depend on styling of the button and/or
- // screen width
- let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i,
- onCreated: function(node) { node.style.minWidth = "200px"; }};
- info("Creating: " + id);
- CustomizableUI.createWidget(spec);
- }
- }
-
- let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds);
- assertAreaPlacements(kToolbarName, widgetIds);
- ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with.");
-
- let originalWindowWidth = window.outerWidth;
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => toolbarNode.hasAttribute("overflowing"));
- ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
-
- let btnId = kTestWidgetPrefix + missingId;
- let btn = createDummyXULButton(btnId, "test");
- btn.setAttribute("overflows", false);
- CustomizableUI.ensureWidgetPlacedInWindow(btnId, window);
-
- is(btn.parentNode.id, kToolbarName + "-target", "New XUL widget should be placed inside new toolbar");
- is(btn.nextSibling, null,
- "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
- yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing"));
-
- btn.remove();
- widgetIds.forEach(id => CustomizableUI.destroyWidget(id));
- removeCustomToolbars();
- yield resetCustomization();
-});
-
-
-add_task(function* asyncCleanUp() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js b/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js
deleted file mode 100644
index a653c2d51..000000000
--- a/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var draggedItem;
-
-/**
- * Check that customizing-movingItem gets removed on a drop when the item is moved.
- */
-
-// Drop on the palette
-add_task(function*() {
- draggedItem = document.createElement("toolbarbutton");
- draggedItem.id = "test-dragEnd-after-move1";
- draggedItem.setAttribute("label", "Test");
- draggedItem.setAttribute("removable", "true");
- let navbar = document.getElementById("nav-bar");
- navbar.customizationTarget.appendChild(draggedItem);
- yield startCustomizing();
- simulateItemDrag(draggedItem, gCustomizeMode.visiblePalette);
- is(document.documentElement.hasAttribute("customizing-movingItem"), false,
- "Make sure customizing-movingItem is removed after dragging to the palette");
- yield endCustomizing();
-});
-
-// Drop on a customization target itself
-add_task(function*() {
- draggedItem = document.createElement("toolbarbutton");
- draggedItem.id = "test-dragEnd-after-move2";
- draggedItem.setAttribute("label", "Test");
- draggedItem.setAttribute("removable", "true");
- let dest = createToolbarWithPlacements("test-dragEnd");
- let navbar = document.getElementById("nav-bar");
- navbar.customizationTarget.appendChild(draggedItem);
- yield startCustomizing();
- simulateItemDrag(draggedItem, dest.customizationTarget);
- is(document.documentElement.hasAttribute("customizing-movingItem"), false,
- "Make sure customizing-movingItem is removed");
- yield endCustomizing();
-});
-
-add_task(function* asyncCleanup() {
- yield endCustomizing();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js
deleted file mode 100644
index 15197ac86..000000000
--- a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kToolbarName = "test-new-overflowable-toolbar";
-const kTestWidgetPrefix = "test-widget-for-overflowable-toolbar-";
-
-add_task(function* addOverflowingToolbar() {
- let originalWindowWidth = window.outerWidth;
-
- let widgetIds = [];
- for (let i = 0; i < 10; i++) {
- let id = kTestWidgetPrefix + i;
- widgetIds.push(id);
- let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i};
- CustomizableUI.createWidget(spec);
- }
-
- let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds);
- assertAreaPlacements(kToolbarName, widgetIds);
-
- for (let id of widgetIds) {
- document.getElementById(id).style.minWidth = "200px";
- }
-
- isnot(toolbarNode.overflowable, null, "Toolbar should have overflowable controller");
- isnot(toolbarNode.customizationTarget, null, "Toolbar should have customization target");
- isnot(toolbarNode.customizationTarget, toolbarNode, "Customization target should not be toolbar node");
-
- let oldChildCount = toolbarNode.customizationTarget.childElementCount;
- let overflowableList = document.getElementById(kToolbarName + "-overflow-list");
- let oldOverflowCount = overflowableList.childElementCount;
-
- isnot(oldChildCount, 0, "Toolbar should have non-overflowing widgets");
-
- window.resizeTo(400, window.outerHeight);
- yield waitForCondition(() => toolbarNode.hasAttribute("overflowing"));
- ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar.");
- ok(toolbarNode.customizationTarget.childElementCount < oldChildCount, "Should have fewer children.");
- ok(overflowableList.childElementCount > oldOverflowCount, "Should have more overflowed widgets.");
-
- window.resizeTo(originalWindowWidth, window.outerHeight);
-});
-
-
-add_task(function* asyncCleanup() {
- removeCustomToolbars();
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_981305_separator_insertion.js b/browser/components/customizableui/test/browser_981305_separator_insertion.js
deleted file mode 100644
index 8d4d86c2a..000000000
--- a/browser/components/customizableui/test/browser_981305_separator_insertion.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var tempElements = [];
-
-function insertTempItemsIntoMenu(parentMenu) {
- // Last element is null to insert at the end:
- let beforeEls = [parentMenu.firstChild, parentMenu.lastChild, null];
- for (let i = 0; i < beforeEls.length; i++) {
- let sep = document.createElement("menuseparator");
- tempElements.push(sep);
- parentMenu.insertBefore(sep, beforeEls[i]);
- let menu = document.createElement("menu");
- tempElements.push(menu);
- parentMenu.insertBefore(menu, beforeEls[i]);
- // And another separator for good measure:
- sep = document.createElement("menuseparator");
- tempElements.push(sep);
- parentMenu.insertBefore(sep, beforeEls[i]);
- }
-}
-
-function checkSeparatorInsertion(menuId, buttonId, subviewId) {
- return function*() {
- info("Checking for duplicate separators in " + buttonId + " widget");
- let menu = document.getElementById(menuId);
- insertTempItemsIntoMenu(menu);
-
- let placement = CustomizableUI.getPlacementOfWidget(buttonId);
- let changedPlacement = false;
- if (!placement || placement.area != CustomizableUI.AREA_PANEL) {
- CustomizableUI.addWidgetToArea(buttonId, CustomizableUI.AREA_PANEL);
- changedPlacement = true;
- }
- yield PanelUI.show();
-
- let button = document.getElementById(buttonId);
- button.click();
-
- yield waitForCondition(() => !PanelUI.multiView.hasAttribute("transitioning"));
- let subview = document.getElementById(subviewId);
- ok(subview.firstChild, "Subview should have a kid");
- is(subview.firstChild.localName, "toolbarbutton", "There should be no separators to start with");
-
- for (let kid of subview.children) {
- if (kid.localName == "menuseparator") {
- ok(kid.previousSibling && kid.previousSibling.localName != "menuseparator",
- "Separators should never have another separator next to them, and should never be the first node.");
- }
- }
-
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
-
- if (changedPlacement) {
- CustomizableUI.reset();
- }
- };
-}
-
-add_task(checkSeparatorInsertion("menuWebDeveloperPopup", "developer-button", "PanelUI-developerItems"));
-add_task(checkSeparatorInsertion("viewSidebarMenu", "sidebar-button", "PanelUI-sidebarItems"));
-
-registerCleanupFunction(function() {
- for (let el of tempElements) {
- el.remove();
- }
- tempElements = null;
-});
diff --git a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js
deleted file mode 100644
index 9a7227a47..000000000
--- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* 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/. */
-
-"use strict";
-const kWidgetId = 'test-981418-widget-onbeforecreated';
-
-// Should be able to add broken view widget
-add_task(function* testAddOnBeforeCreatedWidget() {
- let viewShownDeferred = Promise.defer();
- let onBeforeCreatedCalled = false;
- let widgetSpec = {
- id: kWidgetId,
- type: 'view',
- viewId: kWidgetId + 'idontexistyet',
- onBeforeCreated: function(doc) {
- let view = doc.createElement("panelview");
- view.id = kWidgetId + 'idontexistyet';
- let label = doc.createElement("label");
- label.setAttribute("value", "Hello world");
- label.className = 'panel-subview-header';
- view.appendChild(label);
- document.getElementById("PanelUI-multiView").appendChild(view);
- onBeforeCreatedCalled = true;
- },
- onViewShowing: function() {
- viewShownDeferred.resolve();
- }
- };
-
- let noError = true;
- try {
- CustomizableUI.createWidget(widgetSpec);
- CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Should not throw an exception trying to add the widget.");
- ok(onBeforeCreatedCalled, "onBeforeCreated should have been called");
-
- let widgetNode = document.getElementById(kWidgetId);
- ok(widgetNode, "Widget should exist");
- if (widgetNode) {
- try {
- widgetNode.click();
-
- let tempPanel = document.getElementById("customizationui-widget-panel");
- let panelShownPromise = promisePanelElementShown(window, tempPanel);
-
- let shownTimeout = setTimeout(() => viewShownDeferred.reject("Panel not shown within 20s"), 20000);
- yield viewShownDeferred.promise;
- yield panelShownPromise;
- clearTimeout(shownTimeout);
- ok(true, "Found view shown");
-
- let panelHiddenPromise = promisePanelElementHidden(window, tempPanel);
- tempPanel.hidePopup();
- yield panelHiddenPromise;
-
- CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_PANEL);
- yield PanelUI.show();
-
- viewShownDeferred = Promise.defer();
- widgetNode.click();
-
- shownTimeout = setTimeout(() => viewShownDeferred.reject("Panel not shown within 20s"), 20000);
- yield viewShownDeferred.promise;
- clearTimeout(shownTimeout);
- ok(true, "Found view shown");
-
- let panelHidden = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidden;
- } catch (ex) {
- ok(false, "Unexpected exception (like a timeout for one of the yields) " +
- "when testing view widget.");
- }
- }
-
- noError = true;
- try {
- CustomizableUI.destroyWidget(kWidgetId);
- } catch (ex) {
- Cu.reportError(ex);
- noError = false;
- }
- ok(noError, "Should not throw an exception trying to remove the broken view widget.");
-});
-
-add_task(function* asyncCleanup() {
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js b/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js
deleted file mode 100644
index e7f8d0cf4..000000000
--- a/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Restoring default should not place addon widgets back in the toolbar
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Default state to begin");
-
- const kWidgetId = "bug982656-add-on-widget-should-not-restore-to-default-area";
- let widgetSpec = {
- id: kWidgetId,
- defaultArea: CustomizableUI.AREA_NAVBAR
- };
- CustomizableUI.createWidget(widgetSpec);
-
- ok(!CustomizableUI.inDefaultState, "Not in default state after widget added");
- is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar");
-
- yield resetCustomization();
-
- ok(CustomizableUI.inDefaultState, "Back in default state after reset");
- is(CustomizableUI.getPlacementOfWidget(kWidgetId), null, "Widget now in palette");
- CustomizableUI.destroyWidget(kWidgetId);
-});
-
-
-// resetCustomization shouldn't move 3rd party widgets out of custom toolbars
-add_task(function*() {
- const kToolbarId = "bug982656-toolbar-with-defaultset";
- const kWidgetId = "bug982656-add-on-widget-should-restore-to-default-area-when-area-is-not-builtin";
- ok(CustomizableUI.inDefaultState, "Everything should be in its default state.");
- let toolbar = createToolbarWithPlacements(kToolbarId);
- ok(CustomizableUI.areas.indexOf(kToolbarId) != -1,
- "Toolbar has been registered.");
- is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR,
- "Area should be registered as toolbar");
-
- let widgetSpec = {
- id: kWidgetId,
- defaultArea: kToolbarId
- };
- CustomizableUI.createWidget(widgetSpec);
-
- ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible.");
- is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, kToolbarId, "Widget should be in custom toolbar");
-
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "Back in default state after reset");
- is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, kToolbarId, "Widget still in custom toolbar");
- ok(toolbar.collapsed, "Custom toolbar should be collapsed after reset");
-
- toolbar.remove();
- CustomizableUI.destroyWidget(kWidgetId);
- CustomizableUI.unregisterArea(kToolbarId);
-});
diff --git a/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js b/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js
deleted file mode 100644
index 42b346c10..000000000
--- a/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js
+++ /dev/null
@@ -1,267 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var gNavBar = document.getElementById(CustomizableUI.AREA_NAVBAR);
-var gOverflowList = document.getElementById(gNavBar.getAttribute("overflowtarget"));
-
-const kBookmarksButton = "bookmarks-menu-button";
-const kBookmarksItems = "personal-bookmarks";
-const kOriginalWindowWidth = window.outerWidth;
-const kSmallWidth = 400;
-
-/**
- * Helper function that opens the bookmarks menu, and returns a Promise that
- * resolves as soon as the menu is ready for interaction.
- */
-function bookmarksMenuPanelShown() {
- let deferred = Promise.defer();
- let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup");
- let onTransitionEnd = (e) => {
- if (e.target == bookmarksMenuPopup) {
- bookmarksMenuPopup.removeEventListener("transitionend", onTransitionEnd);
- deferred.resolve();
- }
- }
- bookmarksMenuPopup.addEventListener("transitionend", onTransitionEnd);
- return deferred.promise;
-}
-
-/**
- * Checks that the placesContext menu is correctly attached to the
- * controller of some view. Returns a Promise that resolves as soon
- * as the context menu is closed.
- *
- * @param aItemWithContextMenu the item that we need to synthesize hte
- * right click on in order to open the context menu.
- */
-function checkPlacesContextMenu(aItemWithContextMenu) {
- return Task.spawn(function* () {
- let contextMenu = document.getElementById("placesContext");
- let newBookmarkItem = document.getElementById("placesContext_new:bookmark");
- info("Waiting for context menu on " + aItemWithContextMenu.id);
- let shownPromise = popupShown(contextMenu);
- EventUtils.synthesizeMouseAtCenter(aItemWithContextMenu,
- {type: "contextmenu", button: 2});
- yield shownPromise;
-
- ok(!newBookmarkItem.hasAttribute("disabled"),
- "New bookmark item shouldn't be disabled");
-
- info("Closing context menu");
- yield closePopup(contextMenu);
- });
-}
-
-/**
- * Opens the bookmarks menu panel, and then opens each of the "special"
- * submenus in that list. Then it checks that those submenu's context menus
- * are properly hooked up to a controller.
- */
-function checkSpecialContextMenus() {
- return Task.spawn(function* () {
- let bookmarksMenuButton = document.getElementById(kBookmarksButton);
- let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup");
-
- const kSpecialItemIDs = {
- "BMB_bookmarksToolbar": "BMB_bookmarksToolbarPopup",
- "BMB_unsortedBookmarks": "BMB_unsortedBookmarksPopup",
- };
-
- // Open the bookmarks menu button context menus and ensure that
- // they have the proper views attached.
- let shownPromise = bookmarksMenuPanelShown();
- let dropmarker = document.getAnonymousElementByAttribute(bookmarksMenuButton,
- "anonid", "dropmarker");
- EventUtils.synthesizeMouseAtCenter(dropmarker, {});
- info("Waiting for bookmarks menu popup to show after clicking dropmarker.")
- yield shownPromise;
-
- for (let menuID in kSpecialItemIDs) {
- let menuItem = document.getElementById(menuID);
- let menuPopup = document.getElementById(kSpecialItemIDs[menuID]);
- info("Waiting to open menu for " + menuID);
- let shownPromise = popupShown(menuPopup);
- menuPopup.openPopup(menuItem, null, 0, 0, false, false, null);
- yield shownPromise;
-
- yield checkPlacesContextMenu(menuPopup);
- info("Closing menu for " + menuID);
- yield closePopup(menuPopup);
- }
-
- info("Closing bookmarks menu");
- yield closePopup(bookmarksMenuPopup);
- });
-}
-
-/**
- * Closes a focused popup by simulating pressing the Escape key,
- * and returns a Promise that resolves as soon as the popup is closed.
- *
- * @param aPopup the popup node to close.
- */
-function closePopup(aPopup) {
- let hiddenPromise = popupHidden(aPopup);
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- return hiddenPromise;
-}
-
-/**
- * Helper function that checks that the context menu of the
- * bookmark toolbar items chevron popup is correctly hooked up
- * to the controller of a view.
- */
-function checkBookmarksItemsChevronContextMenu() {
- return Task.spawn(function*() {
- let chevronPopup = document.getElementById("PlacesChevronPopup");
- let shownPromise = popupShown(chevronPopup);
- let chevron = document.getElementById("PlacesChevron");
- EventUtils.synthesizeMouseAtCenter(chevron, {});
- info("Waiting for bookmark toolbar item chevron popup to show");
- yield shownPromise;
- yield waitForCondition(() => {
- for (let child of chevronPopup.children) {
- if (child.style.visibility != "hidden")
- return true;
- }
- return false;
- });
- yield checkPlacesContextMenu(chevronPopup);
- info("Waiting for bookmark toolbar item chevron popup to close");
- yield closePopup(chevronPopup);
- });
-}
-
-/**
- * Forces the window to a width that causes the nav-bar to overflow
- * its contents. Returns a Promise that resolves as soon as the
- * overflowable nav-bar is showing its chevron.
- */
-function overflowEverything() {
- info("Waiting for overflow");
- window.resizeTo(kSmallWidth, window.outerHeight);
- return waitForCondition(() => gNavBar.hasAttribute("overflowing"));
-}
-
-/**
- * Returns the window to its original size from the start of the test,
- * and returns a Promise that resolves when the nav-bar is no longer
- * overflowing.
- */
-function stopOverflowing() {
- info("Waiting until we stop overflowing");
- window.resizeTo(kOriginalWindowWidth, window.outerHeight);
- return waitForCondition(() => !gNavBar.hasAttribute("overflowing"));
-}
-
-/**
- * Checks that an item with ID aID is overflowing in the nav-bar.
- *
- * @param aID the ID of the node to check for overflowingness.
- */
-function checkOverflowing(aID) {
- ok(!gNavBar.querySelector("#" + aID),
- "Item with ID " + aID + " should no longer be in the gNavBar");
- let item = gOverflowList.querySelector("#" + aID);
- ok(item, "Item with ID " + aID + " should be overflowing");
- is(item.getAttribute("overflowedItem"), "true",
- "Item with ID " + aID + " should have overflowedItem attribute");
-}
-
-/**
- * Checks that an item with ID aID is not overflowing in the nav-bar.
- *
- * @param aID the ID of hte node to check for non-overflowingness.
- */
-function checkNotOverflowing(aID) {
- ok(!gOverflowList.querySelector("#" + aID),
- "Item with ID " + aID + " should no longer be overflowing");
- let item = gNavBar.querySelector("#" + aID);
- ok(item, "Item with ID " + aID + " should be in the nav bar");
- ok(!item.hasAttribute("overflowedItem"),
- "Item with ID " + aID + " should not have overflowedItem attribute");
-}
-
-/**
- * Test that overflowing the bookmarks menu button doesn't break the
- * context menus for the Unsorted and Bookmarks Toolbar menu items.
- */
-add_task(function* testOverflowingBookmarksButtonContextMenu() {
- ok(!gNavBar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar.");
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
-
- // Open the Unsorted and Bookmarks Toolbar context menus and ensure
- // that they have views attached.
- yield checkSpecialContextMenus();
-
- yield overflowEverything();
- checkOverflowing(kBookmarksButton);
-
- yield stopOverflowing();
- checkNotOverflowing(kBookmarksButton);
-
- yield checkSpecialContextMenus();
-});
-
-/**
- * Test that the bookmarks toolbar items context menu still works if moved
- * to the menu from the overflow panel, and then back to the toolbar.
- */
-add_task(function* testOverflowingBookmarksItemsContextMenu() {
- info("Ensuring panel is ready.");
- yield PanelUI.ensureReady();
-
- let bookmarksToolbarItems = document.getElementById(kBookmarksItems);
- gCustomizeMode.addToToolbar(bookmarksToolbarItems);
- yield checkPlacesContextMenu(bookmarksToolbarItems);
-
- yield overflowEverything();
- checkOverflowing(kBookmarksItems)
-
- gCustomizeMode.addToPanel(bookmarksToolbarItems);
-
- yield stopOverflowing();
-
- gCustomizeMode.addToToolbar(bookmarksToolbarItems);
- yield checkPlacesContextMenu(bookmarksToolbarItems);
-});
-
-/**
- * Test that overflowing the bookmarks toolbar items doesn't cause the
- * context menu in the bookmarks toolbar items chevron to stop working.
- */
-add_task(function* testOverflowingBookmarksItemsChevronContextMenu() {
- // If it's not already there, let's move the bookmarks toolbar items to
- // the nav-bar.
- let bookmarksToolbarItems = document.getElementById(kBookmarksItems);
- gCustomizeMode.addToToolbar(bookmarksToolbarItems);
-
- // We make the PlacesToolbarItems element be super tiny in order to force
- // the bookmarks toolbar items into overflowing and making the chevron
- // show itself.
- let placesToolbarItems = document.getElementById("PlacesToolbarItems");
- let placesChevron = document.getElementById("PlacesChevron");
- placesToolbarItems.style.maxWidth = "10px";
- info("Waiting for chevron to no longer be collapsed");
- yield waitForCondition(() => !placesChevron.collapsed);
-
- yield checkBookmarksItemsChevronContextMenu();
-
- yield overflowEverything();
- checkOverflowing(kBookmarksItems);
-
- yield stopOverflowing();
- checkNotOverflowing(kBookmarksItems);
-
- yield checkBookmarksItemsChevronContextMenu();
-
- placesToolbarItems.style.removeProperty("max-width");
-});
-
-add_task(function* asyncCleanup() {
- window.resizeTo(kOriginalWindowWidth, window.outerHeight);
- yield resetCustomization();
-});
diff --git a/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js b/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js
deleted file mode 100644
index c341c2158..000000000
--- a/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function*() {
- ok(CustomizableUI.inDefaultState, "Should start in default state.");
- this.otherWin = yield openAndLoadWindow({private: true}, true);
- yield startCustomizing(this.otherWin);
- let resetButton = this.otherWin.document.getElementById("customization-reset-button");
- ok(resetButton.disabled, "Reset button should be disabled");
-
- if (typeof CustomizableUI.setToolbarVisibility == "function") {
- CustomizableUI.setToolbarVisibility("PersonalToolbar", true);
- } else {
- setToolbarVisibility(document.getElementById("PersonalToolbar"), true);
- }
-
- let otherPersonalToolbar = this.otherWin.document.getElementById("PersonalToolbar");
- let personalToolbar = document.getElementById("PersonalToolbar");
- ok(!otherPersonalToolbar.collapsed, "Toolbar should be uncollapsed in private window");
- ok(!personalToolbar.collapsed, "Toolbar should be uncollapsed in normal window");
- ok(!resetButton.disabled, "Reset button should be enabled");
-
- yield this.otherWin.gCustomizeMode.reset();
-
- ok(otherPersonalToolbar.collapsed, "Toolbar should be collapsed in private window");
- ok(personalToolbar.collapsed, "Toolbar should be collapsed in normal window");
- ok(resetButton.disabled, "Reset button should be disabled");
-
- yield endCustomizing(this.otherWin);
-
- yield promiseWindowClosed(this.otherWin);
-});
-
-
-add_task(function* asyncCleanup() {
- if (this.otherWin && !this.otherWin.closed) {
- yield promiseWindowClosed(this.otherWin);
- }
- if (!CustomizableUI.inDefaultState) {
- CustomizableUI.reset();
- }
-});
diff --git a/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js b/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js
deleted file mode 100644
index 6a4d0aab4..000000000
--- a/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const BUTTONID = "test-XUL-wrapper-destroyWidget";
-
-
-add_task(function() {
- let btn = createDummyXULButton(BUTTONID, "XUL btn");
- gNavToolbox.palette.appendChild(btn);
- let firstWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window);
- ok(firstWrapper, "Should get a wrapper");
- ok(firstWrapper.node, "Node should be there on first wrapper.");
-
- btn.remove();
- CustomizableUI.destroyWidget(BUTTONID);
- let secondWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window);
- isnot(firstWrapper, secondWrapper, "Wrappers should be different after destroyWidget call.");
- ok(!firstWrapper.node, "No node should be there on old wrapper.");
- ok(!secondWrapper.node, "No node should be there on new wrapper.");
-
- btn = createDummyXULButton(BUTTONID, "XUL btn");
- gNavToolbox.palette.appendChild(btn);
- let thirdWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window);
- ok(thirdWrapper, "Should get a wrapper");
- is(secondWrapper, thirdWrapper, "Should get the second wrapper again.");
- ok(firstWrapper.node, "Node should be there on old wrapper.");
- ok(secondWrapper.node, "Node should be there on second wrapper.");
- ok(thirdWrapper.node, "Node should be there on third wrapper.");
-});
-
diff --git a/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js b/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js
deleted file mode 100644
index f838e204d..000000000
--- a/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const BUTTONID = "test-XUL-wrapper-widget";
-add_task(function() {
- let btn = createDummyXULButton(BUTTONID, "XUL btn");
- gNavToolbox.palette.appendChild(btn);
- let groupWrapper = CustomizableUI.getWidget(BUTTONID);
- ok(groupWrapper, "Should get a group wrapper");
- let singleWrapper = groupWrapper.forWindow(window);
- ok(singleWrapper, "Should get a single wrapper");
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR);
-
- let otherSingleWrapper = groupWrapper.forWindow(window);
- is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after adding the node to the navbar.");
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- CustomizableUI.removeWidgetFromArea(BUTTONID);
-
- otherSingleWrapper = groupWrapper.forWindow(window);
- isnot(singleWrapper, otherSingleWrapper, "Shouldn't get the same wrapper after removing it from the navbar.");
- singleWrapper = otherSingleWrapper;
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- btn.remove();
- otherSingleWrapper = groupWrapper.forWindow(window);
- is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after physically removing the node.");
- is(singleWrapper.node, null, "Wrapper's node should be null now that it's left the DOM.");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, null, "That instance should be null.");
-
- btn = createDummyXULButton(BUTTONID, "XUL btn");
- gNavToolbox.palette.appendChild(btn);
- otherSingleWrapper = groupWrapper.forWindow(window);
- is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after readding the node.");
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR);
-
- otherSingleWrapper = groupWrapper.forWindow(window);
- is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after adding the node to the navbar.");
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- CustomizableUI.removeWidgetFromArea(BUTTONID);
-
- otherSingleWrapper = groupWrapper.forWindow(window);
- isnot(singleWrapper, otherSingleWrapper, "Shouldn't get the same wrapper after removing it from the navbar.");
- singleWrapper = otherSingleWrapper;
- is(singleWrapper.node, btn, "Node should be in the wrapper");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, btn, "Button should be that instance.");
-
- btn.remove();
- otherSingleWrapper = groupWrapper.forWindow(window);
- is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after physically removing the node.");
- is(singleWrapper.node, null, "Wrapper's node should be null now that it's left the DOM.");
- is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper");
- is(groupWrapper.instances[0].node, null, "That instance should be null.");
-});
diff --git a/browser/components/customizableui/test/browser_987185_syncButton.js b/browser/components/customizableui/test/browser_987185_syncButton.js
deleted file mode 100755
index 988d738be..000000000
--- a/browser/components/customizableui/test/browser_987185_syncButton.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* 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/.
- */
-"use strict";
-
-var syncService = {};
-Components.utils.import("resource://services-sync/service.js", syncService);
-
-var needsSetup;
-var originalSync;
-var service = syncService.Service;
-var syncWasCalled = false;
-
-add_task(function* testSyncButtonFunctionality() {
- info("Check Sync button functionality");
- storeInitialValues();
- mockFunctions();
-
- // add the Sync button to the panel
- CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
-
- // check the button's functionality
- yield PanelUI.show();
- info("The panel menu was opened");
-
- let syncButton = document.getElementById("sync-button");
- ok(syncButton, "The Sync button was added to the Panel Menu");
- // click the button - the panel should open.
- syncButton.click();
- let syncPanel = document.getElementById("PanelUI-remotetabs");
- ok(syncPanel.getAttribute("current"), "Sync Panel is in view");
-
- // Find and click the "setup" button.
- let syncNowButton = document.getElementById("PanelUI-remotetabs-syncnow");
- syncNowButton.click();
-
- info("The sync button was clicked");
-
- yield waitForCondition(() => syncWasCalled);
-});
-
-add_task(function* asyncCleanup() {
- // reset the panel UI to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The panel UI is in default state again.");
-
- if (isPanelUIOpen()) {
- let panelHidePromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHidePromise;
- }
-
- restoreValues();
-});
-
-function mockFunctions() {
- // mock needsSetup
- gSyncUI._needsSetup = () => Promise.resolve(false);
-
- // mock service.errorHandler.syncAndReportErrors()
- service.errorHandler.syncAndReportErrors = mocked_syncAndReportErrors;
-}
-
-function mocked_syncAndReportErrors() {
- syncWasCalled = true;
-}
-
-function restoreValues() {
- gSyncUI._needsSetup = needsSetup;
- service.sync = originalSync;
-}
-
-function storeInitialValues() {
- needsSetup = gSyncUI._needsSetup;
- originalSync = service.sync;
-}
diff --git a/browser/components/customizableui/test/browser_987492_window_api.js b/browser/components/customizableui/test/browser_987492_window_api.js
deleted file mode 100644
index 1718303e1..000000000
--- a/browser/components/customizableui/test/browser_987492_window_api.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-
-add_task(function* testOneWindow() {
- let windows = [];
- for (let win of CustomizableUI.windows)
- windows.push(win);
- is(windows.length, 1, "Should have one customizable window");
-});
-
-
-add_task(function* testOpenCloseWindow() {
- let newWindow = null;
- let openListener = {
- onWindowOpened: function(window) {
- newWindow = window;
- }
- }
- CustomizableUI.addListener(openListener);
- let win = yield openAndLoadWindow(null, true);
- isnot(newWindow, null, "Should have gotten onWindowOpen event");
- is(newWindow, win, "onWindowOpen event should have received expected window");
- CustomizableUI.removeListener(openListener);
-
- let windows = [];
- for (let win of CustomizableUI.windows)
- windows.push(win);
- is(windows.length, 2, "Should have two customizable windows");
- isnot(windows.indexOf(window), -1, "Current window should be in window collection.");
- isnot(windows.indexOf(newWindow), -1, "New window should be in window collection.");
-
- let closedWindow = null;
- let closeListener = {
- onWindowClosed: function(window) {
- closedWindow = window;
- }
- }
- CustomizableUI.addListener(closeListener);
- yield promiseWindowClosed(newWindow);
- isnot(closedWindow, null, "Should have gotten onWindowClosed event")
- is(newWindow, closedWindow, "Closed window should match previously opened window");
- CustomizableUI.removeListener(closeListener);
-
- windows = [];
- for (let win of CustomizableUI.windows)
- windows.push(win);
- is(windows.length, 1, "Should have one customizable window");
- isnot(windows.indexOf(window), -1, "Current window should be in window collection.");
- is(windows.indexOf(closedWindow), -1, "Closed window should not be in window collection.");
-});
diff --git a/browser/components/customizableui/test/browser_987640_charEncoding.js b/browser/components/customizableui/test/browser_987640_charEncoding.js
deleted file mode 100644
index dfe02f940..000000000
--- a/browser/components/customizableui/test/browser_987640_charEncoding.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/customizableui/test/support/test_967000_charEncoding_page.html";
-
-add_task(function*() {
- info("Check Character Encoding panel functionality");
-
- // add the Character Encoding button to the panel
- CustomizableUI.addWidgetToArea("characterencoding-button",
- CustomizableUI.AREA_PANEL);
-
- let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_PAGE, true, true);
-
- yield PanelUI.show();
- let charEncodingButton = document.getElementById("characterencoding-button");
- let characterEncodingView = document.getElementById("PanelUI-characterEncodingView");
- let subviewShownPromise = subviewShown(characterEncodingView);
- charEncodingButton.click();
- yield subviewShownPromise;
-
- let checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']");
- let initialEncoding = checkedButtons[0];
- is(initialEncoding.getAttribute("label"), "Unicode", "The unicode encoding is initially selected");
-
- // change the encoding
- let encodings = characterEncodingView.querySelectorAll("toolbarbutton");
- let newEncoding = encodings[0].hasAttribute("checked") ? encodings[1] : encodings[0];
- let tabLoadPromise = promiseTabLoadEvent(gBrowser.selectedTab, TEST_PAGE);
- newEncoding.click();
- yield tabLoadPromise;
-
- // check that the new encodng is applied
- yield PanelUI.show();
- charEncodingButton.click();
- checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']");
- let selectedEncodingName = checkedButtons[0].getAttribute("label");
- ok(selectedEncodingName != "Unicode", "The encoding was changed to " + selectedEncodingName);
-
- // reset the initial encoding
- yield PanelUI.show();
- charEncodingButton.click();
- tabLoadPromise = promiseTabLoadEvent(gBrowser.selectedTab, TEST_PAGE);
- initialEncoding.click();
- yield tabLoadPromise;
- yield PanelUI.show();
- charEncodingButton.click();
- checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']");
- is(checkedButtons[0].getAttribute("label"), "Unicode", "The encoding was reset to Unicode");
- yield BrowserTestUtils.removeTab(newTab);
-});
-
-add_task(function* asyncCleanup() {
- // reset the panel to the default state
- yield resetCustomization();
- ok(CustomizableUI.inDefaultState, "The UI is in default state again.");
-});
diff --git a/browser/components/customizableui/test/browser_988072_sidebar_events.js b/browser/components/customizableui/test/browser_988072_sidebar_events.js
deleted file mode 100644
index 6791be67a..000000000
--- a/browser/components/customizableui/test/browser_988072_sidebar_events.js
+++ /dev/null
@@ -1,392 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var gSidebarMenu = document.getElementById("viewSidebarMenu");
-var gTestSidebarItem = null;
-
-var EVENTS = {
- click: 0, command: 0,
- onclick: 0, oncommand: 0
-};
-
-window.sawEvent = function(event, isattr) {
- let type = (isattr ? "on" : "") + event.type
- EVENTS[type]++;
-};
-
-registerCleanupFunction(() => {
- delete window.sawEvent;
-
- // Ensure sidebar is hidden after each test:
- if (!document.getElementById("sidebar-box").hidden) {
- SidebarUI.hide();
- }
-});
-
-function checkExpectedEvents(expected) {
- for (let type of Object.keys(EVENTS)) {
- let count = (type in expected ? expected[type] : 0);
- is(EVENTS[type], count, "Should have seen the right number of " + type + " events");
- EVENTS[type] = 0;
- }
-}
-
-function createSidebarItem() {
- gTestSidebarItem = document.createElement("menuitem");
- gTestSidebarItem.id = "testsidebar";
- gTestSidebarItem.setAttribute("label", "Test Sidebar");
- gSidebarMenu.insertBefore(gTestSidebarItem, gSidebarMenu.firstChild);
-}
-
-function addWidget() {
- CustomizableUI.addWidgetToArea("sidebar-button", "nav-bar");
- PanelUI.disableSingleSubviewPanelAnimations();
-}
-
-function removeWidget() {
- CustomizableUI.removeWidgetFromArea("sidebar-button");
- PanelUI.enableSingleSubviewPanelAnimations();
-}
-
-// Filters out the trailing menuseparators from the sidebar list
-function getSidebarList() {
- let sidebars = [...gSidebarMenu.children].filter(sidebar => {
- if (sidebar.localName == "menuseparator")
- return false;
- if (sidebar.getAttribute("hidden") == "true")
- return false;
- return true;
- });
- return sidebars;
-}
-
-function compareElements(original, displayed) {
- let attrs = ["label", "key", "disabled", "hidden", "origin", "image", "checked"];
- for (let attr of attrs) {
- is(displayed.getAttribute(attr), original.getAttribute(attr), "Should have the same " + attr + " attribute");
- }
-}
-
-function compareList(original, displayed) {
- is(displayed.length, original.length, "Should have the same number of children");
-
- for (let i = 0; i < Math.min(original.length, displayed.length); i++) {
- compareElements(displayed[i], original[i]);
- }
-}
-
-var showSidebarPopup = Task.async(function*() {
- let button = document.getElementById("sidebar-button");
- let subview = document.getElementById("PanelUI-sidebar");
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown");
-
- let subviewShownPromise = subviewShown(subview);
- EventUtils.synthesizeMouseAtCenter(button, {});
- return Promise.all([subviewShownPromise, popupShownPromise]);
-});
-
-// Check the sidebar widget shows the default items
-add_task(function*() {
- addWidget();
-
- yield showSidebarPopup();
-
- let sidebars = getSidebarList();
- let displayed = [...document.getElementById("PanelUI-sidebarItems").children];
- compareList(sidebars, displayed);
-
- let subview = document.getElementById("PanelUI-sidebar");
- let subviewHiddenPromise = subviewHidden(subview);
- document.getElementById("customizationui-widget-panel").hidePopup();
- yield subviewHiddenPromise;
-
- removeWidget();
-});
-
-function add_sidebar_task(description, setup, teardown) {
- add_task(function*() {
- info(description);
- createSidebarItem();
- addWidget();
- yield setup();
-
- CustomizableUI.addWidgetToArea("sidebar-button", "nav-bar");
-
- yield showSidebarPopup();
-
- let sidebars = getSidebarList();
- let displayed = [...document.getElementById("PanelUI-sidebarItems").children];
- compareList(sidebars, displayed);
-
- is(displayed[0].label, "Test Sidebar", "Should have the right element at the top");
- let subview = document.getElementById("PanelUI-sidebar");
- let subviewHiddenPromise = subviewHidden(subview);
- EventUtils.synthesizeMouseAtCenter(displayed[0], {});
- yield subviewHiddenPromise;
-
- yield teardown();
- gTestSidebarItem.remove();
- removeWidget();
- });
-}
-
-add_sidebar_task(
- "Check that a sidebar that uses a command event listener works",
-function*() {
- gTestSidebarItem.addEventListener("command", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ command: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a click event listener works",
-function*() {
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ click: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses both click and command event listeners works",
-function*() {
- gTestSidebarItem.addEventListener("command", window.sawEvent);
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ command: 1, click: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses an oncommand attribute works",
-function*() {
- gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)");
-}, function*() {
- checkExpectedEvents({ oncommand: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses an onclick attribute works",
-function*() {
- gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)");
-}, function*() {
- checkExpectedEvents({ onclick: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses both onclick and oncommand attributes works",
-function*() {
- gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)");
- gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)");
-}, function*() {
- checkExpectedEvents({ onclick: 1, oncommand: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses an onclick attribute and a command listener works",
-function*() {
- gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)");
- gTestSidebarItem.addEventListener("command", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ onclick: 1, command: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses an oncommand attribute and a click listener works",
-function*() {
- gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)");
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ click: 1, oncommand: 1 });
-});
-
-add_sidebar_task(
- "A sidebar with both onclick attribute and click listener sees only one event :(",
-function*() {
- gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)");
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ onclick: 1 });
-});
-
-add_sidebar_task(
- "A sidebar with both oncommand attribute and command listener sees only one event :(",
-function*() {
- gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)");
- gTestSidebarItem.addEventListener("command", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ oncommand: 1 });
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a broadcaster with an oncommand attribute works",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
-}, function*() {
- checkExpectedEvents({ oncommand: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a broadcaster with an onclick attribute works",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("onclick", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
-}, function*() {
- checkExpectedEvents({ onclick: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a broadcaster with both onclick and oncommand attributes works",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("onclick", "window.sawEvent(event, true)");
- broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
-}, function*() {
- checkExpectedEvents({ onclick: 1, oncommand: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar with a click listener and a broadcaster with an oncommand attribute works",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ click: 1, oncommand: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar with a command listener and a broadcaster with an onclick attribute works",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("onclick", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
- gTestSidebarItem.addEventListener("command", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ onclick: 1, command: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar with a click listener and a broadcaster with an onclick " +
- "attribute only sees one event :(",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("onclick", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ onclick: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar with a command listener and a broadcaster with an oncommand " +
- "attribute only sees one event :(",
-function*() {
- let broadcaster = document.createElement("broadcaster");
- broadcaster.setAttribute("id", "testbroadcaster");
- broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)");
- broadcaster.setAttribute("label", "Test Sidebar");
- document.getElementById("mainBroadcasterSet").appendChild(broadcaster);
-
- gTestSidebarItem.setAttribute("observes", "testbroadcaster");
- gTestSidebarItem.addEventListener("command", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ oncommand: 1 });
- document.getElementById("testbroadcaster").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a command element with a command event listener works",
-function*() {
- let command = document.createElement("command");
- command.setAttribute("id", "testcommand");
- document.getElementById("mainCommandSet").appendChild(command);
- command.addEventListener("command", window.sawEvent);
-
- gTestSidebarItem.setAttribute("command", "testcommand");
-}, function*() {
- checkExpectedEvents({ command: 1 });
- document.getElementById("testcommand").remove();
-});
-
-add_sidebar_task(
- "Check that a sidebar that uses a command element with an oncommand attribute works",
-function*() {
- let command = document.createElement("command");
- command.setAttribute("id", "testcommand");
- command.setAttribute("oncommand", "window.sawEvent(event, true)");
- document.getElementById("mainCommandSet").appendChild(command);
-
- gTestSidebarItem.setAttribute("command", "testcommand");
-}, function*() {
- checkExpectedEvents({ oncommand: 1 });
- document.getElementById("testcommand").remove();
-});
-
-add_sidebar_task("Check that a sidebar that uses a command element with a " +
- "command event listener and oncommand attribute works",
-function*() {
- let command = document.createElement("command");
- command.setAttribute("id", "testcommand");
- command.setAttribute("oncommand", "window.sawEvent(event, true)");
- document.getElementById("mainCommandSet").appendChild(command);
- command.addEventListener("command", window.sawEvent);
-
- gTestSidebarItem.setAttribute("command", "testcommand");
-}, function*() {
- checkExpectedEvents({ command: 1, oncommand: 1 });
- document.getElementById("testcommand").remove();
-});
-
-add_sidebar_task(
- "A sidebar with a command element will still see click events",
-function*() {
- let command = document.createElement("command");
- command.setAttribute("id", "testcommand");
- command.setAttribute("oncommand", "window.sawEvent(event, true)");
- document.getElementById("mainCommandSet").appendChild(command);
- command.addEventListener("command", window.sawEvent);
-
- gTestSidebarItem.setAttribute("command", "testcommand");
- gTestSidebarItem.addEventListener("click", window.sawEvent);
-}, function*() {
- checkExpectedEvents({ click: 1, command: 1, oncommand: 1 });
- document.getElementById("testcommand").remove();
-});
diff --git a/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js b/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js
deleted file mode 100644
index 2a1b01bf7..000000000
--- a/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const BUTTONID = "test-widget-saved-earlier";
-const AREAID = "test-area-saved-earlier";
-
-var hadSavedState;
-function test() {
- // Hack our way into the module to fake a saved state that isn't there...
- let backstagePass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
- hadSavedState = backstagePass.gSavedState != null;
- if (!hadSavedState) {
- backstagePass.gSavedState = {placements: {}};
- }
- backstagePass.gSavedState.placements[AREAID] = [BUTTONID];
- // Put bogus stuff in the saved state for the nav-bar, so as to check the current placements
- // override this one...
- backstagePass.gSavedState.placements[CustomizableUI.AREA_NAVBAR] = ["bogus-navbar-item"];
-
- backstagePass.gDirty = true;
- backstagePass.CustomizableUIInternal.saveState();
-
- let newSavedState = JSON.parse(Services.prefs.getCharPref("browser.uiCustomization.state"));
- let savedArea = Array.isArray(newSavedState.placements[AREAID]);
- ok(savedArea, "Should have re-saved the state, even though the area isn't registered");
-
- if (savedArea) {
- placementArraysEqual(AREAID, newSavedState.placements[AREAID], [BUTTONID]);
- }
- ok(!backstagePass.gPlacements.has(AREAID), "Placements map shouldn't have been affected");
-
- let savedNavbar = Array.isArray(newSavedState.placements[CustomizableUI.AREA_NAVBAR]);
- ok(savedNavbar, "Should have saved nav-bar contents");
- if (savedNavbar) {
- placementArraysEqual(CustomizableUI.AREA_NAVBAR, newSavedState.placements[CustomizableUI.AREA_NAVBAR],
- CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR));
- }
-}
-
-registerCleanupFunction(function() {
- let backstagePass = Cu.import("resource:///modules/CustomizableUI.jsm", {});
- if (!hadSavedState) {
- backstagePass.gSavedState = null;
- } else {
- let savedPlacements = backstagePass.gSavedState.placements;
- delete savedPlacements[AREAID];
- let realNavBarPlacements = CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR);
- savedPlacements[CustomizableUI.AREA_NAVBAR] = realNavBarPlacements;
- }
- backstagePass.gDirty = true;
- backstagePass.CustomizableUIInternal.saveState();
-});
-
diff --git a/browser/components/customizableui/test/browser_989751_subviewbutton_class.js b/browser/components/customizableui/test/browser_989751_subviewbutton_class.js
deleted file mode 100644
index 0d11324ed..000000000
--- a/browser/components/customizableui/test/browser_989751_subviewbutton_class.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const kCustomClass = "acustomclassnoonewilluse";
-var tempElement = null;
-
-function insertClassNameToMenuChildren(parentMenu) {
- let el = parentMenu.querySelector("menuitem:first-of-type");
- el.classList.add(kCustomClass);
- tempElement = el;
-}
-
-function checkSubviewButtonClass(menuId, buttonId, subviewId) {
- return function*() {
- info("Checking for items without the subviewbutton class in " + buttonId + " widget");
- let menu = document.getElementById(menuId);
- insertClassNameToMenuChildren(menu);
-
- let placement = CustomizableUI.getPlacementOfWidget(buttonId);
- let changedPlacement = false;
- if (!placement || placement.area != CustomizableUI.AREA_PANEL) {
- CustomizableUI.addWidgetToArea(buttonId, CustomizableUI.AREA_PANEL);
- changedPlacement = true;
- }
- yield PanelUI.show();
-
- let button = document.getElementById(buttonId);
- button.click();
-
- yield waitForCondition(() => !PanelUI.multiView.hasAttribute("transitioning"));
- let subview = document.getElementById(subviewId);
- ok(subview.firstChild, "Subview should have a kid");
- let subviewchildren = subview.querySelectorAll("toolbarbutton");
- for (let i = 0; i < subviewchildren.length; i++) {
- let item = subviewchildren[i];
- let itemReadable = "Item '" + item.label + "' (classes: " + item.className + ")";
- ok(item.classList.contains("subviewbutton"), itemReadable + " should have the subviewbutton class.");
- if (i == 0) {
- ok(item.classList.contains(kCustomClass), itemReadable + " should still have its own class, too.");
- }
- }
-
- let panelHiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield panelHiddenPromise;
-
- if (changedPlacement) {
- CustomizableUI.reset();
- }
- };
-}
-
-add_task(checkSubviewButtonClass("menuWebDeveloperPopup", "developer-button", "PanelUI-developerItems"));
-add_task(checkSubviewButtonClass("viewSidebarMenu", "sidebar-button", "PanelUI-sidebarItems"));
-
-registerCleanupFunction(function() {
- tempElement.classList.remove(kCustomClass)
- tempElement = null;
-});
diff --git a/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js b/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js
deleted file mode 100644
index eb0a8c8ee..000000000
--- a/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TOOLBARID = "test-noncustomizable-toolbar-for-toggling";
-function test() {
- let tb = document.createElementNS(kNSXUL, "toolbar");
- tb.id = TOOLBARID;
- gNavToolbox.appendChild(tb);
- try {
- CustomizableUI.setToolbarVisibility(TOOLBARID, false);
- } catch (ex) {
- ok(false, "Should not throw exceptions trying to set toolbar visibility.");
- }
- is(tb.getAttribute("collapsed"), "true", "Toolbar should be collapsed");
- try {
- CustomizableUI.setToolbarVisibility(TOOLBARID, true);
- } catch (ex) {
- ok(false, "Should not throw exceptions trying to set toolbar visibility.");
- }
- is(tb.getAttribute("collapsed"), "false", "Toolbar should be uncollapsed");
- tb.remove();
-}
-
diff --git a/browser/components/customizableui/test/browser_993322_widget_notoolbar.js b/browser/components/customizableui/test/browser_993322_widget_notoolbar.js
deleted file mode 100644
index 9264eb78a..000000000
--- a/browser/components/customizableui/test/browser_993322_widget_notoolbar.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const BUTTONID = "test-API-created-widget-toolbar-gone";
-const TOOLBARID = "test-API-created-extra-toolbar";
-
-add_task(function*() {
- let toolbar = createToolbarWithPlacements(TOOLBARID, []);
- CustomizableUI.addWidgetToArea(BUTTONID, TOOLBARID);
- is(CustomizableUI.getPlacementOfWidget(BUTTONID).area, TOOLBARID, "Should be on toolbar");
- is(toolbar.children.length, 0, "Toolbar has no kid");
-
- CustomizableUI.unregisterArea(TOOLBARID);
- CustomizableUI.createWidget({id: BUTTONID, label: "Test widget toolbar gone"});
-
- let currentWidget = CustomizableUI.getWidget(BUTTONID);
-
- yield startCustomizing();
- let buttonNode = document.getElementById(BUTTONID);
- ok(buttonNode, "Should find button in window");
- if (buttonNode) {
- is(buttonNode.parentNode.localName, "toolbarpaletteitem", "Node should be wrapped");
- is(buttonNode.parentNode.getAttribute("place"), "palette", "Node should be in palette");
- is(buttonNode, gNavToolbox.palette.querySelector("#" + BUTTONID), "Node should really be in palette.");
- }
- is(currentWidget.forWindow(window).node, buttonNode, "Should have the same node for customize mode");
- yield endCustomizing();
-
- CustomizableUI.destroyWidget(BUTTONID);
- CustomizableUI.unregisterArea(TOOLBARID, true);
- toolbar.remove();
- gAddedToolbars.clear();
-});
diff --git a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js
deleted file mode 100644
index 4d292a929..000000000
--- a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js
+++ /dev/null
@@ -1,149 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TOOLBARID = "test-toolbar-added-during-customize-mode";
-
-// The ID of a button that is not placed (ie, is in the palette) by default
-const kNonPlacedWidgetId = "open-file-button";
-
-add_task(function*() {
- yield startCustomizing();
- let toolbar = createToolbarWithPlacements(TOOLBARID, []);
- CustomizableUI.addWidgetToArea(kNonPlacedWidgetId, TOOLBARID);
- let button = document.getElementById(kNonPlacedWidgetId);
- ok(button, "Button should exist.");
- is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should be a wrapper.");
-
- simulateItemDrag(button, gNavToolbox.palette);
- ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette");
- ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette.");
-
- button.scrollIntoView();
- simulateItemDrag(button, toolbar);
- ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette");
- is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar");
- ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar.");
-
- yield endCustomizing();
- isnot(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should not be a wrapper outside customize mode.");
- yield startCustomizing();
-
- is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should be a wrapper back in customize mode.");
-
- simulateItemDrag(button, gNavToolbox.palette);
- ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette");
- ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette.");
-
- ok(!CustomizableUI.inDefaultState, "Not in default state while toolbar is not collapsed yet.");
- setToolbarVisibility(toolbar, false);
- ok(CustomizableUI.inDefaultState, "In default state while toolbar is collapsed.");
-
- setToolbarVisibility(toolbar, true);
-
- info("Check that removing the area registration from within customize mode works");
- CustomizableUI.unregisterArea(TOOLBARID);
- ok(CustomizableUI.inDefaultState, "Now that the toolbar is no longer registered, should be in default state.");
- ok(!gCustomizeMode.areas.has(toolbar), "Toolbar shouldn't be known to customize mode.");
-
- CustomizableUI.registerArea(TOOLBARID, {legacy: true, defaultPlacements: []});
- CustomizableUI.registerToolbarNode(toolbar, []);
- ok(!CustomizableUI.inDefaultState, "Now that the toolbar is registered again, should no longer be in default state.");
- ok(gCustomizeMode.areas.has(toolbar), "Toolbar should be known to customize mode again.");
-
- button.scrollIntoView();
- simulateItemDrag(button, toolbar);
- ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette");
- is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar");
- ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar.");
-
- let otherWin = yield openAndLoadWindow({}, true);
- let otherTB = otherWin.document.createElementNS(kNSXUL, "toolbar");
- otherTB.id = TOOLBARID;
- otherTB.setAttribute("customizable", "true");
- let wasInformedCorrectlyOfAreaAppearing = false;
- let listener = {
- onAreaNodeRegistered: function(aArea, aNode) {
- if (aNode == otherTB) {
- wasInformedCorrectlyOfAreaAppearing = true;
- }
- }
- };
- CustomizableUI.addListener(listener);
- otherWin.gNavToolbox.appendChild(otherTB);
- ok(wasInformedCorrectlyOfAreaAppearing, "Should have been told area was registered.");
- CustomizableUI.removeListener(listener);
-
- ok(otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is on other toolbar, too.");
-
- simulateItemDrag(button, gNavToolbox.palette);
- ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette");
- ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette.");
- ok(!otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is in palette in other window, too.");
-
- button.scrollIntoView();
- simulateItemDrag(button, toolbar);
- ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette");
- is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar");
- ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar.");
- ok(otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is on other toolbar, too.");
-
- let wasInformedCorrectlyOfAreaDisappearing = false;
- // XXXgijs So we could be using promiseWindowClosed here. However, after
- // repeated random oranges, I'm instead relying on onWindowClosed below to
- // fire appropriately - it is linked to an unload event as well, and so
- // reusing it prevents a potential race between unload handlers where the
- // one from promiseWindowClosed could fire before the onWindowClosed
- // (and therefore onAreaNodeRegistered) one, causing the test to fail.
- let windowCloseDeferred = Promise.defer();
- listener = {
- onAreaNodeUnregistered: function(aArea, aNode, aReason) {
- if (aArea == TOOLBARID) {
- is(aNode, otherTB, "Should be informed about other toolbar");
- is(aReason, CustomizableUI.REASON_WINDOW_CLOSED, "Reason should be correct.");
- wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_WINDOW_CLOSED);
- }
- },
- onWindowClosed: function(aWindow) {
- if (aWindow == otherWin) {
- windowCloseDeferred.resolve(aWindow);
- } else {
- info("Other window was closed!");
- info("Other window title: " + (aWindow.document && aWindow.document.title));
- info("Our window title: " + (otherWin.document && otherWin.document.title));
- }
- },
- };
- CustomizableUI.addListener(listener);
- otherWin.close();
- let windowClosed = yield windowCloseDeferred.promise;
-
- is(windowClosed, otherWin, "Window should have sent onWindowClosed notification.");
- ok(wasInformedCorrectlyOfAreaDisappearing, "Should be told about window closing.");
- // Closing the other window should not be counted against this window's customize mode:
- is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should still be a wrapper.");
- ok(gCustomizeMode.areas.has(toolbar), "Toolbar should still be a customizable area for this customize mode instance.");
-
- yield gCustomizeMode.reset();
-
- yield endCustomizing();
-
- CustomizableUI.removeListener(listener);
- wasInformedCorrectlyOfAreaDisappearing = false;
- listener = {
- onAreaNodeUnregistered: function(aArea, aNode, aReason) {
- if (aArea == TOOLBARID) {
- is(aNode, toolbar, "Should be informed about this window's toolbar");
- is(aReason, CustomizableUI.REASON_AREA_UNREGISTERED, "Reason for final removal should be correct.");
- wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_AREA_UNREGISTERED);
- }
- },
- }
- CustomizableUI.addListener(listener);
- removeCustomToolbars();
- ok(wasInformedCorrectlyOfAreaDisappearing, "Should be told about area being unregistered.");
- CustomizableUI.removeListener(listener);
- ok(CustomizableUI.inDefaultState, "Should be fine after exiting customize mode.");
-});
diff --git a/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js b/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js
deleted file mode 100644
index b9de5f687..000000000
--- a/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Calling CustomizableUI.registerArea twice with no
-// properties should not throw an exception.
-add_task(function() {
- try {
- CustomizableUI.registerArea("area-996364", {});
- CustomizableUI.registerArea("area-996364", {});
- } catch (ex) {
- ok(false, ex.message);
- }
-
- CustomizableUI.unregisterArea("area-996364", true);
-});
-
-add_task(function() {
- let exceptionThrown = false;
- try {
- CustomizableUI.registerArea("area-996364-2", {type: CustomizableUI.TYPE_TOOLBAR, defaultCollapsed: "false"});
- } catch (ex) {
- exceptionThrown = true;
- }
- ok(exceptionThrown, "defaultCollapsed is not allowed as an external property");
-
- // No need to unregister the area because registration fails.
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996364-3", {type: CustomizableUI.TYPE_TOOLBAR});
- CustomizableUI.registerArea("area-996364-3", {type: CustomizableUI.TYPE_MENU_PANEL});
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(exceptionThrown, "Exception expected, an area cannot change types: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
-
- CustomizableUI.unregisterArea("area-996364-3", true);
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996364-4", {type: CustomizableUI.TYPE_MENU_PANEL});
- CustomizableUI.registerArea("area-996364-4", {type: CustomizableUI.TYPE_TOOLBAR});
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(exceptionThrown, "Exception expected, an area cannot change types: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
-
- CustomizableUI.unregisterArea("area-996364-4", true);
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996899-1", { anchor: "PanelUI-menu-button",
- type: CustomizableUI.TYPE_MENU_PANEL,
- defaultPlacements: [] });
- CustomizableUI.registerArea("area-996899-1", { anchor: "home-button",
- type: CustomizableUI.TYPE_MENU_PANEL,
- defaultPlacements: [] });
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(!exceptionThrown, "Changing anchors shouldn't throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
- CustomizableUI.unregisterArea("area-996899-1", true);
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996899-2", { anchor: "PanelUI-menu-button",
- type: CustomizableUI.TYPE_MENU_PANEL,
- defaultPlacements: [] });
- CustomizableUI.registerArea("area-996899-2", { anchor: "PanelUI-menu-button",
- type: CustomizableUI.TYPE_MENU_PANEL,
- defaultPlacements: ["feed-button"] });
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(!exceptionThrown, "Changing defaultPlacements shouldn't throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
- CustomizableUI.unregisterArea("area-996899-2", true);
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996899-3", { legacy: true });
- CustomizableUI.registerArea("area-996899-3", { legacy: false });
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(exceptionThrown, "Changing 'legacy' should throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
- CustomizableUI.unregisterArea("area-996899-3", true);
-});
-
-add_task(function() {
- let exceptionThrown;
- try {
- CustomizableUI.registerArea("area-996899-4", { overflowable: true });
- CustomizableUI.registerArea("area-996899-4", { overflowable: false });
- } catch (ex) {
- exceptionThrown = ex;
- }
- ok(exceptionThrown, "Changing 'overflowable' should throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]"));
- CustomizableUI.unregisterArea("area-996899-4", true);
-});
diff --git a/browser/components/customizableui/test/browser_996635_remove_non_widgets.js b/browser/components/customizableui/test/browser_996635_remove_non_widgets.js
deleted file mode 100644
index 14a446eec..000000000
--- a/browser/components/customizableui/test/browser_996635_remove_non_widgets.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// NB: This is testing what happens if something that /isn't/ a customizable
-// widget gets used in CustomizableUI APIs. Don't use this as an example of
-// what should happen in a "normal" case or how you should use the API.
-function test() {
- // First create a button that isn't customizable, and add it in the nav-bar,
- // but not in the customizable part of it (the customization target) but
- // next to the main (hamburger) menu button.
- const buttonID = "Test-non-widget-non-removable-button";
- let btn = document.createElement("toolbarbutton");
- btn.id = buttonID;
- btn.label = "Hi";
- btn.setAttribute("style", "width: 20px; height: 20px; background-color: red");
- document.getElementById("nav-bar").appendChild(btn);
- registerCleanupFunction(function() {
- btn.remove();
- });
-
- // Now try to add this non-customizable button to the tabstrip. This will
- // update the internal bookkeeping (ie placements) information, but shouldn't
- // move the node.
- CustomizableUI.addWidgetToArea(buttonID, CustomizableUI.AREA_TABSTRIP);
- let placement = CustomizableUI.getPlacementOfWidget(buttonID);
- // Check our bookkeeping
- ok(placement, "Button should be placed");
- is(placement && placement.area, CustomizableUI.AREA_TABSTRIP, "Should be placed on tabstrip.");
- // Check we didn't move the node.
- is(btn.parentNode && btn.parentNode.id, "nav-bar", "Actual button should still be on navbar.");
-
- // Now remove the node again. This should remove the bookkeeping, but again
- // not affect the actual node.
- CustomizableUI.removeWidgetFromArea(buttonID);
- placement = CustomizableUI.getPlacementOfWidget(buttonID);
- // Check our bookkeeping:
- ok(!placement, "Button should no longer have a placement.");
- // Check our node.
- is(btn.parentNode && btn.parentNode.id, "nav-bar", "Actual button should still be on navbar.");
-}
-
diff --git a/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js b/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js
deleted file mode 100644
index 2c5f0c79c..000000000
--- a/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-const kTestBarID = "testBar";
-const kWidgetID = "characterencoding-button";
-
-function createTestBar(aLegacy) {
- let testBar = document.createElement("toolbar");
- testBar.id = kTestBarID;
- testBar.setAttribute("customizable", "true");
- CustomizableUI.registerArea(kTestBarID, {
- type: CustomizableUI.TYPE_TOOLBAR,
- legacy: aLegacy,
- });
- gNavToolbox.appendChild(testBar);
- return testBar;
-}
-
-/**
- * Helper function that does the following:
- *
- * 1) Creates a custom toolbar and registers it
- * with CustomizableUI. Sets the legacy attribute
- * of the object passed to registerArea to aLegacy.
- * 2) Adds the widget with ID aWidgetID to that new
- * toolbar.
- * 3) Enters customize mode and makes sure that the
- * widget is still in the right toolbar.
- * 4) Exits customize mode, then removes and deregisters
- * the custom toolbar.
- * 5) Checks that the widget has no placement.
- * 6) Re-adds and re-registers a custom toolbar with the same
- * ID and options as the first one.
- * 7) Enters customize mode and checks that the widget is
- * properly back in the toolbar.
- * 8) Exits customize mode, removes and de-registers the
- * toolbar, and resets the toolbars to default.
- */
-function checkRestoredPresence(aWidgetID, aLegacy) {
- return Task.spawn(function* () {
- let testBar = createTestBar(aLegacy);
- CustomizableUI.addWidgetToArea(aWidgetID, kTestBarID);
- let placement = CustomizableUI.getPlacementOfWidget(aWidgetID);
- is(placement.area, kTestBarID,
- "Expected " + aWidgetID + " to be in the test toolbar");
-
- CustomizableUI.unregisterArea(testBar.id);
- testBar.remove();
-
- placement = CustomizableUI.getPlacementOfWidget(aWidgetID);
- is(placement, null, "Expected " + aWidgetID + " to be in the palette");
-
- testBar = createTestBar(aLegacy);
-
- yield startCustomizing();
- placement = CustomizableUI.getPlacementOfWidget(aWidgetID);
- is(placement.area, kTestBarID,
- "Expected " + aWidgetID + " to be in the test toolbar");
- yield endCustomizing();
-
- CustomizableUI.unregisterArea(testBar.id);
- testBar.remove();
-
- yield resetCustomization();
- });
-}
-
-add_task(function* () {
- yield checkRestoredPresence("downloads-button", false);
- yield checkRestoredPresence("downloads-button", true);
-});
-
-add_task(function* () {
- yield checkRestoredPresence("characterencoding-button", false);
- yield checkRestoredPresence("characterencoding-button", true);
-});
diff --git a/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js b/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js
deleted file mode 100644
index 31dd42ad8..000000000
--- a/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js
+++ /dev/null
@@ -1,14 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function* check_tooltips_in_navbar() {
- yield startCustomizing();
- let homeButtonWrapper = document.getElementById("wrapper-home-button");
- let homeButton = document.getElementById("home-button");
- is(homeButtonWrapper.getAttribute("tooltiptext"), homeButton.getAttribute("label"), "the wrapper's tooltip should match the button's label");
- ok(homeButtonWrapper.getAttribute("tooltiptext"), "the button should have tooltip text");
- yield endCustomizing();
-});
diff --git a/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js b/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js
deleted file mode 100644
index 8e1950291..000000000
--- a/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js
+++ /dev/null
@@ -1,24 +0,0 @@
-"use strict";
-
-add_task(function*() {
- ok(!PanelUI.menuButton.hasAttribute("open"), "Menu button should not be 'pressed' outside customize mode");
- yield startCustomizing();
-
- is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode");
-
- let contextMenu = document.getElementById("customizationPanelItemContextMenu");
- let shownPromise = popupShown(contextMenu);
- let newWindowButton = document.getElementById("wrapper-new-window-button");
- EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2});
- yield shownPromise;
- is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode after opening a context menu");
-
- let hiddenContextPromise = popupHidden(contextMenu);
- contextMenu.hidePopup();
- yield hiddenContextPromise;
- is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode after hiding a context menu");
- yield endCustomizing();
-
- ok(!PanelUI.menuButton.hasAttribute("open"), "Menu button should not be 'pressed' after ending customize mode");
-});
-
diff --git a/browser/components/customizableui/test/browser_panel_toggle.js b/browser/components/customizableui/test/browser_panel_toggle.js
deleted file mode 100644
index 4c286fb85..000000000
--- a/browser/components/customizableui/test/browser_panel_toggle.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-/**
- * Test opening and closing the menu panel UI.
- */
-
-// Show and hide the menu panel programmatically without an event (like UITour.jsm would)
-add_task(function*() {
- let shownPromise = promisePanelShown(window);
- PanelUI.show();
- yield shownPromise;
-
- is(PanelUI.panel.getAttribute("panelopen"), "true", "Check that panel has panelopen attribute");
- is(PanelUI.panel.state, "open", "Check that panel state is 'open'");
-
- let hiddenPromise = promisePanelHidden(window);
- PanelUI.hide();
- yield hiddenPromise;
-
- ok(!PanelUI.panel.hasAttribute("panelopen"), "Check that panel doesn't have the panelopen attribute");
- is(PanelUI.panel.state, "closed", "Check that panel state is 'closed'");
-});
-
-// Toggle the menu panel open and closed
-add_task(function*() {
- let shownPromise = promisePanelShown(window);
- PanelUI.toggle({type: "command"});
- yield shownPromise;
-
- is(PanelUI.panel.getAttribute("panelopen"), "true", "Check that panel has panelopen attribute");
- is(PanelUI.panel.state, "open", "Check that panel state is 'open'");
-
- let hiddenPromise = promisePanelHidden(window);
- PanelUI.toggle({type: "command"});
- yield hiddenPromise;
-
- ok(!PanelUI.panel.hasAttribute("panelopen"), "Check that panel doesn't have the panelopen attribute");
- is(PanelUI.panel.state, "closed", "Check that panel state is 'closed'");
-});
diff --git a/browser/components/customizableui/test/browser_switch_to_customize_mode.js b/browser/components/customizableui/test/browser_switch_to_customize_mode.js
deleted file mode 100644
index 459ea7a1c..000000000
--- a/browser/components/customizableui/test/browser_switch_to_customize_mode.js
+++ /dev/null
@@ -1,34 +0,0 @@
-"use strict";
-
-add_task(function*() {
- yield startCustomizing();
- is(gBrowser.tabs.length, 2, "Should have 2 tabs");
-
- let paletteKidCount = document.getElementById("customization-palette").childElementCount;
- let nonCustomizingTab = gBrowser.tabContainer.querySelector("tab:not([customizemode=true])");
- let finishedCustomizing = BrowserTestUtils.waitForEvent(gNavToolbox, "aftercustomization");
- yield BrowserTestUtils.switchTab(gBrowser, nonCustomizingTab);
- yield finishedCustomizing;
-
- let startedCount = 0;
- let handler = e => startedCount++;
- gNavToolbox.addEventListener("customizationstarting", handler);
- yield startCustomizing();
- CustomizableUI.removeWidgetFromArea("home-button");
- yield gCustomizeMode.reset().catch(e => {
- ok(false, "Threw an exception trying to reset after making modifications in customize mode: " + e);
- });
-
- let newKidCount = document.getElementById("customization-palette").childElementCount;
- is(newKidCount, paletteKidCount, "Should have just as many items in the palette as before.");
- yield endCustomizing();
- is(startedCount, 1, "Should have only started once");
- gNavToolbox.removeEventListener("customizationstarting", handler);
- let customizableToolbars = document.querySelectorAll("toolbar[customizable=true]:not([autohide=true])");
- for (let toolbar of customizableToolbars) {
- ok(!toolbar.hasAttribute("customizing"), "Toolbar " + toolbar.id + " is no longer customizing");
- }
- let menuitem = document.getElementById("PanelUI-customize");
- isnot(menuitem.getAttribute("label"), menuitem.getAttribute("exitLabel"), "Should have exited successfully");
-});
-
diff --git a/browser/components/customizableui/test/head.js b/browser/components/customizableui/test/head.js
deleted file mode 100644
index 7b8d84e20..000000000
--- a/browser/components/customizableui/test/head.js
+++ /dev/null
@@ -1,499 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Avoid leaks by using tmp for imports...
-var tmp = {};
-Cu.import("resource://gre/modules/Promise.jsm", tmp);
-Cu.import("resource:///modules/CustomizableUI.jsm", tmp);
-Cu.import("resource://gre/modules/AppConstants.jsm", tmp);
-var {Promise, CustomizableUI, AppConstants} = tmp;
-
-var EventUtils = {};
-Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
-Services.prefs.setBoolPref("browser.uiCustomization.skipSourceNodeCheck", true);
-registerCleanupFunction(() => Services.prefs.clearUserPref("browser.uiCustomization.skipSourceNodeCheck"));
-
-// Remove temporary e10s related new window options in customize ui,
-// they break a lot of tests.
-CustomizableUI.destroyWidget("e10s-button");
-CustomizableUI.removeWidgetFromArea("e10s-button");
-
-var {synthesizeDragStart, synthesizeDrop} = EventUtils;
-
-const kNSXUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
-const kTabEventFailureTimeoutInMs = 20000;
-
-function createDummyXULButton(id, label, win = window) {
- let btn = document.createElementNS(kNSXUL, "toolbarbutton");
- btn.id = id;
- btn.setAttribute("label", label || id);
- btn.className = "toolbarbutton-1 chromeclass-toolbar-additional";
- win.gNavToolbox.palette.appendChild(btn);
- return btn;
-}
-
-var gAddedToolbars = new Set();
-
-function createToolbarWithPlacements(id, placements = []) {
- gAddedToolbars.add(id);
- let tb = document.createElementNS(kNSXUL, "toolbar");
- tb.id = id;
- tb.setAttribute("customizable", "true");
- CustomizableUI.registerArea(id, {
- type: CustomizableUI.TYPE_TOOLBAR,
- defaultPlacements: placements
- });
- gNavToolbox.appendChild(tb);
- return tb;
-}
-
-function createOverflowableToolbarWithPlacements(id, placements) {
- gAddedToolbars.add(id);
-
- let tb = document.createElementNS(kNSXUL, "toolbar");
- tb.id = id;
- tb.setAttribute("customizationtarget", id + "-target");
-
- let customizationtarget = document.createElementNS(kNSXUL, "hbox");
- customizationtarget.id = id + "-target";
- customizationtarget.setAttribute("flex", "1");
- tb.appendChild(customizationtarget);
-
- let overflowPanel = document.createElementNS(kNSXUL, "panel");
- overflowPanel.id = id + "-overflow";
- document.getElementById("mainPopupSet").appendChild(overflowPanel);
-
- let overflowList = document.createElementNS(kNSXUL, "vbox");
- overflowList.id = id + "-overflow-list";
- overflowPanel.appendChild(overflowList);
-
- let chevron = document.createElementNS(kNSXUL, "toolbarbutton");
- chevron.id = id + "-chevron";
- tb.appendChild(chevron);
-
- CustomizableUI.registerArea(id, {
- type: CustomizableUI.TYPE_TOOLBAR,
- defaultPlacements: placements,
- overflowable: true,
- });
-
- tb.setAttribute("customizable", "true");
- tb.setAttribute("overflowable", "true");
- tb.setAttribute("overflowpanel", overflowPanel.id);
- tb.setAttribute("overflowtarget", overflowList.id);
- tb.setAttribute("overflowbutton", chevron.id);
-
- gNavToolbox.appendChild(tb);
- return tb;
-}
-
-function removeCustomToolbars() {
- CustomizableUI.reset();
- for (let toolbarId of gAddedToolbars) {
- CustomizableUI.unregisterArea(toolbarId, true);
- let tb = document.getElementById(toolbarId);
- if (tb.hasAttribute("overflowpanel")) {
- let panel = document.getElementById(tb.getAttribute("overflowpanel"));
- if (panel)
- panel.remove();
- }
- tb.remove();
- }
- gAddedToolbars.clear();
-}
-
-function getToolboxCustomToolbarId(toolbarName) {
- return "__customToolbar_" + toolbarName.replace(" ", "_");
-}
-
-function resetCustomization() {
- return CustomizableUI.reset();
-}
-
-function isInDevEdition() {
- return AppConstants.MOZ_DEV_EDITION;
-}
-
-function removeDeveloperButtonIfDevEdition(areaPanelPlacements) {
- if (isInDevEdition()) {
- areaPanelPlacements.splice(areaPanelPlacements.indexOf("developer-button"), 1);
- }
-}
-
-function assertAreaPlacements(areaId, expectedPlacements) {
- let actualPlacements = getAreaWidgetIds(areaId);
- placementArraysEqual(areaId, actualPlacements, expectedPlacements);
-}
-
-function placementArraysEqual(areaId, actualPlacements, expectedPlacements) {
- is(actualPlacements.length, expectedPlacements.length,
- "Area " + areaId + " should have " + expectedPlacements.length + " items.");
- let minItems = Math.min(expectedPlacements.length, actualPlacements.length);
- for (let i = 0; i < minItems; i++) {
- if (typeof expectedPlacements[i] == "string") {
- is(actualPlacements[i], expectedPlacements[i],
- "Item " + i + " in " + areaId + " should match expectations.");
- } else if (expectedPlacements[i] instanceof RegExp) {
- ok(expectedPlacements[i].test(actualPlacements[i]),
- "Item " + i + " (" + actualPlacements[i] + ") in " +
- areaId + " should match " + expectedPlacements[i]);
- } else {
- ok(false, "Unknown type of expected placement passed to " +
- " assertAreaPlacements. Is your test broken?");
- }
- }
-}
-
-function todoAssertAreaPlacements(areaId, expectedPlacements) {
- let actualPlacements = getAreaWidgetIds(areaId);
- let isPassing = actualPlacements.length == expectedPlacements.length;
- let minItems = Math.min(expectedPlacements.length, actualPlacements.length);
- for (let i = 0; i < minItems; i++) {
- if (typeof expectedPlacements[i] == "string") {
- isPassing = isPassing && actualPlacements[i] == expectedPlacements[i];
- } else if (expectedPlacements[i] instanceof RegExp) {
- isPassing = isPassing && expectedPlacements[i].test(actualPlacements[i]);
- } else {
- ok(false, "Unknown type of expected placement passed to " +
- " assertAreaPlacements. Is your test broken?");
- }
- }
- todo(isPassing, "The area placements for " + areaId +
- " should equal the expected placements.");
-}
-
-function getAreaWidgetIds(areaId) {
- return CustomizableUI.getWidgetIdsInArea(areaId);
-}
-
-function simulateItemDrag(aToDrag, aTarget) {
- synthesizeDrop(aToDrag.parentNode, aTarget);
-}
-
-function endCustomizing(aWindow=window) {
- if (aWindow.document.documentElement.getAttribute("customizing") != "true") {
- return true;
- }
- Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true);
- let deferredEndCustomizing = Promise.defer();
- function onCustomizationEnds() {
- Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false);
- aWindow.gNavToolbox.removeEventListener("aftercustomization", onCustomizationEnds);
- deferredEndCustomizing.resolve();
- }
- aWindow.gNavToolbox.addEventListener("aftercustomization", onCustomizationEnds);
- aWindow.gCustomizeMode.exit();
-
- return deferredEndCustomizing.promise;
-}
-
-function startCustomizing(aWindow=window) {
- if (aWindow.document.documentElement.getAttribute("customizing") == "true") {
- return null;
- }
- Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true);
- let deferred = Promise.defer();
- function onCustomizing() {
- aWindow.gNavToolbox.removeEventListener("customizationready", onCustomizing);
- Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false);
- deferred.resolve();
- }
- aWindow.gNavToolbox.addEventListener("customizationready", onCustomizing);
- aWindow.gCustomizeMode.enter();
- return deferred.promise;
-}
-
-function promiseObserverNotified(aTopic) {
- let deferred = Promise.defer();
- Services.obs.addObserver(function onNotification(aSubject, aTopic, aData) {
- Services.obs.removeObserver(onNotification, aTopic);
- deferred.resolve({subject: aSubject, data: aData});
- }, aTopic, false);
- return deferred.promise;
-}
-
-function openAndLoadWindow(aOptions, aWaitForDelayedStartup=false) {
- let deferred = Promise.defer();
- let win = OpenBrowserWindow(aOptions);
- if (aWaitForDelayedStartup) {
- Services.obs.addObserver(function onDS(aSubject, aTopic, aData) {
- if (aSubject != win) {
- return;
- }
- Services.obs.removeObserver(onDS, "browser-delayed-startup-finished");
- deferred.resolve(win);
- }, "browser-delayed-startup-finished", false);
-
- } else {
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- deferred.resolve(win);
- });
- }
- return deferred.promise;
-}
-
-function promiseWindowClosed(win) {
- let deferred = Promise.defer();
- win.addEventListener("unload", function onunload() {
- win.removeEventListener("unload", onunload);
- deferred.resolve();
- });
- win.close();
- return deferred.promise;
-}
-
-function promisePanelShown(win) {
- let panelEl = win.PanelUI.panel;
- return promisePanelElementShown(win, panelEl);
-}
-
-function promiseOverflowShown(win) {
- let panelEl = win.document.getElementById("widget-overflow");
- return promisePanelElementShown(win, panelEl);
-}
-
-function promisePanelElementShown(win, aPanel) {
- let deferred = Promise.defer();
- let timeoutId = win.setTimeout(() => {
- deferred.reject("Panel did not show within 20 seconds.");
- }, 20000);
- function onPanelOpen(e) {
- aPanel.removeEventListener("popupshown", onPanelOpen);
- win.clearTimeout(timeoutId);
- deferred.resolve();
- }
- aPanel.addEventListener("popupshown", onPanelOpen);
- return deferred.promise;
-}
-
-function promisePanelHidden(win) {
- let panelEl = win.PanelUI.panel;
- return promisePanelElementHidden(win, panelEl);
-}
-
-function promiseOverflowHidden(win) {
- let panelEl = document.getElementById("widget-overflow");
- return promisePanelElementHidden(win, panelEl);
-}
-
-function promisePanelElementHidden(win, aPanel) {
- let deferred = Promise.defer();
- let timeoutId = win.setTimeout(() => {
- deferred.reject("Panel did not hide within 20 seconds.");
- }, 20000);
- function onPanelClose(e) {
- aPanel.removeEventListener("popuphidden", onPanelClose);
- win.clearTimeout(timeoutId);
- deferred.resolve();
- }
- aPanel.addEventListener("popuphidden", onPanelClose);
- return deferred.promise;
-}
-
-function isPanelUIOpen() {
- return PanelUI.panel.state == "open" || PanelUI.panel.state == "showing";
-}
-
-function subviewShown(aSubview) {
- let deferred = Promise.defer();
- let win = aSubview.ownerGlobal;
- let timeoutId = win.setTimeout(() => {
- deferred.reject("Subview (" + aSubview.id + ") did not show within 20 seconds.");
- }, 20000);
- function onViewShowing(e) {
- aSubview.removeEventListener("ViewShowing", onViewShowing);
- win.clearTimeout(timeoutId);
- deferred.resolve();
- }
- aSubview.addEventListener("ViewShowing", onViewShowing);
- return deferred.promise;
-}
-
-function subviewHidden(aSubview) {
- let deferred = Promise.defer();
- let win = aSubview.ownerGlobal;
- let timeoutId = win.setTimeout(() => {
- deferred.reject("Subview (" + aSubview.id + ") did not hide within 20 seconds.");
- }, 20000);
- function onViewHiding(e) {
- aSubview.removeEventListener("ViewHiding", onViewHiding);
- win.clearTimeout(timeoutId);
- deferred.resolve();
- }
- aSubview.addEventListener("ViewHiding", onViewHiding);
- return deferred.promise;
-}
-
-function waitForCondition(aConditionFn, aMaxTries=50, aCheckInterval=100) {
- function tryNow() {
- tries++;
- if (aConditionFn()) {
- deferred.resolve();
- } else if (tries < aMaxTries) {
- tryAgain();
- } else {
- deferred.reject("Condition timed out: " + aConditionFn.toSource());
- }
- }
- function tryAgain() {
- setTimeout(tryNow, aCheckInterval);
- }
- let deferred = Promise.defer();
- let tries = 0;
- tryAgain();
- return deferred.promise;
-}
-
-function waitFor(aTimeout=100) {
- let deferred = Promise.defer();
- setTimeout(() => deferred.resolve(), aTimeout);
- return deferred.promise;
-}
-
-/**
- * Starts a load in an existing tab and waits for it to finish (via some event).
- *
- * @param aTab The tab to load into.
- * @param aUrl The url to load.
- * @param aEventType The load event type to wait for. Defaults to "load".
- * @return {Promise} resolved when the event is handled.
- */
-function promiseTabLoadEvent(aTab, aURL) {
- let browser = aTab.linkedBrowser;
-
- BrowserTestUtils.loadURI(browser, aURL);
- return BrowserTestUtils.browserLoaded(browser);
-}
-
-/**
- * Navigate back or forward in tab history and wait for it to finish.
- *
- * @param aDirection Number to indicate to move backward or forward in history.
- * @param aConditionFn Function that returns the result of an evaluated condition
- * that needs to be `true` to resolve the promise.
- * @return {Promise} resolved when navigation has finished.
- */
-function promiseTabHistoryNavigation(aDirection = -1, aConditionFn) {
- let deferred = Promise.defer();
-
- let timeoutId = setTimeout(() => {
- gBrowser.removeEventListener("pageshow", listener, true);
- deferred.reject("Pageshow did not happen within " + kTabEventFailureTimeoutInMs + "ms");
- }, kTabEventFailureTimeoutInMs);
-
- function listener(event) {
- gBrowser.removeEventListener("pageshow", listener, true);
- clearTimeout(timeoutId);
-
- if (aConditionFn) {
- waitForCondition(aConditionFn).then(() => deferred.resolve(),
- aReason => deferred.reject(aReason));
- } else {
- deferred.resolve();
- }
- }
- gBrowser.addEventListener("pageshow", listener, true);
-
- content.history.go(aDirection);
-
- return deferred.promise;
-}
-
-/**
- * Wait for an attribute on a node to change
- *
- * @param aNode Node on which the mutation is expected
- * @param aAttribute The attribute we're interested in
- * @param aFilterFn A function to check if the new value is what we want.
- * @return {Promise} resolved when the requisite mutation shows up.
- */
-function promiseAttributeMutation(aNode, aAttribute, aFilterFn) {
- return new Promise((resolve, reject) => {
- info("waiting for mutation of attribute '" + aAttribute + "'.");
- let obs = new MutationObserver((mutations) => {
- for (let mut of mutations) {
- let attr = mut.attributeName;
- let newValue = mut.target.getAttribute(attr);
- if (aFilterFn(newValue)) {
- ok(true, "mutation occurred: attribute '" + attr + "' changed to '" + newValue + "' from '" + mut.oldValue + "'.");
- obs.disconnect();
- resolve();
- } else {
- info("Ignoring mutation that produced value " + newValue + " because of filter.");
- }
- }
- });
- obs.observe(aNode, {attributeFilter: [aAttribute]});
- });
-}
-
-function popupShown(aPopup) {
- return promisePopupEvent(aPopup, "shown");
-}
-
-function popupHidden(aPopup) {
- return promisePopupEvent(aPopup, "hidden");
-}
-
-/**
- * Returns a Promise that resolves when aPopup fires an event of type
- * aEventType. Times out and rejects after 20 seconds.
- *
- * @param aPopup the popup to monitor for events.
- * @param aEventSuffix the _suffix_ for the popup event type to watch for.
- *
- * Example usage:
- * let popupShownPromise = promisePopupEvent(somePopup, "shown");
- * // ... something that opens a popup
- * yield popupShownPromise;
- *
- * let popupHiddenPromise = promisePopupEvent(somePopup, "hidden");
- * // ... something that hides a popup
- * yield popupHiddenPromise;
- */
-function promisePopupEvent(aPopup, aEventSuffix) {
- let deferred = Promise.defer();
- let eventType = "popup" + aEventSuffix;
-
- function onPopupEvent(e) {
- aPopup.removeEventListener(eventType, onPopupEvent);
- deferred.resolve();
- }
-
- aPopup.addEventListener(eventType, onPopupEvent);
- return deferred.promise;
-}
-
-// This is a simpler version of the context menu check that
-// exists in contextmenu_common.js.
-function checkContextMenu(aContextMenu, aExpectedEntries, aWindow=window) {
- let childNodes = [...aContextMenu.childNodes];
- // Ignore hidden nodes:
- childNodes = childNodes.filter((n) => !n.hidden);
-
- for (let i = 0; i < childNodes.length; i++) {
- let menuitem = childNodes[i];
- try {
- if (aExpectedEntries[i][0] == "---") {
- is(menuitem.localName, "menuseparator", "menuseparator expected");
- continue;
- }
-
- let selector = aExpectedEntries[i][0];
- ok(menuitem.matches(selector), "menuitem should match " + selector + " selector");
- let commandValue = menuitem.getAttribute("command");
- let relatedCommand = commandValue ? aWindow.document.getElementById(commandValue) : null;
- let menuItemDisabled = relatedCommand ?
- relatedCommand.getAttribute("disabled") == "true" :
- menuitem.getAttribute("disabled") == "true";
- is(menuItemDisabled, !aExpectedEntries[i][1], "disabled state for " + selector);
- } catch (e) {
- ok(false, "Exception when checking context menu: " + e);
- }
- }
-}
diff --git a/browser/components/customizableui/test/support/feeds_test_page.html b/browser/components/customizableui/test/support/feeds_test_page.html
deleted file mode 100644
index be78e4dff..000000000
--- a/browser/components/customizableui/test/support/feeds_test_page.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
-<head>
- <title>Feeds test page</title>
- <link rel="alternate" type="application/rss+xml" href="test-feed.xml" title="Test feed">
-</head>
-
-<body>
- This is a test page for feeds
-</body>
-</html>
diff --git a/browser/components/customizableui/test/support/test-feed.xml b/browser/components/customizableui/test/support/test-feed.xml
deleted file mode 100644
index 0e700b6d8..000000000
--- a/browser/components/customizableui/test/support/test-feed.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id>
-
- <entry>
-
- <title>Item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/customizableui/test/support/test_967000_charEncoding_page.html b/browser/components/customizableui/test/support/test_967000_charEncoding_page.html
deleted file mode 100644
index c8d35115c..000000000
--- a/browser/components/customizableui/test/support/test_967000_charEncoding_page.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- <title>Test page</title>
- </head>
-
- <body>
- This is a test page
- </body>
-</html>
diff --git a/browser/components/dirprovider/tests/unit/.eslintrc.js b/browser/components/dirprovider/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/dirprovider/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/downloads/test/browser/.eslintrc.js b/browser/components/downloads/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/downloads/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/downloads/test/browser/browser.ini b/browser/components/downloads/test/browser/browser.ini
deleted file mode 100644
index 76f026c78..000000000
--- a/browser/components/downloads/test/browser/browser.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-support-files = head.js
-
-[browser_basic_functionality.js]
-[browser_first_download_panel.js]
-skip-if = os == "linux" # Bug 949434
-[browser_overflow_anchor.js]
-skip-if = os == "linux" # Bug 952422
-[browser_confirm_unblock_download.js]
-[browser_iframe_gone_mid_download.js]
-[browser_indicatorDrop.js]
-[browser_libraryDrop.js]
-[browser_downloads_panel_block.js]
-[browser_downloads_panel_footer.js]
-[browser_downloads_panel_height.js]
diff --git a/browser/components/downloads/test/browser/browser_basic_functionality.js b/browser/components/downloads/test/browser/browser_basic_functionality.js
deleted file mode 100644
index 564a344a7..000000000
--- a/browser/components/downloads/test/browser/browser_basic_functionality.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-registerCleanupFunction(function*() {
- yield task_resetState();
-});
-
-/**
- * Make sure the downloads panel can display items in the right order and
- * contains the expected data.
- */
-add_task(function* test_basic_functionality() {
- // Display one of each download state.
- const DownloadData = [
- { state: nsIDM.DOWNLOAD_NOTSTARTED },
- { state: nsIDM.DOWNLOAD_PAUSED },
- { state: nsIDM.DOWNLOAD_FINISHED },
- { state: nsIDM.DOWNLOAD_FAILED },
- { state: nsIDM.DOWNLOAD_CANCELED },
- ];
-
- // Wait for focus first
- yield promiseFocus();
-
- // Ensure that state is reset in case previous tests didn't finish.
- yield task_resetState();
-
- // For testing purposes, show all the download items at once.
- var originalCountLimit = DownloadsView.kItemCountLimit;
- DownloadsView.kItemCountLimit = DownloadData.length;
- registerCleanupFunction(function () {
- DownloadsView.kItemCountLimit = originalCountLimit;
- });
-
- // Populate the downloads database with the data required by this test.
- yield task_addDownloads(DownloadData);
-
- // Open the user interface and wait for data to be fully loaded.
- yield task_openPanel();
-
- // Test item data and count. This also tests the ordering of the display.
- let richlistbox = document.getElementById("downloadsListBox");
- /* disabled for failing intermittently (bug 767828)
- is(richlistbox.children.length, DownloadData.length,
- "There is the correct number of richlistitems");
- */
- let itemCount = richlistbox.children.length;
- for (let i = 0; i < itemCount; i++) {
- let element = richlistbox.children[itemCount - i - 1];
- let download = DownloadsView.itemForElement(element).download;
- is(DownloadsCommon.stateOfDownload(download), DownloadData[i].state,
- "Download states match up");
- }
-});
diff --git a/browser/components/downloads/test/browser/browser_confirm_unblock_download.js b/browser/components/downloads/test/browser/browser_confirm_unblock_download.js
deleted file mode 100644
index 8ba37ba64..000000000
--- a/browser/components/downloads/test/browser/browser_confirm_unblock_download.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Tests the dialog which allows the user to unblock a downloaded file.
-
-registerCleanupFunction(() => {});
-
-function* assertDialogResult({ args, buttonToClick, expectedResult }) {
- promiseAlertDialogOpen(buttonToClick);
- is(yield DownloadsCommon.confirmUnblockDownload(args), expectedResult);
-}
-
-/**
- * Tests the "unblock" dialog, for each of the possible verdicts.
- */
-add_task(function* test_unblock_dialog_unblock() {
- for (let verdict of [Downloads.Error.BLOCK_VERDICT_MALWARE,
- Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED,
- Downloads.Error.BLOCK_VERDICT_UNCOMMON]) {
- let args = { verdict, window, dialogType: "unblock" };
-
- // Test both buttons.
- yield assertDialogResult({
- args,
- buttonToClick: "accept",
- expectedResult: "unblock",
- });
- yield assertDialogResult({
- args,
- buttonToClick: "cancel",
- expectedResult: "cancel",
- });
- }
-});
-
-/**
- * Tests the "chooseUnblock" dialog for potentially unwanted downloads.
- */
-add_task(function* test_chooseUnblock_dialog() {
- let args = {
- verdict: Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED,
- window,
- dialogType: "chooseUnblock",
- };
-
- // Test each of the three buttons.
- yield assertDialogResult({
- args,
- buttonToClick: "accept",
- expectedResult: "unblock",
- });
- yield assertDialogResult({
- args,
- buttonToClick: "cancel",
- expectedResult: "cancel",
- });
- yield assertDialogResult({
- args,
- buttonToClick: "extra1",
- expectedResult: "confirmBlock",
- });
-});
-
-/**
- * Tests the "chooseOpen" dialog for uncommon downloads.
- */
-add_task(function* test_chooseOpen_dialog() {
- let args = {
- verdict: Downloads.Error.BLOCK_VERDICT_UNCOMMON,
- window,
- dialogType: "chooseOpen",
- };
-
- // Test each of the three buttons.
- yield assertDialogResult({
- args,
- buttonToClick: "accept",
- expectedResult: "open",
- });
- yield assertDialogResult({
- args,
- buttonToClick: "cancel",
- expectedResult: "cancel",
- });
- yield assertDialogResult({
- args,
- buttonToClick: "extra1",
- expectedResult: "confirmBlock",
- });
-});
diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_block.js b/browser/components/downloads/test/browser/browser_downloads_panel_block.js
deleted file mode 100644
index 05056e842..000000000
--- a/browser/components/downloads/test/browser/browser_downloads_panel_block.js
+++ /dev/null
@@ -1,183 +0,0 @@
-"use strict";
-
-add_task(function* mainTest() {
- yield task_resetState();
-
- let verdicts = [
- Downloads.Error.BLOCK_VERDICT_UNCOMMON,
- Downloads.Error.BLOCK_VERDICT_MALWARE,
- Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED,
- ];
- yield task_addDownloads(verdicts.map(v => makeDownload(v)));
-
- // Check that the richlistitem for each download is correct.
- for (let i = 0; i < verdicts.length; i++) {
- yield openPanel();
-
- // The current item is always the first one in the listbox since each
- // iteration of this loop removes the item at the end.
- let item = DownloadsView.richListBox.firstChild;
-
- // Open the panel and click the item to show the subview.
- EventUtils.sendMouseEvent({ type: "click" }, item);
- yield promiseSubviewShown(true);
-
- // Items are listed in newest-to-oldest order, so e.g. the first item's
- // verdict is the last element in the verdicts array.
- Assert.ok(DownloadsBlockedSubview.subview.getAttribute("verdict"),
- verdicts[verdicts.count - i - 1]);
-
- // Click the sliver of the main view that's still showing on the left to go
- // back to it.
- EventUtils.synthesizeMouse(DownloadsPanel.panel, 10, 10, {}, window);
- yield promiseSubviewShown(false);
-
- // Show the subview again.
- EventUtils.sendMouseEvent({ type: "click" }, item);
- yield promiseSubviewShown(true);
-
- // Click the Open button. The download should be unblocked and then opened,
- // i.e., unblockAndOpenDownload() should be called on the item. The panel
- // should also be closed as a result, so wait for that too.
- let unblockOpenPromise = promiseUnblockAndOpenDownloadCalled(item);
- let hidePromise = promisePanelHidden();
- EventUtils.synthesizeMouse(DownloadsBlockedSubview.elements.openButton,
- 10, 10, {}, window);
- yield unblockOpenPromise;
- yield hidePromise;
-
- window.focus();
- yield SimpleTest.promiseFocus(window);
-
- // Reopen the panel and show the subview again.
- yield openPanel();
-
- EventUtils.sendMouseEvent({ type: "click" }, item);
- yield promiseSubviewShown(true);
-
- // Click the Remove button. The panel should close and the item should be
- // removed from it.
- EventUtils.synthesizeMouse(DownloadsBlockedSubview.elements.deleteButton,
- 10, 10, {}, window);
- yield promisePanelHidden();
- yield openPanel();
-
- Assert.ok(!item.parentNode);
- DownloadsPanel.hidePanel();
- yield promisePanelHidden();
- }
-
- yield task_resetState();
-});
-
-function* openPanel() {
- // This function is insane but something intermittently causes the panel to be
- // closed as soon as it's opening on Linux ASAN. Maybe it would also happen
- // on other build machines if the test ran often enough. Not only is the
- // panel closed, it's closed while it's opening, leaving DownloadsPanel._state
- // such that when you try to open the panel again, it thinks it's already
- // open, but it's not. The result is that the test times out.
- //
- // What this does is call DownloadsPanel.showPanel over and over again until
- // the panel is really open. There are a few wrinkles:
- //
- // (1) When panel.state is "open", check four more times (for a total of five)
- // before returning to make the panel stays open.
- // (2) If the panel is not open, check the _state. It should be either
- // kStateUninitialized or kStateHidden. If it's not, then the panel is in the
- // process of opening -- or maybe it's stuck in that process -- so reset the
- // _state to kStateHidden.
- // (3) If the _state is not kStateUninitialized or kStateHidden, then it may
- // actually be properly opening and not stuck at all. To avoid always closing
- // the panel while it's properly opening, use an exponential backoff mechanism
- // for retries.
- //
- // If all that fails, then the test will time out, but it would have timed out
- // anyway.
-
- yield promiseFocus();
- yield new Promise(resolve => {
- let verifyCount = 5;
- let backoff = 0;
- let iBackoff = 0;
- let interval = setInterval(() => {
- if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") {
- if (verifyCount > 0) {
- verifyCount--;
- } else {
- clearInterval(interval);
- resolve();
- }
- } else {
- if (iBackoff < backoff) {
- // Keep backing off before trying again.
- iBackoff++;
- } else {
- // Try (or retry) opening the panel.
- verifyCount = 5;
- backoff = Math.max(1, 2 * backoff);
- iBackoff = 0;
- if (DownloadsPanel._state != DownloadsPanel.kStateUninitialized) {
- DownloadsPanel._state = DownloadsPanel.kStateHidden;
- }
- DownloadsPanel.showPanel();
- }
- }
- }, 100);
- });
-}
-
-function promisePanelHidden() {
- return new Promise(resolve => {
- if (!DownloadsPanel.panel || DownloadsPanel.panel.state == "closed") {
- resolve();
- return;
- }
- DownloadsPanel.panel.addEventListener("popuphidden", function onHidden() {
- DownloadsPanel.panel.removeEventListener("popuphidden", onHidden);
- setTimeout(resolve, 0);
- });
- });
-}
-
-function makeDownload(verdict) {
- return {
- state: nsIDM.DOWNLOAD_DIRTY,
- hasBlockedData: true,
- errorObj: {
- result: Components.results.NS_ERROR_FAILURE,
- message: "Download blocked.",
- becauseBlocked: true,
- becauseBlockedByReputationCheck: true,
- reputationCheckVerdict: verdict,
- },
- };
-}
-
-function promiseSubviewShown(shown) {
- // More terribleness, but I'm tired of fighting intermittent timeouts on try.
- // Just poll for the subview and wait a second before resolving the promise.
- return new Promise(resolve => {
- let interval = setInterval(() => {
- if (shown == DownloadsBlockedSubview.view.showingSubView &&
- !DownloadsBlockedSubview.view._transitioning) {
- clearInterval(interval);
- setTimeout(resolve, 1000);
- return;
- }
- }, 0);
- });
-}
-
-function promiseUnblockAndOpenDownloadCalled(item) {
- return new Promise(resolve => {
- let realFn = item._shell.unblockAndOpenDownload;
- item._shell.unblockAndOpenDownload = () => {
- item._shell.unblockAndOpenDownload = realFn;
- resolve();
- // unblockAndOpenDownload returns a promise (that's resolved when the file
- // is opened).
- return Promise.resolve();
- };
- });
-}
diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_footer.js b/browser/components/downloads/test/browser/browser_downloads_panel_footer.js
deleted file mode 100644
index 4083dde98..000000000
--- a/browser/components/downloads/test/browser/browser_downloads_panel_footer.js
+++ /dev/null
@@ -1,95 +0,0 @@
-"use strict";
-
-function *task_openDownloadsSubPanel() {
- let downloadSubPanel = document.getElementById("downloadSubPanel");
- let popupShownPromise = BrowserTestUtils.waitForEvent(downloadSubPanel, "popupshown");
-
- let downloadsDropmarker = document.getElementById("downloadsFooterDropmarker");
- EventUtils.synthesizeMouseAtCenter(downloadsDropmarker, {}, window);
-
- yield popupShownPromise;
-}
-
-add_task(function* test_openDownloadsFolder() {
- yield SpecialPowers.pushPrefEnv({"set": [["browser.download.showPanelDropmarker", true]]});
- yield task_openPanel();
-
- yield task_openDownloadsSubPanel();
-
- yield new Promise(resolve => {
- sinon.stub(DownloadsCommon, "showDirectory", file => {
- resolve(Downloads.getPreferredDownloadsDirectory().then(downloadsPath => {
- is(file.path, downloadsPath, "Check the download folder path.");
- }));
- });
-
- let itemOpenDownloadsFolder =
- document.getElementById("downloadsDropdownItemOpenDownloadsFolder");
- EventUtils.synthesizeMouseAtCenter(itemOpenDownloadsFolder, {}, window);
- });
-
- yield task_resetState();
-});
-
-add_task(function* test_clearList() {
- const kTestCases = [{
- downloads: [
- { state: nsIDM.DOWNLOAD_NOTSTARTED },
- { state: nsIDM.DOWNLOAD_FINISHED },
- { state: nsIDM.DOWNLOAD_FAILED },
- { state: nsIDM.DOWNLOAD_CANCELED },
- ],
- expectClearListShown: true,
- expectedItemNumber: 0,
- },{
- downloads: [
- { state: nsIDM.DOWNLOAD_NOTSTARTED },
- { state: nsIDM.DOWNLOAD_FINISHED },
- { state: nsIDM.DOWNLOAD_FAILED },
- { state: nsIDM.DOWNLOAD_PAUSED },
- { state: nsIDM.DOWNLOAD_CANCELED },
- ],
- expectClearListShown: true,
- expectedItemNumber: 1,
- },{
- downloads: [
- { state: nsIDM.DOWNLOAD_PAUSED },
- ],
- expectClearListShown: false,
- expectedItemNumber: 1,
- }];
-
- for (let testCase of kTestCases) {
- yield verify_clearList(testCase);
- }
-});
-
-function *verify_clearList(testCase) {
- let downloads = testCase.downloads;
- yield task_addDownloads(downloads);
-
- yield task_openPanel();
- is(DownloadsView._downloads.length, downloads.length,
- "Expect the number of download items");
-
- yield task_openDownloadsSubPanel();
-
- let itemClearList = document.getElementById("downloadsDropdownItemClearList");
- let itemNumberPromise = BrowserTestUtils.waitForCondition(() => {
- return DownloadsView._downloads.length === testCase.expectedItemNumber;
- });
- if (testCase.expectClearListShown) {
- isnot("true", itemClearList.getAttribute("hidden"),
- "Should show Clear Preview Panel button");
- EventUtils.synthesizeMouseAtCenter(itemClearList, {}, window);
- } else {
- is("true", itemClearList.getAttribute("hidden"),
- "Should not show Clear Preview Panel button");
- }
-
- yield itemNumberPromise;
- is(DownloadsView._downloads.length, testCase.expectedItemNumber,
- "Download items remained.");
-
- yield task_resetState();
-}
diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_height.js b/browser/components/downloads/test/browser/browser_downloads_panel_height.js
deleted file mode 100644
index 1638e4f0e..000000000
--- a/browser/components/downloads/test/browser/browser_downloads_panel_height.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * This test exists because we use a <panelmultiview> element and it handles
- * some of the height changes for us. We need to verify that the height is
- * updated correctly if downloads are removed while the panel is hidden.
- */
-add_task(function* test_height_reduced_after_removal() {
- yield task_addDownloads([
- { state: nsIDM.DOWNLOAD_FINISHED },
- ]);
-
- yield task_openPanel();
- let panel = document.getElementById("downloadsPanel");
- let heightBeforeRemoval = panel.getBoundingClientRect().height;
-
- // We want to close the panel before we remove the download from the list.
- DownloadsPanel.hidePanel();
- yield task_resetState();
-
- yield task_openPanel();
- let heightAfterRemoval = panel.getBoundingClientRect().height;
- Assert.greater(heightBeforeRemoval, heightAfterRemoval);
-
- yield task_resetState();
-});
diff --git a/browser/components/downloads/test/browser/browser_first_download_panel.js b/browser/components/downloads/test/browser/browser_first_download_panel.js
deleted file mode 100644
index 2cd871360..000000000
--- a/browser/components/downloads/test/browser/browser_first_download_panel.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Make sure the downloads panel only opens automatically on the first
- * download it notices. All subsequent downloads, even across sessions, should
- * not open the panel automatically.
- */
-add_task(function* test_first_download_panel() {
- // Clear the download panel has shown preference first as this test is used to
- // verify this preference's behaviour.
- let oldPrefValue = Services.prefs.getBoolPref("browser.download.panel.shown");
- Services.prefs.setBoolPref("browser.download.panel.shown", false);
-
- registerCleanupFunction(function*() {
- // Clean up when the test finishes.
- yield task_resetState();
-
- // Set the preference instead of clearing it afterwards to ensure the
- // right value is used no matter what the default was. This ensures the
- // panel doesn't appear and affect other tests.
- Services.prefs.setBoolPref("browser.download.panel.shown", oldPrefValue);
- });
-
- // Ensure that state is reset in case previous tests didn't finish.
- yield task_resetState();
-
- // With this set to false, we should automatically open the panel the first
- // time a download is started.
- DownloadsCommon.getData(window).panelHasShownBefore = false;
-
- let promise = promisePanelOpened();
- DownloadsCommon.getData(window)._notifyDownloadEvent("start");
- yield promise;
-
- // If we got here, that means the panel opened.
- DownloadsPanel.hidePanel();
-
- ok(DownloadsCommon.getData(window).panelHasShownBefore,
- "Should have recorded that the panel was opened on a download.")
-
- // Next, make sure that if we start another download, we don't open the
- // panel automatically.
- let originalOnPopupShown = DownloadsPanel.onPopupShown;
- DownloadsPanel.onPopupShown = function () {
- originalOnPopupShown.apply(this, arguments);
- ok(false, "Should not have opened the downloads panel.");
- };
-
- DownloadsCommon.getData(window)._notifyDownloadEvent("start");
-
- // Wait 2 seconds to ensure that the panel does not open.
- yield new Promise(resolve => setTimeout(resolve, 2000));
- DownloadsPanel.onPopupShown = originalOnPopupShown;
-});
diff --git a/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js b/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js
deleted file mode 100644
index ebdd4f9af..000000000
--- a/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js
+++ /dev/null
@@ -1,62 +0,0 @@
-const SAVE_PER_SITE_PREF = "browser.download.lastDir.savePerSite";
-
-function test_deleted_iframe(perSitePref, windowOptions={}) {
- return function*() {
- Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, perSitePref);
- let {DownloadLastDir} = Cu.import("resource://gre/modules/DownloadLastDir.jsm", {});
-
- let win = yield promiseOpenAndLoadWindow(windowOptions);
- let tab = win.gBrowser.addTab();
- yield promiseTabLoadEvent(tab, "about:mozilla");
-
- let doc = tab.linkedBrowser.contentDocument;
- let iframe = doc.createElement("iframe");
- doc.body.appendChild(iframe);
-
- ok(iframe.contentWindow, "iframe should have a window");
- let gDownloadLastDir = new DownloadLastDir(iframe.contentWindow);
- let cw = iframe.contentWindow;
- let promiseIframeWindowGone = new Promise((resolve, reject) => {
- Services.obs.addObserver(function obs(subject, topic) {
- if (subject == cw) {
- Services.obs.removeObserver(obs, topic);
- resolve();
- }
- }, "dom-window-destroyed", false);
- });
- iframe.remove();
- yield promiseIframeWindowGone;
- cw = null;
- ok(!iframe.contentWindow, "Managed to destroy iframe");
-
- let someDir = "blah";
- try {
- someDir = yield new Promise((resolve, reject) => {
- gDownloadLastDir.getFileAsync("http://www.mozilla.org/", function(dir) {
- resolve(dir);
- });
- });
- } catch (ex) {
- ok(false, "Got an exception trying to get the directory where things should be saved.");
- Cu.reportError(ex);
- }
- // NB: someDir can legitimately be null here when set, hence the 'blah' workaround:
- isnot(someDir, "blah", "Should get a file even after the window was destroyed.");
-
- try {
- gDownloadLastDir.setFile("http://www.mozilla.org/", null);
- } catch (ex) {
- ok(false, "Got an exception trying to set the directory where things should be saved.");
- Cu.reportError(ex);
- }
-
- yield promiseWindowClosed(win);
- Services.prefs.clearUserPref(SAVE_PER_SITE_PREF);
- };
-}
-
-add_task(test_deleted_iframe(false));
-add_task(test_deleted_iframe(false));
-add_task(test_deleted_iframe(true, {private: true}));
-add_task(test_deleted_iframe(true, {private: true}));
-
diff --git a/browser/components/downloads/test/browser/browser_indicatorDrop.js b/browser/components/downloads/test/browser/browser_indicatorDrop.js
deleted file mode 100644
index 368d85ccf..000000000
--- a/browser/components/downloads/test/browser/browser_indicatorDrop.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
- "resource://testing-common/httpd.js");
-
-registerCleanupFunction(function*() {
- yield task_resetState();
- yield task_clearHistory();
-});
-
-add_task(function* test_indicatorDrop() {
- let downloadButton = document.getElementById("downloads-button");
- ok(downloadButton, "download button present");
-
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- function* task_drop(urls) {
- let dragData = [[{type: "text/plain", data: urls.join("\n")}]];
-
- let list = yield Downloads.getList(Downloads.ALL);
-
- let added = new Set();
- let succeeded = new Set();
- yield new Promise(function(resolve) {
- let view = {
- onDownloadAdded: function(download) {
- added.add(download.source.url);
- },
- onDownloadChanged: function(download) {
- if (!added.has(download.source.url))
- return;
- if (!download.succeeded)
- return;
- succeeded.add(download.source.url);
- if (succeeded.size == urls.length) {
- list.removeView(view).then(resolve);
- }
- }
- };
- list.addView(view).then(function() {
- EventUtils.synthesizeDrop(downloadButton, downloadButton, dragData, "link", window);
- });
- });
-
- for (let url of urls) {
- ok(added.has(url), url + " is added to download");
- }
- }
-
- // Ensure that state is reset in case previous tests didn't finish.
- yield task_resetState();
-
- yield setDownloadDir();
-
- startServer();
-
- yield* task_drop([httpUrl("file1.txt")]);
- yield* task_drop([httpUrl("file1.txt"),
- httpUrl("file2.txt"),
- httpUrl("file3.txt")]);
-});
diff --git a/browser/components/downloads/test/browser/browser_libraryDrop.js b/browser/components/downloads/test/browser/browser_libraryDrop.js
deleted file mode 100644
index fa7df8a87..000000000
--- a/browser/components/downloads/test/browser/browser_libraryDrop.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
- "resource://testing-common/httpd.js");
-
-registerCleanupFunction(function*() {
- yield task_resetState();
- yield task_clearHistory();
-});
-
-add_task(function* test_indicatorDrop() {
- let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
- let EventUtils = {};
- scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
- function task_drop(win, urls) {
- let dragData = [[{type: "text/plain", data: urls.join("\n")}]];
-
- let listBox = win.document.getElementById("downloadsRichListBox");
- ok(listBox, "download list box present");
-
- let list = yield Downloads.getList(Downloads.ALL);
-
- let added = new Set();
- let succeeded = new Set();
- yield new Promise(function(resolve) {
- let view = {
- onDownloadAdded: function(download) {
- added.add(download.source.url);
- },
- onDownloadChanged: function(download) {
- if (!added.has(download.source.url))
- return;
- if (!download.succeeded)
- return;
- succeeded.add(download.source.url);
- if (succeeded.size == urls.length) {
- list.removeView(view).then(resolve);
- }
- }
- };
- list.addView(view).then(function() {
- EventUtils.synthesizeDrop(listBox, listBox, dragData, "link", win);
- });
- });
-
- for (let url of urls) {
- ok(added.has(url), url + " is added to download");
- }
- }
-
- // Ensure that state is reset in case previous tests didn't finish.
- yield task_resetState();
-
- setDownloadDir();
-
- startServer();
-
- let win = yield openLibrary("Downloads");
- registerCleanupFunction(function() {
- win.close();
- });
-
- yield* task_drop(win, [httpUrl("file1.txt")]);
- yield* task_drop(win, [httpUrl("file1.txt"),
- httpUrl("file2.txt"),
- httpUrl("file3.txt")]);
-});
diff --git a/browser/components/downloads/test/browser/browser_overflow_anchor.js b/browser/components/downloads/test/browser/browser_overflow_anchor.js
deleted file mode 100644
index a293a81cf..000000000
--- a/browser/components/downloads/test/browser/browser_overflow_anchor.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-registerCleanupFunction(function*() {
- // Clean up when the test finishes.
- yield task_resetState();
-});
-
-/**
- * Make sure the downloads button and indicator overflows into the nav-bar
- * chevron properly, and then when those buttons are clicked in the overflow
- * panel that the downloads panel anchors to the chevron.
- */
-add_task(function* test_overflow_anchor() {
- // Ensure that state is reset in case previous tests didn't finish.
- yield task_resetState();
-
- // Record the original width of the window so we can put it back when
- // this test finishes.
- let oldWidth = window.outerWidth;
-
- // The downloads button should not be overflowed to begin with.
- let button = CustomizableUI.getWidget("downloads-button")
- .forWindow(window);
- ok(!button.overflowed, "Downloads button should not be overflowed.");
-
- // Hack - we lock the size of the default flex-y items in the nav-bar,
- // namely, the URL and search inputs. That way we can resize the
- // window without worrying about them flexing.
- const kFlexyItems = ["urlbar-container", "search-container"];
- registerCleanupFunction(() => unlockWidth(kFlexyItems));
- lockWidth(kFlexyItems);
-
- // Resize the window to half of its original size. That should
- // be enough to overflow the downloads button.
- window.resizeTo(oldWidth / 2, window.outerHeight);
- yield waitForOverflowed(button, true);
-
- let promise = promisePanelOpened();
- button.node.doCommand();
- yield promise;
-
- let panel = DownloadsPanel.panel;
- let chevron = document.getElementById("nav-bar-overflow-button");
- is(panel.anchorNode, chevron, "Panel should be anchored to the chevron.");
-
- DownloadsPanel.hidePanel();
-
- // Unlock the widths on the flex-y items.
- unlockWidth(kFlexyItems);
-
- // Put the window back to its original dimensions.
- window.resizeTo(oldWidth, window.outerHeight);
-
- // The downloads button should eventually be un-overflowed.
- yield waitForOverflowed(button, false);
-
- // Now try opening the panel again.
- promise = promisePanelOpened();
- button.node.doCommand();
- yield promise;
-
- is(panel.anchorNode.id, "downloads-indicator-anchor");
-
- DownloadsPanel.hidePanel();
-});
-
-/**
- * For some node IDs, finds the nodes and sets their min-width's to their
- * current width, preventing them from flex-shrinking.
- *
- * @param aItemIDs an array of item IDs to set min-width on.
- */
-function lockWidth(aItemIDs) {
- for (let itemID of aItemIDs) {
- let item = document.getElementById(itemID);
- let curWidth = item.getBoundingClientRect().width + "px";
- item.style.minWidth = curWidth;
- }
-}
-
-/**
- * Clears the min-width's set on a set of IDs by lockWidth.
- *
- * @param aItemIDs an array of ItemIDs to remove min-width on.
- */
-function unlockWidth(aItemIDs) {
- for (let itemID of aItemIDs) {
- let item = document.getElementById(itemID);
- item.style.minWidth = "";
- }
-}
-
-/**
- * Waits for a node to enter or exit the overflowed state.
- *
- * @param aItem the node to wait for.
- * @param aIsOverflowed if we're waiting for the item to be overflowed.
- */
-function waitForOverflowed(aItem, aIsOverflowed) {
- let deferOverflow = Promise.defer();
- if (aItem.overflowed == aIsOverflowed) {
- return deferOverflow.resolve();
- }
-
- let observer = new MutationObserver(function(aMutations) {
- if (aItem.overflowed == aIsOverflowed) {
- observer.disconnect();
- deferOverflow.resolve();
- }
- });
- observer.observe(aItem.node, {attributes: true});
-
- return deferOverflow.promise;
-}
diff --git a/browser/components/downloads/test/browser/head.js b/browser/components/downloads/test/browser/head.js
deleted file mode 100644
index bcf703eb6..000000000
--- a/browser/components/downloads/test/browser/head.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Provides infrastructure for automated download components tests.
- */
-
-////////////////////////////////////////////////////////////////////////////////
-//// Globals
-
-XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
- "resource://gre/modules/Downloads.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon",
- "resource:///modules/DownloadsCommon.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-const nsIDM = Ci.nsIDownloadManager;
-
-var gTestTargetFile = FileUtils.getFile("TmpD", ["dm-ui-test.file"]);
-gTestTargetFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
-
-// Load mocking/stubbing library, sinon
-// docs: http://sinonjs.org/docs/
-Services.scriptloader.loadSubScript("resource://testing-common/sinon-1.16.1.js");
-
-registerCleanupFunction(function () {
- gTestTargetFile.remove(false);
-
- delete window.sinon;
- delete window.setImmediate;
- delete window.clearImmediate;
-});
-
-////////////////////////////////////////////////////////////////////////////////
-//// Asynchronous support subroutines
-
-function promiseOpenAndLoadWindow(aOptions)
-{
- return new Promise((resolve, reject) => {
- let win = OpenBrowserWindow(aOptions);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- resolve(win);
- });
- });
-}
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @param [optional] event
- * The load event type to wait for. Defaults to "load".
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url, eventType="load")
-{
- let deferred = Promise.defer();
- info("Wait tab event: " + eventType);
-
- function handle(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank" ||
- (url && event.target.location.href != url)) {
- info("Skipping spurious '" + eventType + "'' event" +
- " for " + event.target.location.href);
- return;
- }
- // Remove reference to tab from the cleanup function:
- realCleanup = () => {};
- tab.linkedBrowser.removeEventListener(eventType, handle, true);
- info("Tab event received: " + eventType);
- deferred.resolve(event);
- }
-
- // Juggle a bit to avoid leaks:
- let realCleanup = () => tab.linkedBrowser.removeEventListener(eventType, handle, true);
- registerCleanupFunction(() => realCleanup());
-
- tab.linkedBrowser.addEventListener(eventType, handle, true, true);
- if (url)
- tab.linkedBrowser.loadURI(url);
- return deferred.promise;
-}
-
-function promiseWindowClosed(win)
-{
- let promise = new Promise((resolve, reject) => {
- Services.obs.addObserver(function obs(subject, topic) {
- if (subject == win) {
- Services.obs.removeObserver(obs, topic);
- resolve();
- }
- }, "domwindowclosed", false);
- });
- win.close();
- return promise;
-}
-
-
-function promiseFocus()
-{
- let deferred = Promise.defer();
- waitForFocus(deferred.resolve);
- return deferred.promise;
-}
-
-function promisePanelOpened()
-{
- let deferred = Promise.defer();
-
- if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") {
- return deferred.resolve();
- }
-
- // Hook to wait until the panel is shown.
- let originalOnPopupShown = DownloadsPanel.onPopupShown;
- DownloadsPanel.onPopupShown = function () {
- DownloadsPanel.onPopupShown = originalOnPopupShown;
- originalOnPopupShown.apply(this, arguments);
-
- // Defer to the next tick of the event loop so that we don't continue
- // processing during the DOM event handler itself.
- setTimeout(deferred.resolve, 0);
- };
-
- return deferred.promise;
-}
-
-function* task_resetState()
-{
- // Remove all downloads.
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
- let downloads = yield publicList.getAll();
- for (let download of downloads) {
- publicList.remove(download);
- yield download.finalize(true);
- }
-
- DownloadsPanel.hidePanel();
-
- yield promiseFocus();
-}
-
-function* task_addDownloads(aItems)
-{
- let startTimeMs = Date.now();
-
- let publicList = yield Downloads.getList(Downloads.PUBLIC);
- for (let item of aItems) {
- let download = {
- source: {
- url: "http://www.example.com/test-download.txt",
- },
- target: {
- path: gTestTargetFile.path,
- },
- succeeded: item.state == nsIDM.DOWNLOAD_FINISHED,
- canceled: item.state == nsIDM.DOWNLOAD_CANCELED ||
- item.state == nsIDM.DOWNLOAD_PAUSED,
- error: item.state == nsIDM.DOWNLOAD_FAILED ? new Error("Failed.") : null,
- hasPartialData: item.state == nsIDM.DOWNLOAD_PAUSED,
- hasBlockedData: item.hasBlockedData || false,
- startTime: new Date(startTimeMs++),
- };
- // `"errorObj" in download` must be false when there's no error.
- if (item.errorObj) {
- download.errorObj = item.errorObj;
- }
- yield publicList.add(yield Downloads.createDownload(download));
- }
-}
-
-function* task_openPanel()
-{
- yield promiseFocus();
-
- let promise = promisePanelOpened();
- DownloadsPanel.showPanel();
- yield promise;
-}
-
-function* setDownloadDir() {
- let tmpDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
- tmpDir.append("testsavedir");
- if (!tmpDir.exists()) {
- tmpDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
- registerCleanupFunction(function () {
- try {
- tmpDir.remove(true);
- } catch (e) {
- // On Windows debug build this may fail.
- }
- });
- }
-
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [
- ["browser.download.folderList", 2],
- ["browser.download.dir", tmpDir, Ci.nsIFile],
- ]}, resolve);
- });
-}
-
-
-let gHttpServer = null;
-function startServer() {
- gHttpServer = new HttpServer();
- gHttpServer.start(-1);
- registerCleanupFunction(function*() {
- yield new Promise(function(resolve) {
- gHttpServer.stop(resolve);
- });
- });
-
- gHttpServer.registerPathHandler("/file1.txt", (request, response) => {
- response.setStatusLine(null, 200, "OK");
- response.write("file1");
- response.processAsync();
- response.finish();
- });
- gHttpServer.registerPathHandler("/file2.txt", (request, response) => {
- response.setStatusLine(null, 200, "OK");
- response.write("file2");
- response.processAsync();
- response.finish();
- });
- gHttpServer.registerPathHandler("/file3.txt", (request, response) => {
- response.setStatusLine(null, 200, "OK");
- response.write("file3");
- response.processAsync();
- response.finish();
- });
-}
-
-function httpUrl(aFileName) {
- return "http://localhost:" + gHttpServer.identity.primaryPort + "/" +
- aFileName;
-}
-
-function task_clearHistory() {
- return new Promise(function(resolve) {
- Services.obs.addObserver(function observeCH(aSubject, aTopic, aData) {
- Services.obs.removeObserver(observeCH, PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- resolve();
- }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
- PlacesUtils.history.clear();
- });
-}
-
-function openLibrary(aLeftPaneRoot) {
- let library = window.openDialog("chrome://browser/content/places/places.xul",
- "", "chrome,toolbar=yes,dialog=no,resizable",
- aLeftPaneRoot);
-
- return new Promise(resolve => {
- waitForFocus(resolve, library);
- });
-}
-
-function promiseAlertDialogOpen(buttonAction) {
- return new Promise(resolve => {
- Services.ww.registerNotification(function onOpen(subj, topic, data) {
- if (topic == "domwindowopened" && subj instanceof Ci.nsIDOMWindow) {
- // The test listens for the "load" event which guarantees that the alert
- // class has already been added (it is added when "DOMContentLoaded" is
- // fired).
- subj.addEventListener("load", function onLoad() {
- subj.removeEventListener("load", onLoad);
- if (subj.document.documentURI ==
- "chrome://global/content/commonDialog.xul") {
- Services.ww.unregisterNotification(onOpen);
-
- let dialog = subj.document.getElementById("commonDialog");
- ok(dialog.classList.contains("alert-dialog"),
- "The dialog element should contain an alert class.");
-
- let doc = subj.document.documentElement;
- doc.getButton(buttonAction).click();
- resolve();
- }
- });
- }
- });
- });
-}
diff --git a/browser/components/downloads/test/unit/.eslintrc.js b/browser/components/downloads/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/downloads/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/downloads/test/unit/head.js b/browser/components/downloads/test/unit/head.js
deleted file mode 100644
index d7ce4d48a..000000000
--- a/browser/components/downloads/test/unit/head.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Provides infrastructure for automated download components tests.
- */
-
-////////////////////////////////////////////////////////////////////////////////
-//// Globals
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource:///modules/DownloadsCommon.jsm");
diff --git a/browser/components/downloads/test/unit/test_DownloadsCommon.js b/browser/components/downloads/test/unit/test_DownloadsCommon.js
deleted file mode 100644
index 46afbaef9..000000000
--- a/browser/components/downloads/test/unit/test_DownloadsCommon.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests for the functions located directly in the "DownloadsCommon" object.
- */
-
-function testFormatTimeLeft(aSeconds, aExpectedValue, aExpectedUnitString)
-{
- let expected = "";
- if (aExpectedValue) {
- // Format the expected result based on the current language.
- expected = DownloadsCommon.strings[aExpectedUnitString](aExpectedValue);
- }
- do_check_eq(DownloadsCommon.formatTimeLeft(aSeconds), expected);
-}
-
-function run_test()
-{
- testFormatTimeLeft( 0, "", "");
- testFormatTimeLeft( 1, "1", "shortTimeLeftSeconds");
- testFormatTimeLeft( 29, "29", "shortTimeLeftSeconds");
- testFormatTimeLeft( 30, "30", "shortTimeLeftSeconds");
- testFormatTimeLeft( 31, "1", "shortTimeLeftMinutes");
- testFormatTimeLeft( 60, "1", "shortTimeLeftMinutes");
- testFormatTimeLeft( 89, "1", "shortTimeLeftMinutes");
- testFormatTimeLeft( 90, "2", "shortTimeLeftMinutes");
- testFormatTimeLeft( 91, "2", "shortTimeLeftMinutes");
- testFormatTimeLeft( 3600, "1", "shortTimeLeftHours");
- testFormatTimeLeft( 86400, "24", "shortTimeLeftHours");
- testFormatTimeLeft( 169200, "47", "shortTimeLeftHours");
- testFormatTimeLeft( 172800, "2", "shortTimeLeftDays");
- testFormatTimeLeft(8553600, "99", "shortTimeLeftDays");
- testFormatTimeLeft(8640000, "99", "shortTimeLeftDays");
-}
diff --git a/browser/components/downloads/test/unit/xpcshell.ini b/browser/components/downloads/test/unit/xpcshell.ini
deleted file mode 100644
index f53a8cf89..000000000
--- a/browser/components/downloads/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_DownloadsCommon.js]
diff --git a/browser/components/extensions/test/browser/.eslintrc.js b/browser/components/extensions/test/browser/.eslintrc.js
deleted file mode 100644
index 0e673ecb9..000000000
--- a/browser/components/extensions/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": "../../../../../testing/mochitest/browser.eslintrc.js",
-
- "env": {
- "webextensions": true,
- },
-
- "globals": {
- "NetUtil": true,
- "XPCOMUtils": true,
- "Task": true,
-
- // Browser window globals.
- "PanelUI": false,
-
- // Test harness globals
- "ExtensionTestUtils": false,
- "TestUtils": false,
-
- "clickBrowserAction": true,
- "clickPageAction": true,
- "closeContextMenu": true,
- "closeExtensionContextMenu": true,
- "focusWindow": true,
- "makeWidgetId": true,
- "openContextMenu": true,
- "openExtensionContextMenu": true,
- "CustomizableUI": true,
- },
-
- "rules": {
- "no-shadow": 0,
- },
-};
diff --git a/browser/components/extensions/test/browser/browser.ini b/browser/components/extensions/test/browser/browser.ini
deleted file mode 100644
index 1e894dcb5..000000000
--- a/browser/components/extensions/test/browser/browser.ini
+++ /dev/null
@@ -1,115 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- head_pageAction.js
- head_sessions.js
- context.html
- ctxmenu-image.png
- context_tabs_onUpdated_page.html
- context_tabs_onUpdated_iframe.html
- file_popup_api_injection_a.html
- file_popup_api_injection_b.html
- file_iframe_document.html
- file_iframe_document.sjs
- file_bypass_cache.sjs
- file_language_fr_en.html
- file_language_ja.html
- file_language_tlh.html
- file_dummy.html
- searchSuggestionEngine.xml
- searchSuggestionEngine.sjs
- ../../../../../toolkit/components/extensions/test/mochitest/head_webrequest.js
-tags = webextensions
-
-
-[browser_ext_browserAction_context.js]
-[browser_ext_browserAction_disabled.js]
-[browser_ext_browserAction_pageAction_icon.js]
-[browser_ext_browserAction_pageAction_icon_permissions.js]
-[browser_ext_browserAction_popup.js]
-[browser_ext_browserAction_popup_resize.js]
-[browser_ext_browserAction_simple.js]
-[browser_ext_commands_execute_browser_action.js]
-[browser_ext_commands_execute_page_action.js]
-[browser_ext_commands_getAll.js]
-[browser_ext_commands_onCommand.js]
-[browser_ext_contentscript_connect.js]
-[browser_ext_contextMenus.js]
-[browser_ext_contextMenus_checkboxes.js]
-[browser_ext_contextMenus_icons.js]
-[browser_ext_contextMenus_onclick.js]
-[browser_ext_contextMenus_radioGroups.js]
-[browser_ext_contextMenus_uninstall.js]
-[browser_ext_contextMenus_urlPatterns.js]
-[browser_ext_currentWindow.js]
-[browser_ext_getViews.js]
-[browser_ext_incognito_popup.js]
-[browser_ext_incognito_views.js]
-[browser_ext_lastError.js]
-[browser_ext_legacy_extension_context_contentscript.js]
-[browser_ext_omnibox.js]
-[browser_ext_optionsPage_privileges.js]
-[browser_ext_pageAction_context.js]
-[browser_ext_pageAction_popup.js]
-[browser_ext_pageAction_popup_resize.js]
-[browser_ext_pageAction_simple.js]
-[browser_ext_pageAction_title.js]
-[browser_ext_popup_api_injection.js]
-[browser_ext_popup_background.js]
-[browser_ext_popup_corners.js]
-[browser_ext_popup_sendMessage.js]
-[browser_ext_popup_shutdown.js]
-[browser_ext_runtime_openOptionsPage.js]
-[browser_ext_runtime_openOptionsPage_uninstall.js]
-[browser_ext_runtime_setUninstallURL.js]
-[browser_ext_sessions_getRecentlyClosed.js]
-[browser_ext_sessions_getRecentlyClosed_private.js]
-[browser_ext_sessions_getRecentlyClosed_tabs.js]
-[browser_ext_sessions_restore.js]
-[browser_ext_simple.js]
-[browser_ext_tab_runtimeConnect.js]
-[browser_ext_tabs_audio.js]
-[browser_ext_tabs_captureVisibleTab.js]
-[browser_ext_tabs_create.js]
-[browser_ext_tabs_create_invalid_url.js]
-[browser_ext_tabs_detectLanguage.js]
-[browser_ext_tabs_duplicate.js]
-[browser_ext_tabs_events.js]
-[browser_ext_tabs_executeScript.js]
-[browser_ext_tabs_executeScript_good.js]
-[browser_ext_tabs_executeScript_bad.js]
-[browser_ext_tabs_executeScript_runAt.js]
-[browser_ext_tabs_getCurrent.js]
-[browser_ext_tabs_insertCSS.js]
-[browser_ext_tabs_removeCSS.js]
-[browser_ext_tabs_move.js]
-[browser_ext_tabs_move_window.js]
-[browser_ext_tabs_move_window_multiple.js]
-[browser_ext_tabs_move_window_pinned.js]
-[browser_ext_tabs_onHighlighted.js]
-[browser_ext_tabs_onUpdated.js]
-[browser_ext_tabs_query.js]
-[browser_ext_tabs_reload.js]
-[browser_ext_tabs_reload_bypass_cache.js]
-[browser_ext_tabs_sendMessage.js]
-[browser_ext_tabs_cookieStoreId.js]
-[browser_ext_tabs_update.js]
-[browser_ext_tabs_zoom.js]
-[browser_ext_tabs_update_url.js]
-[browser_ext_topwindowid.js]
-[browser_ext_webNavigation_frameId0.js]
-[browser_ext_webNavigation_getFrames.js]
-[browser_ext_webNavigation_urlbar_transitions.js]
-[browser_ext_webRequest.js]
-[browser_ext_windows.js]
-[browser_ext_windows_allowScriptsToClose.js]
-[browser_ext_windows_create.js]
-tags = fullscreen
-[browser_ext_windows_create_params.js]
-[browser_ext_windows_create_tabId.js]
-[browser_ext_windows_create_url.js]
-[browser_ext_windows_events.js]
-[browser_ext_windows_size.js]
-skip-if = os == 'mac' # Fails when windows are randomly opened in fullscreen mode
-[browser_ext_windows_update.js]
-tags = fullscreen
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_context.js b/browser/components/extensions/test/browser/browser_ext_browserAction_context.js
deleted file mode 100644
index 8a26dbb3c..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_context.js
+++ /dev/null
@@ -1,398 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* runTests(options) {
- async function background(getTests) {
- async function checkDetails(expecting, tabId) {
- let title = await browser.browserAction.getTitle({tabId});
- browser.test.assertEq(expecting.title, title,
- "expected value from getTitle");
-
- let popup = await browser.browserAction.getPopup({tabId});
- browser.test.assertEq(expecting.popup, popup,
- "expected value from getPopup");
-
- let badge = await browser.browserAction.getBadgeText({tabId});
- browser.test.assertEq(expecting.badge, badge,
- "expected value from getBadge");
-
- let badgeBackgroundColor = await browser.browserAction.getBadgeBackgroundColor({tabId});
- browser.test.assertEq(String(expecting.badgeBackgroundColor),
- String(badgeBackgroundColor),
- "expected value from getBadgeBackgroundColor");
- }
-
- let expectDefaults = expecting => {
- return checkDetails(expecting);
- };
-
- let tabs = [];
- let tests = getTests(tabs, expectDefaults);
-
- {
- let tabId = 0xdeadbeef;
- let calls = [
- () => browser.browserAction.enable(tabId),
- () => browser.browserAction.disable(tabId),
- () => browser.browserAction.setTitle({tabId, title: "foo"}),
- () => browser.browserAction.setIcon({tabId, path: "foo.png"}),
- () => browser.browserAction.setPopup({tabId, popup: "foo.html"}),
- () => browser.browserAction.setBadgeText({tabId, text: "foo"}),
- () => browser.browserAction.setBadgeBackgroundColor({tabId, color: [0xff, 0, 0, 0xff]}),
- ];
-
- for (let call of calls) {
- await browser.test.assertRejects(
- new Promise(resolve => resolve(call())),
- RegExp(`Invalid tab ID: ${tabId}`),
- "Expected invalid tab ID error");
- }
- }
-
- // Runs the next test in the `tests` array, checks the results,
- // and passes control back to the outer test scope.
- function nextTest() {
- let test = tests.shift();
-
- test(async expecting => {
- // Check that the API returns the expected values, and then
- // run the next test.
- let tabs = await browser.tabs.query({active: true, currentWindow: true});
- await checkDetails(expecting, tabs[0].id);
-
- // Check that the actual icon has the expected values, then
- // run the next test.
- browser.test.sendMessage("nextTest", expecting, tests.length);
- });
- }
-
- browser.test.onMessage.addListener((msg) => {
- if (msg != "runNextTest") {
- browser.test.fail("Expecting 'runNextTest' message");
- }
-
- nextTest();
- });
-
- browser.tabs.query({active: true, currentWindow: true}, resultTabs => {
- tabs[0] = resultTabs[0].id;
-
- nextTest();
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: options.manifest,
-
- files: options.files || {},
-
- background: `(${background})(${options.getTests})`,
- });
-
- let browserActionId;
- function checkDetails(details) {
- if (!browserActionId) {
- browserActionId = `${makeWidgetId(extension.id)}-browser-action`;
- }
-
- let button = document.getElementById(browserActionId);
-
- ok(button, "button exists");
-
- let title = details.title || options.manifest.name;
-
- is(getListStyleImage(button), details.icon, "icon URL is correct");
- is(button.getAttribute("tooltiptext"), title, "image title is correct");
- is(button.getAttribute("label"), title, "image label is correct");
- is(button.getAttribute("badge"), details.badge, "badge text is correct");
- is(button.getAttribute("disabled") == "true", Boolean(details.disabled), "disabled state is correct");
-
- if (details.badge && details.badgeBackgroundColor) {
- let badge = button.ownerDocument.getAnonymousElementByAttribute(
- button, "class", "toolbarbutton-badge");
-
- let badgeColor = window.getComputedStyle(badge).backgroundColor;
- let color = details.badgeBackgroundColor;
- let expectedColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
-
- is(badgeColor, expectedColor, "badge color is correct");
- }
-
-
- // TODO: Popup URL.
- }
-
- let awaitFinish = new Promise(resolve => {
- extension.onMessage("nextTest", (expecting, testsRemaining) => {
- checkDetails(expecting);
-
- if (testsRemaining) {
- extension.sendMessage("runNextTest");
- } else {
- resolve();
- }
- });
- });
-
- yield extension.startup();
-
- yield awaitFinish;
-
- yield extension.unload();
-}
-
-add_task(function* testTabSwitchContext() {
- yield runTests({
- manifest: {
- "browser_action": {
- "default_icon": "default.png",
- "default_popup": "__MSG_popup__",
- "default_title": "Default __MSG_title__",
- },
-
- "default_locale": "en",
-
- "permissions": ["tabs"],
- },
-
- "files": {
- "_locales/en/messages.json": {
- "popup": {
- "message": "default.html",
- "description": "Popup",
- },
-
- "title": {
- "message": "Title",
- "description": "Title",
- },
- },
-
- "default.png": imageBuffer,
- "default-2.png": imageBuffer,
- "1.png": imageBuffer,
- "2.png": imageBuffer,
- },
-
- getTests(tabs, expectDefaults) {
- const DEFAULT_BADGE_COLOR = [0xd9, 0, 0, 255];
-
- let details = [
- {"icon": browser.runtime.getURL("default.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default Title",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR},
- {"icon": browser.runtime.getURL("1.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default Title",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR},
- {"icon": browser.runtime.getURL("2.png"),
- "popup": browser.runtime.getURL("2.html"),
- "title": "Title 2",
- "badge": "2",
- "badgeBackgroundColor": [0xff, 0, 0, 0xff],
- "disabled": true},
- {"icon": browser.runtime.getURL("1.png"),
- "popup": browser.runtime.getURL("default-2.html"),
- "title": "Default Title 2",
- "badge": "d2",
- "badgeBackgroundColor": [0, 0xff, 0, 0xff],
- "disabled": true},
- {"icon": browser.runtime.getURL("1.png"),
- "popup": browser.runtime.getURL("default-2.html"),
- "title": "Default Title 2",
- "badge": "d2",
- "badgeBackgroundColor": [0, 0xff, 0, 0xff],
- "disabled": false},
- {"icon": browser.runtime.getURL("default-2.png"),
- "popup": browser.runtime.getURL("default-2.html"),
- "title": "Default Title 2",
- "badge": "d2",
- "badgeBackgroundColor": [0, 0xff, 0, 0xff]},
- ];
-
- return [
- async expect => {
- browser.test.log("Initial state, expect default properties.");
-
- await expectDefaults(details[0]);
- expect(details[0]);
- },
- async expect => {
- browser.test.log("Change the icon in the current tab. Expect default properties excluding the icon.");
- browser.browserAction.setIcon({tabId: tabs[0], path: "1.png"});
-
- await expectDefaults(details[0]);
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Create a new tab. Expect default properties.");
- let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
- tabs.push(tab.id);
-
- await expectDefaults(details[0]);
- expect(details[0]);
- },
- async expect => {
- browser.test.log("Change properties. Expect new properties.");
- let tabId = tabs[1];
- browser.browserAction.setIcon({tabId, path: "2.png"});
- browser.browserAction.setPopup({tabId, popup: "2.html"});
- browser.browserAction.setTitle({tabId, title: "Title 2"});
- browser.browserAction.setBadgeText({tabId, text: "2"});
- browser.browserAction.setBadgeBackgroundColor({tabId, color: "#ff0000"});
- browser.browserAction.disable(tabId);
-
- await expectDefaults(details[0]);
- expect(details[2]);
- },
- expect => {
- browser.test.log("Navigate to a new page. Expect no changes.");
-
- // TODO: This listener should not be necessary, but the |tabs.update|
- // callback currently fires too early in e10s windows.
- browser.tabs.onUpdated.addListener(function listener(tabId, changed) {
- if (tabId == tabs[1] && changed.url) {
- browser.tabs.onUpdated.removeListener(listener);
- expect(details[2]);
- }
- });
-
- browser.tabs.update(tabs[1], {url: "about:blank?1"});
- },
- async expect => {
- browser.test.log("Switch back to the first tab. Expect previously set properties.");
- await browser.tabs.update(tabs[0], {active: true});
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Change default values, expect those changes reflected.");
- browser.browserAction.setIcon({path: "default-2.png"});
- browser.browserAction.setPopup({popup: "default-2.html"});
- browser.browserAction.setTitle({title: "Default Title 2"});
- browser.browserAction.setBadgeText({text: "d2"});
- browser.browserAction.setBadgeBackgroundColor({color: [0, 0xff, 0, 0xff]});
- browser.browserAction.disable();
-
- await expectDefaults(details[3]);
- expect(details[3]);
- },
- async expect => {
- browser.test.log("Re-enable by default. Expect enabled.");
- browser.browserAction.enable();
-
- await expectDefaults(details[4]);
- expect(details[4]);
- },
- async expect => {
- browser.test.log("Switch back to tab 2. Expect former value, unaffected by changes to defaults in previous step.");
- await browser.tabs.update(tabs[1], {active: true});
-
- await expectDefaults(details[3]);
- expect(details[2]);
- },
- async expect => {
- browser.test.log("Delete tab, switch back to tab 1. Expect previous results again.");
- await browser.tabs.remove(tabs[1]);
- expect(details[4]);
- },
- async expect => {
- browser.test.log("Create a new tab. Expect new default properties.");
- let tab = await browser.tabs.create({active: true, url: "about:blank?2"});
- tabs.push(tab.id);
- expect(details[5]);
- },
- async expect => {
- browser.test.log("Delete tab.");
- await browser.tabs.remove(tabs[2]);
- expect(details[4]);
- },
- ];
- },
- });
-});
-
-add_task(function* testDefaultTitle() {
- yield runTests({
- manifest: {
- "name": "Foo Extension",
-
- "browser_action": {
- "default_icon": "icon.png",
- },
-
- "permissions": ["tabs"],
- },
-
- files: {
- "icon.png": imageBuffer,
- },
-
- getTests(tabs, expectDefaults) {
- const DEFAULT_BADGE_COLOR = [0xd9, 0, 0, 255];
-
- let details = [
- {"title": "Foo Extension",
- "popup": "",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR,
- "icon": browser.runtime.getURL("icon.png")},
- {"title": "Foo Title",
- "popup": "",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR,
- "icon": browser.runtime.getURL("icon.png")},
- {"title": "Bar Title",
- "popup": "",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR,
- "icon": browser.runtime.getURL("icon.png")},
- {"title": "",
- "popup": "",
- "badge": "",
- "badgeBackgroundColor": DEFAULT_BADGE_COLOR,
- "icon": browser.runtime.getURL("icon.png")},
- ];
-
- return [
- async expect => {
- browser.test.log("Initial state. Expect extension title as default title.");
-
- await expectDefaults(details[0]);
- expect(details[0]);
- },
- async expect => {
- browser.test.log("Change the title. Expect new title.");
- browser.browserAction.setTitle({tabId: tabs[0], title: "Foo Title"});
-
- await expectDefaults(details[0]);
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Change the default. Expect same properties.");
- browser.browserAction.setTitle({title: "Bar Title"});
-
- await expectDefaults(details[2]);
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Clear the title. Expect new default title.");
- browser.browserAction.setTitle({tabId: tabs[0], title: ""});
-
- await expectDefaults(details[2]);
- expect(details[2]);
- },
- async expect => {
- browser.test.log("Set default title to null string. Expect null string from API, extension title in UI.");
- browser.browserAction.setTitle({title: ""});
-
- await expectDefaults(details[3]);
- expect(details[3]);
- },
- ];
- },
- });
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js b/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js
deleted file mode 100644
index c0b9c1a1d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testDisabled() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {},
- },
-
- background: function() {
- let clicked = false;
-
- browser.browserAction.onClicked.addListener(() => {
- browser.test.log("Got click event");
- clicked = true;
- });
-
- browser.test.onMessage.addListener((msg, expectClick) => {
- if (msg == "enable") {
- browser.test.log("enable browserAction");
- browser.browserAction.enable();
- } else if (msg == "disable") {
- browser.test.log("disable browserAction");
- browser.browserAction.disable();
- } else if (msg == "check-clicked") {
- browser.test.assertEq(expectClick, clicked, "got click event?");
- clicked = false;
- } else {
- browser.test.fail("Unexpected message");
- }
-
- browser.test.sendMessage("next-test");
- });
-
- browser.test.sendMessage("ready");
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- yield clickBrowserAction(extension);
- yield new Promise(resolve => setTimeout(resolve, 0));
-
- extension.sendMessage("check-clicked", true);
- yield extension.awaitMessage("next-test");
-
- extension.sendMessage("disable");
- yield extension.awaitMessage("next-test");
-
- yield clickBrowserAction(extension);
- yield new Promise(resolve => setTimeout(resolve, 0));
-
- extension.sendMessage("check-clicked", false);
- yield extension.awaitMessage("next-test");
-
- extension.sendMessage("enable");
- yield extension.awaitMessage("next-test");
-
- yield clickBrowserAction(extension);
- yield new Promise(resolve => setTimeout(resolve, 0));
-
- extension.sendMessage("check-clicked", true);
- yield extension.awaitMessage("next-test");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js b/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js
deleted file mode 100644
index 9665d6832..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js
+++ /dev/null
@@ -1,321 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-// Test that various combinations of icon details specs, for both paths
-// and ImageData objects, result in the correct image being displayed in
-// all display resolutions.
-add_task(function* testDetailsObjects() {
- function background() {
- function getImageData(color) {
- let canvas = document.createElement("canvas");
- canvas.width = 2;
- canvas.height = 2;
- let canvasContext = canvas.getContext("2d");
-
- canvasContext.clearRect(0, 0, canvas.width, canvas.height);
- canvasContext.fillStyle = color;
- canvasContext.fillRect(0, 0, 1, 1);
-
- return {
- url: canvas.toDataURL("image/png"),
- imageData: canvasContext.getImageData(0, 0, canvas.width, canvas.height),
- };
- }
-
- let imageData = {
- red: getImageData("red"),
- green: getImageData("green"),
- };
-
- /* eslint-disable comma-dangle, indent */
- let iconDetails = [
- // Only paths.
- {details: {"path": "a.png"},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a.png")}},
- {details: {"path": "/a.png"},
- resolutions: {
- "1": browser.runtime.getURL("a.png"),
- "2": browser.runtime.getURL("a.png")}},
- {details: {"path": {"19": "a.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a.png")}},
- {details: {"path": {"38": "a.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a.png")}},
- {details: {"path": {"19": "a.png", "38": "a-x2.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a-x2.png")}},
-
- // Test that CSS strings are escaped properly.
- {details: {"path": 'a.png#" \\'},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png#%22%20%5C"),
- "2": browser.runtime.getURL("data/a.png#%22%20%5C")}},
-
- // Only ImageData objects.
- {details: {"imageData": imageData.red.imageData},
- resolutions: {
- "1": imageData.red.url,
- "2": imageData.red.url}},
- {details: {"imageData": {"19": imageData.red.imageData}},
- resolutions: {
- "1": imageData.red.url,
- "2": imageData.red.url}},
- {details: {"imageData": {"38": imageData.red.imageData}},
- resolutions: {
- "1": imageData.red.url,
- "2": imageData.red.url}},
- {details: {"imageData": {
- "19": imageData.red.imageData,
- "38": imageData.green.imageData}},
- resolutions: {
- "1": imageData.red.url,
- "2": imageData.green.url}},
-
- // Mixed path and imageData objects.
- //
- // The behavior is currently undefined if both |path| and
- // |imageData| specify icons of the same size.
- {details: {
- "path": {"19": "a.png"},
- "imageData": {"38": imageData.red.imageData}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": imageData.red.url}},
- {details: {
- "path": {"38": "a.png"},
- "imageData": {"19": imageData.red.imageData}},
- resolutions: {
- "1": imageData.red.url,
- "2": browser.runtime.getURL("data/a.png")}},
-
- // A path or ImageData object by itself is treated as a 19px icon.
- {details: {
- "path": "a.png",
- "imageData": {"38": imageData.red.imageData}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": imageData.red.url}},
- {details: {
- "path": {"38": "a.png"},
- "imageData": imageData.red.imageData},
- resolutions: {
- "1": imageData.red.url,
- "2": browser.runtime.getURL("data/a.png")}},
-
- // Various resolutions
- {details: {"path": {"18": "a.png", "36": "a-x2.png"}},
- legacy: true,
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a-x2.png")}},
- {details: {"path": {"16": "a.png", "30": "a-x2.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/a.png"),
- "2": browser.runtime.getURL("data/a-x2.png")}},
- {details: {"path": {"16": "16.png", "100": "100.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/16.png"),
- "2": browser.runtime.getURL("data/100.png")}},
- {details: {"path": {"2": "2.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/2.png"),
- "2": browser.runtime.getURL("data/2.png")}},
- {details: {"path": {
- "16": "16.svg",
- "18": "18.svg"}},
- resolutions: {
- "1": browser.runtime.getURL("data/16.svg"),
- "2": browser.runtime.getURL("data/18.svg")}},
- {details: {"path": {
- "6": "6.png",
- "18": "18.png",
- "36": "36.png",
- "48": "48.png",
- "128": "128.png"}},
- legacy: true,
- resolutions: {
- "1": browser.runtime.getURL("data/18.png"),
- "2": browser.runtime.getURL("data/36.png")},
- menuResolutions: {
- "1": browser.runtime.getURL("data/36.png"),
- "2": browser.runtime.getURL("data/128.png")}},
- {details: {"path": {
- "16": "16.png",
- "18": "18.png",
- "32": "32.png",
- "48": "48.png",
- "64": "64.png",
- "128": "128.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/16.png"),
- "2": browser.runtime.getURL("data/32.png")},
- menuResolutions: {
- "1": browser.runtime.getURL("data/32.png"),
- "2": browser.runtime.getURL("data/64.png")}},
- {details: {"path": {
- "18": "18.png",
- "32": "32.png",
- "48": "48.png",
- "128": "128.png"}},
- resolutions: {
- "1": browser.runtime.getURL("data/32.png"),
- "2": browser.runtime.getURL("data/32.png")}},
- ];
-
- // Allow serializing ImageData objects for logging.
- ImageData.prototype.toJSON = () => "<ImageData>";
-
- let tabId;
-
- browser.test.onMessage.addListener((msg, test) => {
- if (msg != "setIcon") {
- browser.test.fail("expecting 'setIcon' message");
- }
-
- let details = iconDetails[test.index];
-
- let detailString = JSON.stringify(details);
- browser.test.log(`Setting browerAction/pageAction to ${detailString} expecting URLs ${JSON.stringify(details.resolutions)}`);
-
- Promise.all([
- browser.browserAction.setIcon(Object.assign({tabId}, details.details)),
- browser.pageAction.setIcon(Object.assign({tabId}, details.details)),
- ]).then(() => {
- browser.test.sendMessage("iconSet");
- });
- });
-
- // Generate a list of tests and resolutions to send back to the test
- // context.
- //
- // This process is a bit convoluted, because the outer test context needs
- // to handle checking the button nodes and changing the screen resolution,
- // but it can't pass us icon definitions with ImageData objects. This
- // shouldn't be a problem, since structured clones should handle ImageData
- // objects without issue. Unfortunately, |cloneInto| implements a slightly
- // different algorithm than we use in web APIs, and does not handle them
- // correctly.
- let tests = [];
- for (let [idx, icon] of iconDetails.entries()) {
- tests.push({
- index: idx,
- legacy: !!icon.legacy,
- menuResolutions: icon.menuResolutions,
- resolutions: icon.resolutions,
- });
- }
-
- // Sort by resolution, so we don't needlessly switch back and forth
- // between each test.
- tests.sort(test => test.resolution);
-
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- tabId = tabs[0].id;
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("ready", tests);
- });
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {},
- "page_action": {},
- "background": {
- "page": "data/background.html",
- }
- },
-
- files: {
- "data/background.html": `<script src="background.js"></script>`,
- "data/background.js": background,
-
- "data/16.svg": imageBuffer,
- "data/18.svg": imageBuffer,
-
- "data/16.png": imageBuffer,
- "data/18.png": imageBuffer,
- "data/32.png": imageBuffer,
- "data/36.png": imageBuffer,
- "data/48.png": imageBuffer,
- "data/64.png": imageBuffer,
- "data/128.png": imageBuffer,
-
- "a.png": imageBuffer,
- "data/2.png": imageBuffer,
- "data/100.png": imageBuffer,
- "data/a.png": imageBuffer,
- "data/a-x2.png": imageBuffer,
- },
- });
-
- const RESOLUTION_PREF = "layout.css.devPixelsPerPx";
-
- yield extension.startup();
-
- let pageActionId = `${makeWidgetId(extension.id)}-page-action`;
- let browserActionWidget = getBrowserActionWidget(extension);
-
- let tests = yield extension.awaitMessage("ready");
- for (let test of tests) {
- extension.sendMessage("setIcon", test);
- yield extension.awaitMessage("iconSet");
-
- let browserActionButton = browserActionWidget.forWindow(window).node;
- let pageActionImage = document.getElementById(pageActionId);
-
-
- // Test icon sizes in the toolbar/urlbar.
- for (let resolution of Object.keys(test.resolutions)) {
- yield SpecialPowers.pushPrefEnv({set: [[RESOLUTION_PREF, resolution]]});
-
- is(window.devicePixelRatio, +resolution, "window has the required resolution");
-
- let imageURL = test.resolutions[resolution];
- is(getListStyleImage(browserActionButton), imageURL, `browser action has the correct image at ${resolution}x resolution`);
- is(getListStyleImage(pageActionImage), imageURL, `page action has the correct image at ${resolution}x resolution`);
-
- let isLegacy = browserActionButton.classList.contains("toolbarbutton-legacy-addon");
- is(isLegacy, test.legacy, "Legacy class should be present?");
-
- yield SpecialPowers.popPrefEnv();
- }
-
- if (!test.menuResolutions) {
- continue;
- }
-
-
- // Test icon sizes in the menu panel.
- CustomizableUI.addWidgetToArea(browserActionWidget.id,
- CustomizableUI.AREA_PANEL);
-
- yield showBrowserAction(extension);
- browserActionButton = browserActionWidget.forWindow(window).node;
-
- for (let resolution of Object.keys(test.menuResolutions)) {
- yield SpecialPowers.pushPrefEnv({set: [[RESOLUTION_PREF, resolution]]});
-
- is(window.devicePixelRatio, +resolution, "window has the required resolution");
-
- let imageURL = test.menuResolutions[resolution];
- is(getListStyleImage(browserActionButton), imageURL, `browser action has the correct menu image at ${resolution}x resolution`);
-
- yield SpecialPowers.popPrefEnv();
- }
-
- yield closeBrowserAction(extension);
-
- CustomizableUI.addWidgetToArea(browserActionWidget.id,
- CustomizableUI.AREA_NAVBAR);
- }
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js b/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js
deleted file mode 100644
index 110746cae..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-// Test that an error is thrown when providing invalid icon sizes
-add_task(function* testInvalidIconSizes() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {},
- "page_action": {},
- },
-
- background: function() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- let tabId = tabs[0].id;
-
- let promises = [];
- for (let api of ["pageAction", "browserAction"]) {
- // helper function to run setIcon and check if it fails
- let assertSetIconThrows = function(detail, error, message) {
- detail.tabId = tabId;
- promises.push(
- browser.test.assertRejects(
- browser[api].setIcon(detail),
- /must be an integer/,
- "setIcon with invalid icon size"));
- };
-
- let imageData = new ImageData(1, 1);
-
- // test invalid icon size inputs
- for (let type of ["path", "imageData"]) {
- let img = type == "imageData" ? imageData : "test.png";
-
- assertSetIconThrows({[type]: {"abcdef": img}});
- assertSetIconThrows({[type]: {"48px": img}});
- assertSetIconThrows({[type]: {"20.5": img}});
- assertSetIconThrows({[type]: {"5.0": img}});
- assertSetIconThrows({[type]: {"-300": img}});
- assertSetIconThrows({[type]: {"abc": img, "5": img}});
- }
-
- assertSetIconThrows({imageData: {"abcdef": imageData}, path: {"5": "test.png"}});
- assertSetIconThrows({path: {"abcdef": "test.png"}, imageData: {"5": imageData}});
- }
-
- Promise.all(promises).then(() => {
- browser.test.notifyPass("setIcon with invalid icon size");
- });
- });
- },
- });
-
- yield Promise.all([extension.startup(), extension.awaitFinish("setIcon with invalid icon size")]);
-
- yield extension.unload();
-});
-
-
-// Test that default icon details in the manifest.json file are handled
-// correctly.
-add_task(function* testDefaultDetails() {
- // TODO: Test localized variants.
- let icons = [
- "foo/bar.png",
- "/foo/bar.png",
- {"19": "foo/bar.png"},
- {"38": "foo/bar.png"},
- ];
-
- if (window.devicePixelRatio > 1) {
- icons.push({"19": "baz/quux.png", "38": "foo/bar.png"});
- } else {
- icons.push({"19": "foo/bar.png", "38": "baz/quux@2x.png"});
- }
-
- let expectedURL = new RegExp(String.raw`^moz-extension://[^/]+/foo/bar\.png$`);
-
- for (let icon of icons) {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {"default_icon": icon},
- "page_action": {"default_icon": icon},
- },
-
- background: function() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- let tabId = tabs[0].id;
-
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("ready");
- });
- });
- },
-
- files: {
- "foo/bar.png": imageBuffer,
- "baz/quux.png": imageBuffer,
- "baz/quux@2x.png": imageBuffer,
- },
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
-
- let browserActionId = makeWidgetId(extension.id) + "-browser-action";
- let pageActionId = makeWidgetId(extension.id) + "-page-action";
-
- let browserActionButton = document.getElementById(browserActionId);
- let image = getListStyleImage(browserActionButton);
-
- ok(expectedURL.test(image), `browser action image ${image} matches ${expectedURL}`);
-
- let pageActionImage = document.getElementById(pageActionId);
- image = getListStyleImage(pageActionImage);
-
- ok(expectedURL.test(image), `page action image ${image} matches ${expectedURL}`);
-
- yield extension.unload();
-
- let node = document.getElementById(pageActionId);
- is(node, null, "pageAction image removed from document");
- }
-});
-
-
-// Check that attempts to load a privileged URL as an icon image fail.
-add_task(function* testSecureURLsDenied() {
- // Test URLs passed to setIcon.
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {},
- "page_action": {},
- },
-
- background: function() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- let tabId = tabs[0].id;
-
- let urls = ["chrome://browser/content/browser.xul",
- "javascript:true"];
-
- let promises = [];
- for (let url of urls) {
- for (let api of ["pageAction", "browserAction"]) {
- promises.push(
- browser.test.assertRejects(
- browser[api].setIcon({tabId, path: url}),
- /Illegal URL/,
- `Load of '${url}' should fail.`));
- }
- }
-
- Promise.all(promises).then(() => {
- browser.test.notifyPass("setIcon security tests");
- });
- });
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("setIcon security tests");
- yield extension.unload();
-});
-
-
-add_task(function* testSecureManifestURLsDenied() {
- // Test URLs included in the manifest.
-
- let urls = ["chrome://browser/content/browser.xul",
- "javascript:true"];
-
- let apis = ["browser_action", "page_action"];
-
- for (let url of urls) {
- for (let api of apis) {
- info(`TEST ${api} icon url: ${url}`);
-
- let matchURLForbidden = url => ({
- message: new RegExp(`match the format "strictRelativeUrl"`),
- });
-
- let messages = [matchURLForbidden(url)];
-
- let waitForConsole = new Promise(resolve => {
- // Not necessary in browser-chrome tests, but monitorConsole gripes
- // if we don't call it.
- SimpleTest.waitForExplicitFinish();
-
- SimpleTest.monitorConsole(resolve, messages);
- });
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- [api]: {
- "default_icon": url,
- },
- },
- });
-
- yield Assert.rejects(extension.startup(),
- null,
- "Manifest rejected");
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
- }
- }
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js b/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js
deleted file mode 100644
index 9f04b3c11..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js
+++ /dev/null
@@ -1,413 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function getBrowserAction(extension) {
- const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let ext = GlobalManager.extensionMap.get(extension.id);
- return browserActionFor(ext);
-}
-
-let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>${url}</body></html>`;
-
-function* testInArea(area) {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "background": {
- "page": "data/background.html",
- },
- "browser_action": {
- "default_popup": "popup-a.html",
- "browser_style": true,
- },
- },
-
- files: {
- "popup-a.html": scriptPage("popup-a.js"),
- "popup-a.js": function() {
- window.onload = () => {
- let color = window.getComputedStyle(document.body).color;
- browser.test.assertEq("rgb(34, 36, 38)", color);
- browser.runtime.sendMessage("from-popup-a");
- };
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "close-popup-using-window.close") {
- window.close();
- }
- });
- },
-
- "data/popup-b.html": scriptPage("popup-b.js"),
- "data/popup-b.js": function() {
- window.onload = () => {
- browser.runtime.sendMessage("from-popup-b");
- };
- },
-
- "data/popup-c.html": scriptPage("popup-c.js"),
- "data/popup-c.js": function() {
- // Close the popup before the document is fully-loaded to make sure that
- // we handle this case sanely.
- browser.runtime.sendMessage("from-popup-c");
- window.close();
- },
-
- "data/background.html": scriptPage("background.js"),
-
- "data/background.js": function() {
- let sendClick;
- let tests = [
- () => {
- browser.test.log(`Click browser action, expect popup "a".`);
- sendClick({expectEvent: false, expectPopup: "a"});
- },
- () => {
- browser.test.log(`Click browser action again, expect popup "a".`);
- sendClick({expectEvent: false, expectPopup: "a"});
- },
- () => {
- browser.test.log(`Call triggerAction, expect popup "a" again. Leave popup open.`);
- sendClick({expectEvent: false, expectPopup: "a", closePopup: false}, "trigger-action");
- },
- () => {
- browser.test.log(`Call triggerAction again. Expect remaining popup closed.`);
- sendClick({expectEvent: false, expectPopup: null}, "trigger-action");
- browser.test.sendMessage("next-test", {waitUntilClosed: true});
- },
- () => {
- browser.test.log(`Call triggerAction again. Expect popup "a" again.`);
- sendClick({expectEvent: false, expectPopup: "a"}, "trigger-action");
- },
- () => {
- browser.test.log(`Set popup to "c" and click browser action. Expect popup "c".`);
- browser.browserAction.setPopup({popup: "popup-c.html"});
- sendClick({expectEvent: false, expectPopup: "c", closePopup: false});
- },
- () => {
- browser.test.log(`Set popup to "b" and click browser action. Expect popup "b".`);
- browser.browserAction.setPopup({popup: "popup-b.html"});
- sendClick({expectEvent: false, expectPopup: "b"});
- },
- () => {
- browser.test.log(`Click browser action again, expect popup "b".`);
- sendClick({expectEvent: false, expectPopup: "b"});
- },
- () => {
- browser.test.log(`Clear popup URL. Click browser action. Expect click event.`);
- browser.browserAction.setPopup({popup: ""});
- sendClick({expectEvent: true, expectPopup: null});
- },
- () => {
- browser.test.log(`Click browser action again. Expect another click event.`);
- sendClick({expectEvent: true, expectPopup: null});
- },
- () => {
- browser.test.log(`Call triggerAction. Expect click event.`);
- sendClick({expectEvent: true, expectPopup: null}, "trigger-action");
- },
- () => {
- browser.test.log(`Set popup to "a" and click browser action. Expect popup "a", and leave open.`);
- browser.browserAction.setPopup({popup: "/popup-a.html"});
- sendClick({expectEvent: false, expectPopup: "a", closePopup: false});
- },
- () => {
- browser.test.log(`Tell popup "a" to call window.close(). Expect popup closed.`);
- browser.test.sendMessage("next-test", {closePopupUsingWindow: true});
- },
- ];
-
- let expect = {};
- sendClick = ({expectEvent, expectPopup, runNextTest, waitUntilClosed, closePopup}, message = "send-click") => {
- if (closePopup == undefined) {
- closePopup = true;
- }
-
- expect = {event: expectEvent, popup: expectPopup, runNextTest, waitUntilClosed, closePopup};
- browser.test.sendMessage(message);
- };
-
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "close-popup-using-window.close") {
- return;
- } else if (expect.popup) {
- browser.test.assertEq(msg, `from-popup-${expect.popup}`,
- "expected popup opened");
- } else {
- browser.test.fail(`unexpected popup: ${msg}`);
- }
-
- expect.popup = null;
- browser.test.sendMessage("next-test", expect);
- });
-
- browser.browserAction.onClicked.addListener(() => {
- if (expect.event) {
- browser.test.succeed("expected click event received");
- } else {
- browser.test.fail("unexpected click event");
- }
-
- expect.event = false;
- browser.test.sendMessage("next-test", expect);
- });
-
- browser.test.onMessage.addListener((msg) => {
- if (msg == "close-popup-using-window.close") {
- browser.runtime.sendMessage("close-popup-using-window.close");
- return;
- }
-
- if (msg != "next-test") {
- browser.test.fail("Expecting 'next-test' message");
- }
-
- if (tests.length) {
- let test = tests.shift();
- test();
- } else {
- browser.test.notifyPass("browseraction-tests-done");
- }
- });
-
- browser.test.sendMessage("next-test");
- },
- },
- });
-
- extension.onMessage("send-click", () => {
- clickBrowserAction(extension);
- });
-
- extension.onMessage("trigger-action", () => {
- getBrowserAction(extension).triggerAction(window);
- });
-
- let widget;
- extension.onMessage("next-test", Task.async(function* (expecting = {}) {
- if (!widget) {
- widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, area);
- }
- if (expecting.waitUntilClosed) {
- let panel = getBrowserActionPopup(extension);
- if (panel && panel.state != "closed") {
- yield promisePopupHidden(panel);
- }
- } else if (expecting.closePopupUsingWindow) {
- let panel = getBrowserActionPopup(extension);
- ok(panel, "Expect panel to exist");
- yield promisePopupShown(panel);
-
- extension.sendMessage("close-popup-using-window.close");
-
- yield promisePopupHidden(panel);
- ok(true, "Panel is closed");
- } else if (expecting.closePopup) {
- yield closeBrowserAction(extension);
- }
-
- extension.sendMessage("next-test");
- }));
-
- yield Promise.all([extension.startup(), extension.awaitFinish("browseraction-tests-done")]);
-
- yield extension.unload();
-
- let view = document.getElementById(widget.viewId);
- is(view, null, "browserAction view removed from document");
-}
-
-add_task(function* testBrowserActionInToolbar() {
- yield testInArea(CustomizableUI.AREA_NAVBAR);
-});
-
-add_task(function* testBrowserActionInPanel() {
- yield testInArea(CustomizableUI.AREA_PANEL);
-});
-
-add_task(function* testBrowserActionClickCanceled() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- "permissions": ["activeTab"],
- },
-
- files: {
- "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head></html>`,
- },
- });
-
- yield extension.startup();
-
- const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let ext = GlobalManager.extensionMap.get(extension.id);
- let browserAction = browserActionFor(ext);
-
- let widget = getBrowserActionWidget(extension).forWindow(window);
- let tab = window.gBrowser.selectedTab;
-
- // Test canceled click.
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window);
-
- isnot(browserAction.pendingPopup, null, "Have pending popup");
- is(browserAction.pendingPopup.window, window, "Have pending popup for the correct window");
-
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- is(browserAction.tabToRevokeDuringClearPopup, tab, "Tab to revoke was saved");
- is(browserAction.tabManager.hasActiveTabPermission(tab), true, "Active tab was granted permission");
-
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mouseup", button: 0}, window);
-
- is(browserAction.pendingPopup, null, "Pending popup was cleared");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- is(browserAction.tabToRevokeDuringClearPopup, null, "Tab to revoke was removed");
- is(browserAction.tabManager.hasActiveTabPermission(tab), false, "Permission was revoked from tab");
-
- // Test completed click.
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window);
-
- isnot(browserAction.pendingPopup, null, "Have pending popup");
- is(browserAction.pendingPopup.window, window, "Have pending popup for the correct window");
-
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- // We need to do these tests during the mouseup event cycle, since the click
- // and command events will be dispatched immediately after mouseup, and void
- // the results.
- let mouseUpPromise = BrowserTestUtils.waitForEvent(widget.node, "mouseup", false, event => {
- isnot(browserAction.pendingPopup, null, "Pending popup was not cleared");
- isnot(browserAction.pendingPopupTimeout, null, "Have a pending popup timeout");
- return true;
- });
-
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, window);
-
- yield mouseUpPromise;
-
- is(browserAction.pendingPopup, null, "Pending popup was cleared");
- is(browserAction.pendingPopupTimeout, null, "Pending popup timeout was cleared");
-
- yield promisePopupShown(getBrowserActionPopup(extension));
- yield closeBrowserAction(extension);
-
- yield extension.unload();
-});
-
-add_task(function* testBrowserActionDisabled() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- },
-
- background() {
- browser.browserAction.disable();
- },
-
- files: {
- "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>`,
- "popup.js"() {
- browser.test.fail("Should not get here");
- },
- },
- });
-
- yield extension.startup();
-
- const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let ext = GlobalManager.extensionMap.get(extension.id);
- let browserAction = browserActionFor(ext);
-
- let widget = getBrowserActionWidget(extension).forWindow(window);
-
- // Test canceled click.
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window);
-
- is(browserAction.pendingPopup, null, "Have no pending popup");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mouseup", button: 0}, window);
-
- is(browserAction.pendingPopup, null, "Have no pending popup");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
-
- // Test completed click.
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window);
-
- is(browserAction.pendingPopup, null, "Have no pending popup");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- // We need to do these tests during the mouseup event cycle, since the click
- // and command events will be dispatched immediately after mouseup, and void
- // the results.
- let mouseUpPromise = BrowserTestUtils.waitForEvent(widget.node, "mouseup", false, event => {
- is(browserAction.pendingPopup, null, "Have no pending popup");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
- return true;
- });
-
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, window);
-
- yield mouseUpPromise;
-
- is(browserAction.pendingPopup, null, "Have no pending popup");
- is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout");
-
- // Give the popup a chance to load and trigger a failure, if it was
- // erroneously opened.
- yield new Promise(resolve => setTimeout(resolve, 250));
-
- yield extension.unload();
-});
-
-add_task(function* testBrowserActionTabPopulation() {
- // Note: This test relates to https://bugzilla.mozilla.org/show_bug.cgi?id=1310019
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- "permissions": ["activeTab"],
- },
-
- files: {
- "popup.html": scriptPage("popup.js"),
- "popup.js": function() {
- browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
- browser.test.assertEq("mochitest index /",
- tabs[0].title,
- "Tab has the expected title on first click");
- browser.test.sendMessage("tabTitle");
- });
- },
- },
- });
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
-
- yield extension.startup();
-
- let widget = getBrowserActionWidget(extension).forWindow(win);
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, win);
-
- yield extension.awaitMessage("tabTitle");
-
- EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, win);
-
- yield extension.unload();
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js b/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js
deleted file mode 100644
index 6c19b17f1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js
+++ /dev/null
@@ -1,304 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* openPanel(extension, win = window, awaitLoad = false) {
- clickBrowserAction(extension, win);
-
- return yield awaitExtensionPanel(extension, win, awaitLoad);
-}
-
-add_task(function* testBrowserActionPopupResize() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- },
-
- files: {
- "popup.html": '<!DOCTYPE html><html><head><meta charset="utf-8"></head></html>',
- },
- });
-
- yield extension.startup();
-
- let browser = yield openPanel(extension);
-
- function* checkSize(expected) {
- let dims = yield promiseContentDimensions(browser);
-
- is(dims.window.innerHeight, expected, `Panel window should be ${expected}px tall`);
- is(dims.body.clientHeight, dims.body.scrollHeight,
- "Panel body should be tall enough to fit its contents");
-
- // Tolerate if it is 1px too wide, as that may happen with the current resizing method.
- ok(Math.abs(dims.window.innerWidth - expected) <= 1, `Panel window should be ${expected}px wide`);
- is(dims.body.clientWidth, dims.body.scrollWidth,
- "Panel body should be wide enough to fit its contents");
- }
-
- /* eslint-disable mozilla/no-cpows-in-tests */
- function setSize(size) {
- content.document.body.style.height = `${size}px`;
- content.document.body.style.width = `${size}px`;
- }
- /* eslint-enable mozilla/no-cpows-in-tests */
-
- let sizes = [
- 200,
- 400,
- 300,
- ];
-
- for (let size of sizes) {
- yield alterContent(browser, setSize, size);
- yield checkSize(size);
- }
-
- yield closeBrowserAction(extension);
- yield extension.unload();
-});
-
-function* testPopupSize(standardsMode, browserWin = window, arrowSide = "top") {
- let docType = standardsMode ? "<!DOCTYPE html>" : "";
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
- },
-
- files: {
- "popup.html": `${docType}
- <html>
- <head>
- <meta charset="utf-8">
- <style type="text/css">
- body > span {
- display: inline-block;
- width: 10px;
- height: 150px;
- border: 2px solid black;
- }
- .big > span {
- width: 300px;
- height: 100px;
- }
- .bigger > span {
- width: 150px;
- height: 150px;
- }
- .huge > span {
- height: ${2 * screen.height}px;
- }
- </style>
- </head>
- <body>
- <span></span>
- <span></span>
- <span></span>
- <span></span>
- </body>
- </html>`,
- },
- });
-
- yield extension.startup();
-
- /* eslint-disable mozilla/no-cpows-in-tests */
-
- if (arrowSide == "top") {
- // Test the standalone panel for a toolbar button.
- let browser = yield openPanel(extension, browserWin, true);
-
- let dims = yield promiseContentDimensions(browser);
-
- is(dims.isStandards, standardsMode, "Document has the expected compat mode");
-
- let {innerWidth, innerHeight} = dims.window;
-
- dims = yield alterContent(browser, () => {
- content.document.body.classList.add("bigger");
- });
-
- let win = dims.window;
- is(win.innerHeight, innerHeight, "Window height should not change");
- ok(win.innerWidth > innerWidth, `Window width should increase (${win.innerWidth} > ${innerWidth})`);
-
-
- dims = yield alterContent(browser, () => {
- content.document.body.classList.remove("bigger");
- });
-
- win = dims.window;
- is(win.innerHeight, innerHeight, "Window height should not change");
-
- // The getContentSize calculation is not always reliable to single-pixel
- // precision.
- ok(Math.abs(win.innerWidth - innerWidth) <= 1,
- `Window width should return to approximately its original value (${win.innerWidth} ~= ${innerWidth})`);
-
- yield closeBrowserAction(extension, browserWin);
- }
-
-
- // Test the PanelUI panel for a menu panel button.
- let widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL);
-
- let browser = yield openPanel(extension, browserWin);
-
- let {panel} = browserWin.PanelUI;
- let origPanelRect = panel.getBoundingClientRect();
-
- // Check that the panel is still positioned as expected.
- let checkPanelPosition = () => {
- is(panel.getAttribute("side"), arrowSide, "Panel arrow is positioned as expected");
-
- let panelRect = panel.getBoundingClientRect();
- if (arrowSide == "top") {
- ok(panelRect.top, origPanelRect.top, "Panel has not moved downwards");
- ok(panelRect.bottom >= origPanelRect.bottom, `Panel has not shrunk from original size (${panelRect.bottom} >= ${origPanelRect.bottom})`);
-
- let screenBottom = browserWin.screen.availTop + browserWin.screen.availHeight;
- let panelBottom = browserWin.mozInnerScreenY + panelRect.bottom;
- ok(panelBottom <= screenBottom, `Bottom of popup should be on-screen. (${panelBottom} <= ${screenBottom})`);
- } else {
- ok(panelRect.bottom, origPanelRect.bottom, "Panel has not moved upwards");
- ok(panelRect.top <= origPanelRect.top, `Panel has not shrunk from original size (${panelRect.top} <= ${origPanelRect.top})`);
-
- let panelTop = browserWin.mozInnerScreenY + panelRect.top;
- ok(panelTop >= browserWin.screen.availTop, `Top of popup should be on-screen. (${panelTop} >= ${browserWin.screen.availTop})`);
- }
- };
-
- yield awaitBrowserLoaded(browser);
-
- // Wait long enough to make sure the initial resize debouncing timer has
- // expired.
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- let dims = yield promiseContentDimensions(browser);
-
- is(dims.isStandards, standardsMode, "Document has the expected compat mode");
-
- // If the browser's preferred height is smaller than the initial height of the
- // panel, then it will still take up the full available vertical space. Even
- // so, we need to check that we've gotten the preferred height calculation
- // correct, so check that explicitly.
- let getHeight = () => parseFloat(browser.style.height);
-
- let {innerWidth, innerHeight} = dims.window;
- let height = getHeight();
-
-
- let setClass = className => {
- content.document.body.className = className;
- };
-
- info("Increase body children's width. " +
- "Expect them to wrap, and the frame to grow vertically rather than widen.");
-
- dims = yield alterContent(browser, setClass, "big");
- let win = dims.window;
-
- ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`);
-
- is(win.innerWidth, innerWidth, "Window width should not change");
- ok(win.innerHeight >= innerHeight, `Window height should increase (${win.innerHeight} >= ${innerHeight})`);
- is(win.scrollMaxY, 0, "Document should not be vertically scrollable");
-
- checkPanelPosition();
-
-
- info("Increase body children's width and height. " +
- "Expect them to wrap, and the frame to grow vertically rather than widen.");
-
- dims = yield alterContent(browser, setClass, "bigger");
- win = dims.window;
-
- ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`);
-
- is(win.innerWidth, innerWidth, "Window width should not change");
- ok(win.innerHeight >= innerHeight, `Window height should increase (${win.innerHeight} >= ${innerHeight})`);
- is(win.scrollMaxY, 0, "Document should not be vertically scrollable");
-
- checkPanelPosition();
-
-
- info("Increase body height beyond the height of the screen. " +
- "Expect the panel to grow to accommodate, but not larger than the height of the screen.");
-
- dims = yield alterContent(browser, setClass, "huge");
- win = dims.window;
-
- ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`);
-
- is(win.innerWidth, innerWidth, "Window width should not change");
- ok(win.innerHeight > innerHeight, `Window height should increase (${win.innerHeight} > ${innerHeight})`);
- ok(win.innerHeight < screen.height, `Window height be less than the screen height (${win.innerHeight} < ${screen.height})`);
- ok(win.scrollMaxY > 0, `Document should be vertically scrollable (${win.scrollMaxY} > 0)`);
-
- checkPanelPosition();
-
-
- info("Restore original styling. Expect original dimensions.");
- dims = yield alterContent(browser, setClass, "");
- win = dims.window;
-
- is(getHeight(), height, "Browser height should return to its original value");
-
- is(win.innerWidth, innerWidth, "Window width should not change");
- is(win.innerHeight, innerHeight, "Window height should return to its original value");
- is(win.scrollMaxY, 0, "Document should not be vertically scrollable");
-
- checkPanelPosition();
-
- yield closeBrowserAction(extension, browserWin);
-
- yield extension.unload();
-}
-
-add_task(function* testBrowserActionMenuResizeStandards() {
- yield testPopupSize(true);
-});
-
-add_task(function* testBrowserActionMenuResizeQuirks() {
- yield testPopupSize(false);
-});
-
-// Test that we still make reasonable maximum size calculations when the window
-// is close enough to the bottom of the screen that the menu panel opens above,
-// rather than below, its button.
-add_task(function* testBrowserActionMenuResizeBottomArrow() {
- const WIDTH = 800;
- const HEIGHT = 300;
-
- let left = screen.availLeft + screen.availWidth - WIDTH;
- let top = screen.availTop + screen.availHeight - HEIGHT;
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
-
- win.resizeTo(WIDTH, HEIGHT);
-
- // Sometimes we run into problems on Linux with resizing being asynchronous
- // and window managers not allowing us to move the window so that any part of
- // it is off-screen, so we need to try more than once.
- for (let i = 0; i < 20; i++) {
- win.moveTo(left, top);
-
- if (win.screenX == left && win.screenY == top) {
- break;
- }
-
- yield new Promise(resolve => setTimeout(resolve, 100));
- }
-
- yield testPopupSize(true, win, "bottom");
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js b/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js
deleted file mode 100644
index e83010958..000000000
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "unrecognized_property": "with-a-random-value",
- },
- },
-
- files: {
- "popup.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="popup.js"></script>
- </body></html>
- `,
-
- "popup.js": function() {
- window.onload = () => {
- browser.runtime.sendMessage("from-popup");
- };
- },
- },
-
- background: function() {
- browser.runtime.onMessage.addListener(msg => {
- browser.test.assertEq(msg, "from-popup", "correct message received");
- browser.test.sendMessage("popup");
- });
- },
- });
-
- SimpleTest.waitForExplicitFinish();
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{
- message: /Reading manifest: Error processing browser_action.unrecognized_property: An unexpected property was found/,
- }]);
- });
-
- yield extension.startup();
-
- // Do this a few times to make sure the pop-up is reloaded each time.
- for (let i = 0; i < 3; i++) {
- clickBrowserAction(extension);
-
- yield extension.awaitMessage("popup");
-
- closeBrowserAction(extension);
- }
-
- yield extension.unload();
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js b/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js
deleted file mode 100644
index f97a735d4..000000000
--- a/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* testExecuteBrowserActionWithOptions(options = {}) {
- let extensionOptions = {};
-
- extensionOptions.manifest = {
- "commands": {
- "_execute_browser_action": {
- "suggested_key": {
- "default": "Alt+Shift+J",
- },
- },
- },
- "browser_action": {
- "browser_style": true,
- },
- };
-
- if (options.withPopup) {
- extensionOptions.manifest.browser_action.default_popup = "popup.html";
-
- extensionOptions.files = {
- "popup.html": `
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script src="popup.js"></script>
- </head>
- </html>
- `,
-
- "popup.js": function() {
- browser.runtime.sendMessage("from-browser-action-popup");
- },
- };
- }
-
- extensionOptions.background = () => {
- browser.test.onMessage.addListener((message, withPopup) => {
- browser.commands.onCommand.addListener((commandName) => {
- if (commandName == "_execute_browser_action") {
- browser.test.fail("The onCommand listener should never fire for _execute_browser_action.");
- }
- });
-
- browser.browserAction.onClicked.addListener(() => {
- if (withPopup) {
- browser.test.fail("The onClick listener should never fire if the browserAction has a popup.");
- browser.test.notifyFail("execute-browser-action-on-clicked-fired");
- } else {
- browser.test.notifyPass("execute-browser-action-on-clicked-fired");
- }
- });
-
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "from-browser-action-popup") {
- browser.test.notifyPass("execute-browser-action-popup-opened");
- }
- });
-
- browser.test.sendMessage("send-keys");
- });
- };
-
- let extension = ExtensionTestUtils.loadExtension(extensionOptions);
-
- extension.onMessage("send-keys", () => {
- EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true});
- });
-
- yield extension.startup();
-
- if (options.inArea) {
- let widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, options.inArea);
- }
-
- extension.sendMessage("withPopup", options.withPopup);
-
- if (options.withPopup) {
- yield extension.awaitFinish("execute-browser-action-popup-opened");
- yield closeBrowserAction(extension);
- } else {
- yield extension.awaitFinish("execute-browser-action-on-clicked-fired");
- }
- yield extension.unload();
-}
-
-add_task(function* test_execute_browser_action_with_popup() {
- yield testExecuteBrowserActionWithOptions({
- withPopup: true,
- });
-});
-
-add_task(function* test_execute_browser_action_without_popup() {
- yield testExecuteBrowserActionWithOptions();
-});
-
-add_task(function* test_execute_browser_action_in_hamburger_menu_with_popup() {
- yield testExecuteBrowserActionWithOptions({
- withPopup: true,
- inArea: CustomizableUI.AREA_PANEL,
- });
-});
-
-add_task(function* test_execute_browser_action_in_hamburger_menu_without_popup() {
- yield testExecuteBrowserActionWithOptions({
- inArea: CustomizableUI.AREA_PANEL,
- });
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js b/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js
deleted file mode 100644
index 83684493e..000000000
--- a/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* test_execute_page_action_without_popup() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "commands": {
- "_execute_page_action": {
- "suggested_key": {
- "default": "Alt+Shift+J",
- },
- },
- "send-keys-command": {
- "suggested_key": {
- "default": "Alt+Shift+3",
- },
- },
- },
- "page_action": {},
- },
-
- background: function() {
- let isShown = false;
-
- browser.commands.onCommand.addListener((commandName) => {
- if (commandName == "_execute_page_action") {
- browser.test.fail(`The onCommand listener should never fire for ${commandName}.`);
- } else if (commandName == "send-keys-command") {
- if (!isShown) {
- isShown = true;
- browser.tabs.query({currentWindow: true, active: true}, tabs => {
- tabs.forEach(tab => {
- browser.pageAction.show(tab.id);
- });
- browser.test.sendMessage("send-keys");
- });
- }
- }
- });
-
- browser.pageAction.onClicked.addListener(() => {
- browser.test.assertTrue(isShown, "The onClicked event should fire if the page action is shown.");
- browser.test.notifyPass("page-action-without-popup");
- });
-
- browser.test.sendMessage("send-keys");
- },
- });
-
- extension.onMessage("send-keys", () => {
- EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true});
- EventUtils.synthesizeKey("3", {altKey: true, shiftKey: true});
- });
-
- yield extension.startup();
- yield extension.awaitFinish("page-action-without-popup");
- yield extension.unload();
-});
-
-add_task(function* test_execute_page_action_with_popup() {
- let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>Test Popup</body></html>`;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "commands": {
- "_execute_page_action": {
- "suggested_key": {
- "default": "Alt+Shift+J",
- },
- },
- "send-keys-command": {
- "suggested_key": {
- "default": "Alt+Shift+3",
- },
- },
- },
- "page_action": {
- "default_popup": "popup.html",
- },
- },
-
- files: {
- "popup.html": scriptPage("popup.js"),
- "popup.js": function() {
- browser.runtime.sendMessage("popup-opened");
- },
- },
-
- background: function() {
- let isShown = false;
-
- browser.commands.onCommand.addListener((message) => {
- if (message == "_execute_page_action") {
- browser.test.fail(`The onCommand listener should never fire for ${message}.`);
- }
-
- if (message == "send-keys-command") {
- if (!isShown) {
- isShown = true;
- browser.tabs.query({currentWindow: true, active: true}, tabs => {
- tabs.forEach(tab => {
- browser.pageAction.show(tab.id);
- });
- browser.test.sendMessage("send-keys");
- });
- }
- }
- });
-
- browser.pageAction.onClicked.addListener(() => {
- browser.test.fail(`The onClicked listener should never fire when the pageAction has a popup.`);
- });
-
- browser.runtime.onMessage.addListener(msg => {
- browser.test.assertEq(msg, "popup-opened", "expected popup opened");
- browser.test.assertTrue(isShown, "The onClicked event should fire if the page action is shown.");
- browser.test.notifyPass("page-action-with-popup");
- });
-
- browser.test.sendMessage("send-keys");
- },
- });
-
- extension.onMessage("send-keys", () => {
- EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true});
- EventUtils.synthesizeKey("3", {altKey: true, shiftKey: true});
- });
-
- yield extension.startup();
- yield extension.awaitFinish("page-action-with-popup");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_commands_getAll.js b/browser/components/extensions/test/browser/browser_ext_commands_getAll.js
deleted file mode 100644
index 5885e8aee..000000000
--- a/browser/components/extensions/test/browser/browser_ext_commands_getAll.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-var {AppConstants} = Cu.import("resource://gre/modules/AppConstants.jsm");
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "name": "Commands Extension",
- "commands": {
- "with-desciption": {
- "suggested_key": {
- "default": "Ctrl+Shift+Y",
- },
- "description": "should have a description",
- },
- "without-description": {
- "suggested_key": {
- "default": "Ctrl+Shift+D",
- },
- },
- "with-platform-info": {
- "suggested_key": {
- "mac": "Ctrl+Shift+M",
- "linux": "Ctrl+Shift+L",
- "windows": "Ctrl+Shift+W",
- "android": "Ctrl+Shift+A",
- },
- },
- },
- },
-
- background: function() {
- browser.test.onMessage.addListener((message, additionalScope) => {
- browser.commands.getAll((commands) => {
- let errorMessage = "getAll should return an array of commands";
- browser.test.assertEq(commands.length, 3, errorMessage);
-
- let command = commands.find(c => c.name == "with-desciption");
-
- errorMessage = "The description should match what is provided in the manifest";
- browser.test.assertEq("should have a description", command.description, errorMessage);
-
- errorMessage = "The shortcut should match the default shortcut provided in the manifest";
- browser.test.assertEq("Ctrl+Shift+Y", command.shortcut, errorMessage);
-
- command = commands.find(c => c.name == "without-description");
-
- errorMessage = "The description should be empty when it is not provided";
- browser.test.assertEq(null, command.description, errorMessage);
-
- errorMessage = "The shortcut should match the default shortcut provided in the manifest";
- browser.test.assertEq("Ctrl+Shift+D", command.shortcut, errorMessage);
-
- let platformKeys = {
- macosx: "M",
- linux: "L",
- win: "W",
- android: "A",
- };
-
- command = commands.find(c => c.name == "with-platform-info");
- let platformKey = platformKeys[additionalScope.platform];
- let shortcut = `Ctrl+Shift+${platformKey}`;
- errorMessage = `The shortcut should match the one provided in the manifest for OS='${additionalScope.platform}'`;
- browser.test.assertEq(shortcut, command.shortcut, errorMessage);
-
- browser.test.notifyPass("commands");
- });
- });
- browser.test.sendMessage("ready");
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
- extension.sendMessage("additional-scope", {platform: AppConstants.platform});
- yield extension.awaitFinish("commands");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js b/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js
deleted file mode 100644
index dd959dcec..000000000
--- a/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js
+++ /dev/null
@@ -1,229 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-Cu.import("resource://gre/modules/AppConstants.jsm");
-
-add_task(function* test_user_defined_commands() {
- const testCommands = [
- // Ctrl Shortcuts
- {
- name: "toggle-ctrl-a",
- shortcut: "Ctrl+A",
- key: "A",
- modifiers: {
- accelKey: true,
- },
- },
- {
- name: "toggle-ctrl-up",
- shortcut: "Ctrl+Up",
- key: "VK_UP",
- modifiers: {
- accelKey: true,
- },
- },
- // Alt Shortcuts
- {
- name: "toggle-alt-a",
- shortcut: "Alt+A",
- key: "A",
- modifiers: {
- altKey: true,
- },
- },
- {
- name: "toggle-alt-down",
- shortcut: "Alt+Down",
- key: "VK_DOWN",
- modifiers: {
- altKey: true,
- },
- },
- // Mac Shortcuts
- {
- name: "toggle-command-shift-page-up",
- shortcutMac: "Command+Shift+PageUp",
- key: "VK_PAGE_UP",
- modifiers: {
- accelKey: true,
- shiftKey: true,
- },
- },
- {
- name: "toggle-mac-control-shift+period",
- shortcut: "Ctrl+Shift+Period",
- shortcutMac: "MacCtrl+Shift+Period",
- key: "VK_PERIOD",
- modifiers: {
- ctrlKey: true,
- shiftKey: true,
- },
- },
- // Ctrl+Shift Shortcuts
- {
- name: "toggle-ctrl-shift-left",
- shortcut: "Ctrl+Shift+Left",
- key: "VK_LEFT",
- modifiers: {
- accelKey: true,
- shiftKey: true,
- },
- },
- // Alt+Shift Shortcuts
- {
- name: "toggle-alt-shift-1",
- shortcut: "Alt+Shift+1",
- key: "1",
- modifiers: {
- altKey: true,
- shiftKey: true,
- },
- },
- {
- name: "toggle-alt-shift-a",
- shortcut: "Alt+Shift+A",
- key: "A",
- modifiers: {
- altKey: true,
- shiftKey: true,
- },
- },
- {
- name: "toggle-alt-shift-right",
- shortcut: "Alt+Shift+Right",
- key: "VK_RIGHT",
- modifiers: {
- altKey: true,
- shiftKey: true,
- },
- },
- // Misc Shortcuts
- {
- name: "valid-command-with-unrecognized-property-name",
- shortcut: "Alt+Shift+3",
- key: "3",
- modifiers: {
- altKey: true,
- shiftKey: true,
- },
- unrecognized_property: "with-a-random-value",
- },
- {
- name: "spaces-in-shortcut-name",
- shortcut: " Alt + Shift + 2 ",
- key: "2",
- modifiers: {
- altKey: true,
- shiftKey: true,
- },
- },
- ];
-
- // Create a window before the extension is loaded.
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(win1.gBrowser.selectedBrowser, "about:robots");
- yield BrowserTestUtils.browserLoaded(win1.gBrowser.selectedBrowser);
-
- let commands = {};
- let isMac = AppConstants.platform == "macosx";
- let totalMacOnlyCommands = 0;
-
- for (let testCommand of testCommands) {
- let command = {
- suggested_key: {},
- };
-
- if (testCommand.shortcut) {
- command.suggested_key.default = testCommand.shortcut;
- }
-
- if (testCommand.shortcutMac) {
- command.suggested_key.mac = testCommand.shortcutMac;
- }
-
- if (testCommand.shortcutMac && !testCommand.shortcut) {
- totalMacOnlyCommands++;
- }
-
- if (testCommand.unrecognized_property) {
- command.unrecognized_property = testCommand.unrecognized_property;
- }
-
- commands[testCommand.name] = command;
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "commands": commands,
- },
-
- background: function() {
- browser.commands.onCommand.addListener(commandName => {
- browser.test.sendMessage("oncommand", commandName);
- });
- browser.test.sendMessage("ready");
- },
- });
-
- SimpleTest.waitForExplicitFinish();
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{
- message: /Reading manifest: Error processing commands.*.unrecognized_property: An unexpected property was found/,
- }]);
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- function* runTest(window) {
- for (let testCommand of testCommands) {
- if (testCommand.shortcutMac && !testCommand.shortcut && !isMac) {
- continue;
- }
- EventUtils.synthesizeKey(testCommand.key, testCommand.modifiers, window);
- let message = yield extension.awaitMessage("oncommand");
- is(message, testCommand.name, `Expected onCommand listener to fire with the correct name: ${testCommand.name}`);
- }
- }
-
- // Create another window after the extension is loaded.
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(win2.gBrowser.selectedBrowser, "about:robots");
- yield BrowserTestUtils.browserLoaded(win2.gBrowser.selectedBrowser);
-
- let totalTestCommands = Object.keys(testCommands).length;
- let expectedCommandsRegistered = isMac ? totalTestCommands : totalTestCommands - totalMacOnlyCommands;
-
- // Confirm the keysets have been added to both windows.
- let keysetID = `ext-keyset-id-${makeWidgetId(extension.id)}`;
- let keyset = win1.document.getElementById(keysetID);
- ok(keyset != null, "Expected keyset to exist");
- is(keyset.childNodes.length, expectedCommandsRegistered, "Expected keyset to have the correct number of children");
-
- keyset = win2.document.getElementById(keysetID);
- ok(keyset != null, "Expected keyset to exist");
- is(keyset.childNodes.length, expectedCommandsRegistered, "Expected keyset to have the correct number of children");
-
- // Confirm that the commands are registered to both windows.
- yield focusWindow(win1);
- yield runTest(win1);
-
- yield focusWindow(win2);
- yield runTest(win2);
-
- yield extension.unload();
-
- // Confirm that the keysets have been removed from both windows after the extension is unloaded.
- keyset = win1.document.getElementById(keysetID);
- is(keyset, null, "Expected keyset to be removed from the window");
-
- keyset = win2.document.getElementById(keysetID);
- is(keyset, null, "Expected keyset to be removed from the window");
-
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js b/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js
deleted file mode 100644
index 8b2d9badf..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/"],
- },
-
- background: function() {
- let ports_received = 0;
- let port_messages_received = 0;
-
- browser.runtime.onConnect.addListener((port) => {
- browser.test.assertTrue(!!port, "port1 received");
-
- ports_received++;
- browser.test.assertEq(1, ports_received, "1 port received");
-
- port.onMessage.addListener((msg, msgPort) => {
- browser.test.assertEq("port message", msg, "listener1 port message received");
- browser.test.assertEq(port, msgPort, "onMessage should receive port as second argument");
-
- port_messages_received++;
- browser.test.assertEq(1, port_messages_received, "1 port message received");
- });
- });
- browser.runtime.onConnect.addListener((port) => {
- browser.test.assertTrue(!!port, "port2 received");
-
- ports_received++;
- browser.test.assertEq(2, ports_received, "2 ports received");
-
- port.onMessage.addListener((msg, msgPort) => {
- browser.test.assertEq("port message", msg, "listener2 port message received");
- browser.test.assertEq(port, msgPort, "onMessage should receive port as second argument");
-
- port_messages_received++;
- browser.test.assertEq(2, port_messages_received, "2 port messages received");
-
- browser.test.notifyPass("contentscript_connect.pass");
- });
- });
-
- browser.tabs.executeScript({file: "script.js"}).catch(e => {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("contentscript_connect.pass");
- });
- },
-
- files: {
- "script.js": function() {
- let port = browser.runtime.connect();
- port.postMessage("port message");
- },
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contentscript_connect.pass");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus.js b/browser/components/extensions/test/browser/browser_ext_contextMenus.js
deleted file mode 100644
index fa1483b20..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus.js
+++ /dev/null
@@ -1,342 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-const PAGE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE);
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: function() {
- browser.contextMenus.create({
- id: "clickme-image",
- title: "Click me!",
- contexts: ["image"],
- });
- browser.contextMenus.create({
- id: "clickme-page",
- title: "Click me!",
- contexts: ["page"],
- });
- browser.test.notifyPass();
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish();
-
- let contentAreaContextMenu = yield openContextMenu("#img1");
- let item = contentAreaContextMenu.getElementsByAttribute("label", "Click me!");
- is(item.length, 1, "contextMenu item for image was found");
- yield closeContextMenu();
-
- contentAreaContextMenu = yield openContextMenu("body");
- item = contentAreaContextMenu.getElementsByAttribute("label", "Click me!");
- is(item.length, 1, "contextMenu item for page was found");
- yield closeContextMenu();
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
-});
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE);
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: async function() {
- // A generic onclick callback function.
- function genericOnClick(info, tab) {
- browser.test.sendMessage("onclick", {info, tab});
- }
-
- browser.contextMenus.onClicked.addListener((info, tab) => {
- browser.test.sendMessage("browser.contextMenus.onClicked", {info, tab});
- });
-
- browser.contextMenus.create({
- contexts: ["all"],
- type: "separator",
- });
-
- let contexts = ["page", "selection", "image", "editable"];
- for (let i = 0; i < contexts.length; i++) {
- let context = contexts[i];
- let title = context;
- browser.contextMenus.create({
- title: title,
- contexts: [context],
- id: "ext-" + context,
- onclick: genericOnClick,
- });
- if (context == "selection") {
- browser.contextMenus.update("ext-selection", {
- title: "selection is: '%s'",
- onclick: (info, tab) => {
- browser.contextMenus.removeAll();
- genericOnClick(info, tab);
- },
- });
- }
- }
-
- let parent = browser.contextMenus.create({
- title: "parent",
- });
- browser.contextMenus.create({
- title: "child1",
- parentId: parent,
- onclick: genericOnClick,
- });
- let child2 = browser.contextMenus.create({
- title: "child2",
- parentId: parent,
- onclick: genericOnClick,
- });
-
- let parentToDel = browser.contextMenus.create({
- title: "parentToDel",
- });
- browser.contextMenus.create({
- title: "child1",
- parentId: parentToDel,
- onclick: genericOnClick,
- });
- browser.contextMenus.create({
- title: "child2",
- parentId: parentToDel,
- onclick: genericOnClick,
- });
- browser.contextMenus.remove(parentToDel);
-
- browser.contextMenus.create({
- title: "Without onclick property",
- id: "ext-without-onclick",
- });
-
- await browser.test.assertRejects(
- browser.contextMenus.update(parent, {parentId: child2}),
- /cannot be an ancestor/,
- "Should not be able to reparent an item as descendent of itself");
-
- browser.test.notifyPass("contextmenus");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus");
-
- let expectedClickInfo = {
- menuItemId: "ext-image",
- mediaType: "image",
- srcUrl: "http://mochi.test:8888/browser/browser/components/extensions/test/browser/ctxmenu-image.png",
- pageUrl: PAGE,
- editable: false,
- };
-
- function checkClickInfo(result) {
- for (let i of Object.keys(expectedClickInfo)) {
- is(result.info[i], expectedClickInfo[i],
- "click info " + i + " expected to be: " + expectedClickInfo[i] + " but was: " + result.info[i]);
- }
- is(expectedClickInfo.pageSrc, result.tab.url, "click info page source is the right tab");
- }
-
- let extensionMenuRoot = yield openExtensionContextMenu();
-
- // Check some menu items
- let items = extensionMenuRoot.getElementsByAttribute("label", "image");
- is(items.length, 1, "contextMenu item for image was found (context=image)");
- let image = items[0];
-
- items = extensionMenuRoot.getElementsByAttribute("label", "selection-edited");
- is(items.length, 0, "contextMenu item for selection was not found (context=image)");
-
- items = extensionMenuRoot.getElementsByAttribute("label", "parentToDel");
- is(items.length, 0, "contextMenu item for removed parent was not found (context=image)");
-
- items = extensionMenuRoot.getElementsByAttribute("label", "parent");
- is(items.length, 1, "contextMenu item for parent was found (context=image)");
-
- is(items[0].childNodes[0].childNodes.length, 2, "child items for parent were found (context=image)");
-
- // Click on ext-image item and check the click results
- yield closeExtensionContextMenu(image);
-
- let result = yield extension.awaitMessage("onclick");
- checkClickInfo(result);
- result = yield extension.awaitMessage("browser.contextMenus.onClicked");
- checkClickInfo(result);
-
-
- // Test "editable" context and OnClick data property.
- extensionMenuRoot = yield openExtensionContextMenu("#edit-me");
-
- // Check some menu items.
- items = extensionMenuRoot.getElementsByAttribute("label", "editable");
- is(items.length, 1, "contextMenu item for text input element was found (context=editable)");
- let editable = items[0];
-
- // Click on ext-editable item and check the click results.
- yield closeExtensionContextMenu(editable);
-
- expectedClickInfo = {
- menuItemId: "ext-editable",
- pageUrl: PAGE,
- editable: true,
- };
-
- result = yield extension.awaitMessage("onclick");
- checkClickInfo(result);
- result = yield extension.awaitMessage("browser.contextMenus.onClicked");
- checkClickInfo(result);
-
-
- // Select some text
- yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) {
- let doc = content.document;
- let range = doc.createRange();
- let selection = content.getSelection();
- selection.removeAllRanges();
- let textNode = doc.getElementById("img1").previousSibling;
- range.setStart(textNode, 0);
- range.setEnd(textNode, 100);
- selection.addRange(range);
- });
-
- // Bring up context menu again
- extensionMenuRoot = yield openExtensionContextMenu();
-
- // Check some menu items
- items = extensionMenuRoot.getElementsByAttribute("label", "Without onclick property");
- is(items.length, 1, "contextMenu item was found (context=page)");
-
- yield closeExtensionContextMenu(items[0]);
-
- expectedClickInfo = {
- menuItemId: "ext-without-onclick",
- pageUrl: PAGE,
- };
-
- result = yield extension.awaitMessage("browser.contextMenus.onClicked");
- checkClickInfo(result);
-
- // Bring up context menu again
- extensionMenuRoot = yield openExtensionContextMenu();
-
- // Check some menu items
- items = extensionMenuRoot.getElementsByAttribute("label", "selection is: 'just some text 123456789012345678901234567890...'");
- is(items.length, 1, "contextMenu item for selection was found (context=selection)");
- let selectionItem = items[0];
-
- items = extensionMenuRoot.getElementsByAttribute("label", "selection");
- is(items.length, 0, "contextMenu item label update worked (context=selection)");
-
- yield closeExtensionContextMenu(selectionItem);
-
- expectedClickInfo = {
- menuItemId: "ext-selection",
- pageUrl: PAGE,
- selectionText: "just some text 1234567890123456789012345678901234567890123456789012345678901234567890123456789012",
- };
-
- result = yield extension.awaitMessage("onclick");
- checkClickInfo(result);
- result = yield extension.awaitMessage("browser.contextMenus.onClicked");
- checkClickInfo(result);
-
- let contentAreaContextMenu = yield openContextMenu("#img1");
- items = contentAreaContextMenu.getElementsByAttribute("ext-type", "top-level-menu");
- is(items.length, 0, "top level item was not found (after removeAll()");
- yield closeContextMenu();
-
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
-
-add_task(function* testRemoveAllWithTwoExtensions() {
- const tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE);
- const manifest = {permissions: ["contextMenus"]};
-
- const first = ExtensionTestUtils.loadExtension({manifest, background() {
- browser.contextMenus.create({title: "alpha", contexts: ["all"]});
-
- browser.contextMenus.onClicked.addListener(() => {
- browser.contextMenus.removeAll();
- });
- browser.test.onMessage.addListener(msg => {
- if (msg == "ping") {
- browser.test.sendMessage("pong-alpha");
- return;
- }
- browser.contextMenus.create({title: "gamma", contexts: ["all"]});
- });
- }});
-
- const second = ExtensionTestUtils.loadExtension({manifest, background() {
- browser.contextMenus.create({title: "beta", contexts: ["all"]});
-
- browser.contextMenus.onClicked.addListener(() => {
- browser.contextMenus.removeAll();
- });
-
- browser.test.onMessage.addListener(() => {
- browser.test.sendMessage("pong-beta");
- });
- }});
-
- yield first.startup();
- yield second.startup();
-
- function* confirmMenuItems(...items) {
- // Round-trip to extension to make sure that the context menu state has been
- // updated by the async contextMenus.create / contextMenus.removeAll calls.
- first.sendMessage("ping");
- second.sendMessage("ping");
- yield first.awaitMessage("pong-alpha");
- yield second.awaitMessage("pong-beta");
-
- const menu = yield openContextMenu();
- for (const id of ["alpha", "beta", "gamma"]) {
- const expected = items.includes(id);
- const found = menu.getElementsByAttribute("label", id);
- is(found.length, expected, `menu item ${id} ${expected ? "" : "not "}found`);
- }
- // Return the first menu item, we need to click it.
- return menu.getElementsByAttribute("label", items[0])[0];
- }
-
- // Confirm alpha, beta exist; click alpha to remove it.
- const alpha = yield confirmMenuItems("alpha", "beta");
- yield closeExtensionContextMenu(alpha);
-
- // Confirm only beta exists.
- yield confirmMenuItems("beta");
- yield closeContextMenu();
-
- // Create gamma, confirm, click.
- first.sendMessage("create");
- const beta = yield confirmMenuItems("beta", "gamma");
- yield closeExtensionContextMenu(beta);
-
- // Confirm only gamma is left.
- yield confirmMenuItems("gamma");
- yield closeContextMenu();
-
- yield first.unload();
- yield second.unload();
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js
deleted file mode 100644
index a3fa9d32c..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: function() {
- // Report onClickData info back.
- browser.contextMenus.onClicked.addListener(info => {
- browser.test.sendMessage("contextmenus-click", info);
- });
-
- browser.contextMenus.create({
- title: "Checkbox",
- type: "checkbox",
- });
-
- browser.contextMenus.create({
- type: "separator",
- });
-
- browser.contextMenus.create({
- title: "Checkbox",
- type: "checkbox",
- checked: true,
- });
-
- browser.contextMenus.create({
- title: "Checkbox",
- type: "checkbox",
- });
-
- browser.test.notifyPass("contextmenus-checkboxes");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-checkboxes");
-
- function confirmCheckboxStates(extensionMenuRoot, expectedStates) {
- let checkboxItems = extensionMenuRoot.getElementsByAttribute("type", "checkbox");
-
- is(checkboxItems.length, 3, "there should be 3 checkbox items in the context menu");
-
- is(checkboxItems[0].hasAttribute("checked"), expectedStates[0], `checkbox item 1 has state (checked=${expectedStates[0]})`);
- is(checkboxItems[1].hasAttribute("checked"), expectedStates[1], `checkbox item 2 has state (checked=${expectedStates[1]})`);
- is(checkboxItems[2].hasAttribute("checked"), expectedStates[2], `checkbox item 3 has state (checked=${expectedStates[2]})`);
-
- return extensionMenuRoot.getElementsByAttribute("type", "checkbox");
- }
-
- function confirmOnClickData(onClickData, id, was, checked) {
- is(onClickData.wasChecked, was, `checkbox item ${id} was ${was ? "" : "not "}checked before the click`);
- is(onClickData.checked, checked, `checkbox item ${id} is ${checked ? "" : "not "}checked after the click`);
- }
-
- let extensionMenuRoot = yield openExtensionContextMenu();
- let items = confirmCheckboxStates(extensionMenuRoot, [false, true, false]);
- yield closeExtensionContextMenu(items[0]);
-
- let result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 1, false, true);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmCheckboxStates(extensionMenuRoot, [true, true, false]);
- yield closeExtensionContextMenu(items[2]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 3, false, true);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmCheckboxStates(extensionMenuRoot, [true, true, true]);
- yield closeExtensionContextMenu(items[0]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 1, true, false);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmCheckboxStates(extensionMenuRoot, [false, true, true]);
- yield closeExtensionContextMenu(items[2]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 3, true, false);
-
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js
deleted file mode 100644
index a3d31bd19..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- let encodedImageData = "iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAC4klEQVRYhdWXLWzbQBSADQtDAwsHC1tUhUxqfL67lk2tdn+OJg0ODU0rLByqgqINBY6tmlbn7LMTJ5FaFVVBk1G0oUGjG2jT2Y7jxmmcbU/6iJ+f36fz+e5sGP9riCGm9hB37RG+scd4Yo/wsDXCZyIE2xuXsce4bY+wXkAsQtzYmExrfFgvkJkRbkzo1ehoxx5iXcgI/9iYUGt8WH9MqDXEcmNChmEYrRCf2SHWeYgQx3x0tLNRIeKQLTtEFyJEep4NTuhk8BC+yMrwEE3+iozo42d8gK7FAOkMsRiiN8QhW2ttSK5QTfRRV4QoymVeJMvPvDp7gCZigD613MN6yRFA3SWarow9QB9LCfG+NeF9qCtjAKOSQjCqVKhfVsiHEQ+grgx/lRGqUihAc1uL8EFD+KCRO+GrF4J61phcoRoPoEzkYhZYpykh5sMb7kOdIeY+jHKur4QI4Feh4AFX1nVeLxrAvQchGsBz5ls6wa2QdwcvIcE2863bTH79KOvsz/uUYJsp+J0pSzNlDckVqqVGUAF+n6uS7txcOl6wot4JVy70ufDLy4pWLUQVPE81pRI0mGe9oxLMHSeohHvMs/STUNaUK6vDPCvOyxMFDx4achehRDJmHnydnkPww5OFfLxrGIZBFDyYl4LpMzlTQFIP6AQx86w2UeYBccFpJrcKv5L9eGDtUAU6RIELqsB74uynjy/UBRF1gS5BTFxwQT1wTiXoUg9MH7m/3NZRRoi5IJytUbMgzv4Wc832+oQkiKgEehmyMkkpKsFkQV11QsRJL5rJYBLItQgRaUZEmnoZXsomz3vGiWw+I9KMF9SVFOqZEemZekli1jN3U/UOqhHHvC6oWWGElhfSpGdOk6+O9prdwvtLj5BjRsQxdRnot+Zeifpy/2/0stktKTRNLmbk0mwXyl8253fyojj+8rxOHNAhjjm5n0/5OOCGOKBzkrMO0Z75lvSAzKlrF32Z/3z8BqLAn+yMV7VhAAAAAElFTkSuQmCC";
- let decodedImageData = atob(encodedImageData);
- const IMAGE_ARRAYBUFFER = Uint8Array.from(decodedImageData, byte => byte.charCodeAt(0)).buffer;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- "icons": {
- "18": "extension.png",
- },
- },
-
- files: {
- "extension.png": IMAGE_ARRAYBUFFER,
- },
-
- background: function() {
- let menuitemId = browser.contextMenus.create({
- title: "child-to-delete",
- onclick: () => {
- browser.contextMenus.remove(menuitemId);
- },
- });
-
- browser.contextMenus.create({
- title: "child",
- });
-
- browser.test.onMessage.addListener(() => {
- browser.test.sendMessage("pong");
- });
- browser.test.notifyPass("contextmenus-icons");
- },
- });
-
- let confirmContextMenuIcon = (rootElement) => {
- let expectedURL = new RegExp(String.raw`^moz-extension://[^/]+/extension\.png$`);
- let imageUrl = rootElement.getAttribute("image");
- ok(expectedURL.test(imageUrl), "The context menu should display the extension icon next to the root element");
- };
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-icons");
-
- let extensionMenu = yield openExtensionContextMenu();
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let topLevelMenuItem = contextMenu.getElementsByAttribute("ext-type", "top-level-menu")[0];
- confirmContextMenuIcon(topLevelMenuItem);
-
- let childToDelete = extensionMenu.getElementsByAttribute("label", "child-to-delete")[0];
- yield closeExtensionContextMenu(childToDelete);
- // Now perform a roundtrip to the extension process to make sure that the
- // click event has had a chance to fire.
- extension.sendMessage("ping");
- yield extension.awaitMessage("pong");
-
- yield openExtensionContextMenu();
-
- contextMenu = document.getElementById("contentAreaContextMenu");
- topLevelMenuItem = contextMenu.getElementsByAttribute("label", "child")[0];
-
- confirmContextMenuIcon(topLevelMenuItem);
- yield closeContextMenu();
-
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js
deleted file mode 100644
index 96453863d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js
+++ /dev/null
@@ -1,196 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-// Loaded both as a background script and a tab page.
-function testScript() {
- let page = location.pathname.includes("tab.html") ? "tab" : "background";
- let clickCounts = {
- old: 0,
- new: 0,
- };
- browser.contextMenus.onClicked.addListener(() => {
- // Async to give other onclick handlers a chance to fire.
- setTimeout(() => {
- browser.test.sendMessage("onClicked-fired", page);
- });
- });
- browser.test.onMessage.addListener((toPage, msg) => {
- if (toPage !== page) {
- return;
- }
- browser.test.log(`Received ${msg} for ${toPage}`);
- if (msg == "get-click-counts") {
- browser.test.sendMessage("click-counts", clickCounts);
- } else if (msg == "clear-click-counts") {
- clickCounts.old = clickCounts.new = 0;
- browser.test.sendMessage("next");
- } else if (msg == "create-with-onclick") {
- browser.contextMenus.create({
- id: "iden",
- title: "tifier",
- onclick() {
- ++clickCounts.old;
- browser.test.log(`onclick fired for original onclick property in ${page}`);
- },
- }, () => browser.test.sendMessage("next"));
- } else if (msg == "create-without-onclick") {
- browser.contextMenus.create({
- id: "iden",
- title: "tifier",
- }, () => browser.test.sendMessage("next"));
- } else if (msg == "update-without-onclick") {
- browser.contextMenus.update("iden", {
- enabled: true, // Already enabled, so this does nothing.
- }, () => browser.test.sendMessage("next"));
- } else if (msg == "update-with-onclick") {
- browser.contextMenus.update("iden", {
- onclick() {
- ++clickCounts.new;
- browser.test.log(`onclick fired for updated onclick property in ${page}`);
- },
- }, () => browser.test.sendMessage("next"));
- } else if (msg == "remove") {
- browser.contextMenus.remove("iden", () => browser.test.sendMessage("next"));
- } else if (msg == "removeAll") {
- browser.contextMenus.removeAll(() => browser.test.sendMessage("next"));
- }
- });
-
- if (page == "background") {
- browser.test.log("Opening tab.html");
- browser.tabs.create({
- url: "tab.html",
- active: false, // To not interfere with the context menu tests.
- });
- } else {
- // Sanity check - the pages must be in the same process.
- let pages = browser.extension.getViews();
- browser.test.assertTrue(pages.includes(window),
- "Expected this tab to be an extension view");
- pages = pages.filter(w => w !== window);
- browser.test.assertEq(pages[0], browser.extension.getBackgroundPage(),
- "Expected the other page to be a background page");
- browser.test.sendMessage("tab.html ready");
- }
-}
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
- background: testScript,
- files: {
- "tab.html": `<!DOCTYPE html><meta charset="utf-8"><script src="tab.js"></script>`,
- "tab.js": testScript,
- },
- });
- yield extension.startup();
- yield extension.awaitMessage("tab.html ready");
-
- function* clickContextMenu() {
- // Using openContextMenu instead of openExtensionContextMenu because the
- // test extension has only one context menu item.
- let extensionMenuRoot = yield openContextMenu();
- let items = extensionMenuRoot.getElementsByAttribute("label", "tifier");
- is(items.length, 1, "Expected one context menu item");
- yield closeExtensionContextMenu(items[0]);
- // One of them is "tab", the other is "background".
- info(`onClicked from: ${yield extension.awaitMessage("onClicked-fired")}`);
- info(`onClicked from: ${yield extension.awaitMessage("onClicked-fired")}`);
- }
-
- function* getCounts(page) {
- extension.sendMessage(page, "get-click-counts");
- return yield extension.awaitMessage("click-counts");
- }
- function* resetCounts() {
- extension.sendMessage("tab", "clear-click-counts");
- extension.sendMessage("background", "clear-click-counts");
- yield extension.awaitMessage("next");
- yield extension.awaitMessage("next");
- }
-
- // During this test, at most one "onclick" attribute is expected at any time.
- for (let pageOne of ["background", "tab"]) {
- for (let pageTwo of ["background", "tab"]) {
- info(`Testing with menu created by ${pageOne} and updated by ${pageTwo}`);
- extension.sendMessage(pageOne, "create-with-onclick");
- yield extension.awaitMessage("next");
-
- // Test that update without onclick attribute does not clear the existing
- // onclick handler.
- extension.sendMessage(pageTwo, "update-without-onclick");
- yield extension.awaitMessage("next");
- yield clickContextMenu();
- let clickCounts = yield getCounts(pageOne);
- is(clickCounts.old, 1, `Original onclick should still be present in ${pageOne}`);
- is(clickCounts.new, 0, `Not expecting any new handlers in ${pageOne}`);
- if (pageOne !== pageTwo) {
- clickCounts = yield getCounts(pageTwo);
- is(clickCounts.old, 0, `Not expecting any handlers in ${pageTwo}`);
- is(clickCounts.new, 0, `Not expecting any new handlers in ${pageTwo}`);
- }
- yield resetCounts();
-
- // Test that update with onclick handler in a different page clears the
- // existing handler and activates the new onclick handler.
- extension.sendMessage(pageTwo, "update-with-onclick");
- yield extension.awaitMessage("next");
- yield clickContextMenu();
- clickCounts = yield getCounts(pageOne);
- is(clickCounts.old, 0, `Original onclick should be gone from ${pageOne}`);
- if (pageOne !== pageTwo) {
- is(clickCounts.new, 0, `Still not expecting new handlers in ${pageOne}`);
- }
- clickCounts = yield getCounts(pageTwo);
- if (pageOne !== pageTwo) {
- is(clickCounts.old, 0, `Not expecting an old onclick in ${pageTwo}`);
- }
- is(clickCounts.new, 1, `New onclick should be triggered in ${pageTwo}`);
- yield resetCounts();
-
- // Test that updating the handler (different again from the last `update`
- // call, but the same as the `create` call) clears the existing handler
- // and activates the new onclick handler.
- extension.sendMessage(pageOne, "update-with-onclick");
- yield extension.awaitMessage("next");
- yield clickContextMenu();
- clickCounts = yield getCounts(pageOne);
- is(clickCounts.new, 1, `onclick should be triggered in ${pageOne}`);
- if (pageOne !== pageTwo) {
- clickCounts = yield getCounts(pageTwo);
- is(clickCounts.new, 0, `onclick should be gone from ${pageTwo}`);
- }
- yield resetCounts();
-
- // Test that removing the context menu and recreating it with the same ID
- // (in a different context) does not leave behind any onclick handlers.
- extension.sendMessage(pageTwo, "remove");
- yield extension.awaitMessage("next");
- extension.sendMessage(pageTwo, "create-without-onclick");
- yield extension.awaitMessage("next");
- yield clickContextMenu();
- clickCounts = yield getCounts(pageOne);
- is(clickCounts.new, 0, `Did not expect any click handlers in ${pageOne}`);
- if (pageOne !== pageTwo) {
- clickCounts = yield getCounts(pageTwo);
- is(clickCounts.new, 0, `Did not expect any click handlers in ${pageTwo}`);
- }
- yield resetCounts();
-
- // Remove context menu for the next iteration of the test. And just to get
- // more coverage, let's use removeAll instead of remove.
- extension.sendMessage(pageOne, "removeAll");
- yield extension.awaitMessage("next");
- }
- }
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js
deleted file mode 100644
index 3c5fa584b..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: function() {
- // Report onClickData info back.
- browser.contextMenus.onClicked.addListener(info => {
- browser.test.sendMessage("contextmenus-click", info);
- });
-
- browser.contextMenus.create({
- title: "radio-group-1",
- type: "radio",
- checked: true,
- });
-
- browser.contextMenus.create({
- type: "separator",
- });
-
- browser.contextMenus.create({
- title: "radio-group-2",
- type: "radio",
- });
-
- browser.contextMenus.create({
- title: "radio-group-2",
- type: "radio",
- });
-
- browser.test.notifyPass("contextmenus-radio-groups");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-radio-groups");
-
- function confirmRadioGroupStates(extensionMenuRoot, expectedStates) {
- let radioItems = extensionMenuRoot.getElementsByAttribute("type", "radio");
- let radioGroup1 = extensionMenuRoot.getElementsByAttribute("label", "radio-group-1");
- let radioGroup2 = extensionMenuRoot.getElementsByAttribute("label", "radio-group-2");
-
- is(radioItems.length, 3, "there should be 3 radio items in the context menu");
- is(radioGroup1.length, 1, "the first radio group should only have 1 radio item");
- is(radioGroup2.length, 2, "the second radio group should only have 2 radio items");
-
- is(radioGroup1[0].hasAttribute("checked"), expectedStates[0], `radio item 1 has state (checked=${expectedStates[0]})`);
- is(radioGroup2[0].hasAttribute("checked"), expectedStates[1], `radio item 2 has state (checked=${expectedStates[1]})`);
- is(radioGroup2[1].hasAttribute("checked"), expectedStates[2], `radio item 3 has state (checked=${expectedStates[2]})`);
-
- return extensionMenuRoot.getElementsByAttribute("type", "radio");
- }
-
- function confirmOnClickData(onClickData, id, was, checked) {
- is(onClickData.wasChecked, was, `radio item ${id} was ${was ? "" : "not "}checked before the click`);
- is(onClickData.checked, checked, `radio item ${id} is ${checked ? "" : "not "}checked after the click`);
- }
-
- let extensionMenuRoot = yield openExtensionContextMenu();
- let items = confirmRadioGroupStates(extensionMenuRoot, [true, false, false]);
- yield closeExtensionContextMenu(items[1]);
-
- let result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 2, false, true);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmRadioGroupStates(extensionMenuRoot, [true, true, false]);
- yield closeExtensionContextMenu(items[2]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 3, false, true);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmRadioGroupStates(extensionMenuRoot, [true, false, true]);
- yield closeExtensionContextMenu(items[0]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 1, true, true);
-
- extensionMenuRoot = yield openExtensionContextMenu();
- items = confirmRadioGroupStates(extensionMenuRoot, [true, false, true]);
- yield closeExtensionContextMenu(items[0]);
-
- result = yield extension.awaitMessage("contextmenus-click");
- confirmOnClickData(result, 1, true, true);
-
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js
deleted file mode 100644
index fdf06d656..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- // Install an extension.
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: function() {
- browser.contextMenus.create({title: "a"});
- browser.contextMenus.create({title: "b"});
- browser.test.notifyPass("contextmenus-icons");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-icons");
-
- // Open the context menu.
- let contextMenu = yield openContextMenu("#img1");
-
- // Confirm that the extension menu item exists.
- let topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu");
- is(topLevelExtensionMenuItems.length, 1, "the top level extension menu item exists");
-
- yield closeContextMenu();
-
- // Uninstall the extension.
- yield extension.unload();
-
- // Open the context menu.
- contextMenu = yield openContextMenu("#img1");
-
- // Confirm that the extension menu item has been removed.
- topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu");
- is(topLevelExtensionMenuItems.length, 0, "no top level extension menu items should exist");
-
- yield closeContextMenu();
-
- // Install a new extension.
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
- background: function() {
- browser.contextMenus.create({title: "c"});
- browser.contextMenus.create({title: "d"});
- browser.test.notifyPass("contextmenus-uninstall-second-extension");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-uninstall-second-extension");
-
- // Open the context menu.
- contextMenu = yield openContextMenu("#img1");
-
- // Confirm that only the new extension menu item is in the context menu.
- topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu");
- is(topLevelExtensionMenuItems.length, 1, "only one top level extension menu item should exist");
-
- // Close the context menu.
- yield closeContextMenu();
-
- // Uninstall the extension.
- yield extension.unload();
-
- // Open the context menu.
- contextMenu = yield openContextMenu("#img1");
-
- // Confirm that no extension menu items exist.
- topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu");
- is(topLevelExtensionMenuItems.length, 0, "no top level extension menu items should exist");
-
- yield closeContextMenu();
-
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js
deleted file mode 100644
index 7849b8778..000000000
--- a/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js
+++ /dev/null
@@ -1,254 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser,
- "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["contextMenus"],
- },
-
- background: function() {
- // Test menu items using targetUrlPatterns.
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternMatches-contextAll",
- targetUrlPatterns: ["*://*/*ctxmenu-image.png", "*://*/*some-link"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternMatches-contextImage",
- targetUrlPatterns: ["*://*/*ctxmenu-image.png"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternMatches-contextLink",
- targetUrlPatterns: ["*://*/*some-link"],
- contexts: ["link"],
- });
-
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternDoesNotMatch-contextAll",
- targetUrlPatterns: ["*://*/does-not-match"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternDoesNotMatch-contextImage",
- targetUrlPatterns: ["*://*/does-not-match"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "targetUrlPatterns-patternDoesNotMatch-contextLink",
- targetUrlPatterns: ["*://*/does-not-match"],
- contexts: ["link"],
- });
-
- // Test menu items using documentUrlPatterns.
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-contextAll",
- documentUrlPatterns: ["*://*/*context.html"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-contextImage",
- documentUrlPatterns: ["*://*/*context.html", "http://*/url-that-does-not-match"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-contextLink",
- documentUrlPatterns: ["*://*/*context.html", "*://*/does-not-match"],
- contexts: ["link"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-contextAll",
- documentUrlPatterns: ["*://*/does-not-match"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-contextImage",
- documentUrlPatterns: ["*://*/does-not-match"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-contextLink",
- documentUrlPatterns: ["*://*/does-not-match"],
- contexts: ["link"],
- });
-
- // Test menu items using both targetUrlPatterns and documentUrlPatterns.
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll",
- documentUrlPatterns: ["*://*/*context.html"],
- targetUrlPatterns: ["*://*/*ctxmenu-image.png"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll",
- documentUrlPatterns: ["*://does-not-match"],
- targetUrlPatterns: ["*://*/*ctxmenu-image.png"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll",
- documentUrlPatterns: ["*://*/*context.html"],
- targetUrlPatterns: ["*://does-not-match"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll",
- documentUrlPatterns: ["*://does-not-match"],
- targetUrlPatterns: ["*://does-not-match"],
- contexts: ["all"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage",
- documentUrlPatterns: ["*://*/*context.html"],
- targetUrlPatterns: ["*://*/*ctxmenu-image.png"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage",
- documentUrlPatterns: ["*://does-not-match"],
- targetUrlPatterns: ["*://*/*ctxmenu-image.png"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage",
- documentUrlPatterns: ["*://*/*context.html"],
- targetUrlPatterns: ["*://does-not-match"],
- contexts: ["image"],
- });
-
- browser.contextMenus.create({
- title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage",
- documentUrlPatterns: ["*://does-not-match"],
- targetUrlPatterns: ["*://does-not-match"],
- contexts: ["image"],
- });
-
- browser.test.notifyPass("contextmenus-urlPatterns");
- },
- });
-
- function* confirmContextMenuItems(menu, expected) {
- for (let [label, shouldShow] of expected) {
- let items = menu.getElementsByAttribute("label", label);
- if (shouldShow) {
- is(items.length, 1, `The menu item for label ${label} was correctly shown`);
- } else {
- is(items.length, 0, `The menu item for label ${label} was correctly not shown`);
- }
- }
- }
-
- yield extension.startup();
- yield extension.awaitFinish("contextmenus-urlPatterns");
-
- let extensionContextMenu = yield openExtensionContextMenu("#img1");
- let expected = [
- ["targetUrlPatterns-patternMatches-contextAll", true],
- ["targetUrlPatterns-patternMatches-contextImage", true],
- ["targetUrlPatterns-patternMatches-contextLink", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-contextAll", true],
- ["documentUrlPatterns-patternMatches-contextImage", true],
- ["documentUrlPatterns-patternMatches-contextLink", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll", true],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage", true],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ];
- yield confirmContextMenuItems(extensionContextMenu, expected);
- yield closeContextMenu();
-
- let contextMenu = yield openContextMenu("body");
- expected = [
- ["targetUrlPatterns-patternMatches-contextAll", false],
- ["targetUrlPatterns-patternMatches-contextImage", false],
- ["targetUrlPatterns-patternMatches-contextLink", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-contextAll", true],
- ["documentUrlPatterns-patternMatches-contextImage", false],
- ["documentUrlPatterns-patternMatches-contextLink", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage", false],
- ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ];
- yield confirmContextMenuItems(contextMenu, expected);
- yield closeContextMenu();
-
- contextMenu = yield openContextMenu("#link1");
- expected = [
- ["targetUrlPatterns-patternMatches-contextAll", true],
- ["targetUrlPatterns-patternMatches-contextImage", false],
- ["targetUrlPatterns-patternMatches-contextLink", true],
- ["targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-contextAll", true],
- ["documentUrlPatterns-patternMatches-contextImage", false],
- ["documentUrlPatterns-patternMatches-contextLink", true],
- ["documentUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextLink", false],
- ];
- yield confirmContextMenuItems(contextMenu, expected);
- yield closeContextMenu();
-
- contextMenu = yield openContextMenu("#img-wrapped-in-link");
- expected = [
- ["targetUrlPatterns-patternMatches-contextAll", true],
- ["targetUrlPatterns-patternMatches-contextImage", true],
- ["targetUrlPatterns-patternMatches-contextLink", true],
- ["targetUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["targetUrlPatterns-patternDoesNotMatch-contextLink", false],
- ["documentUrlPatterns-patternMatches-contextAll", true],
- ["documentUrlPatterns-patternMatches-contextImage", true],
- ["documentUrlPatterns-patternMatches-contextLink", true],
- ["documentUrlPatterns-patternDoesNotMatch-contextAll", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextImage", false],
- ["documentUrlPatterns-patternDoesNotMatch-contextLink", false],
- ];
- yield confirmContextMenuItems(contextMenu, expected);
- yield closeContextMenu();
-
- yield extension.unload();
- yield BrowserTestUtils.removeTab(tab1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_currentWindow.js b/browser/components/extensions/test/browser/browser_ext_currentWindow.js
deleted file mode 100644
index 11660bf4d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_currentWindow.js
+++ /dev/null
@@ -1,149 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function genericChecker() {
- let kind = "background";
- let path = window.location.pathname;
- if (path.includes("/popup.html")) {
- kind = "popup";
- } else if (path.includes("/page.html")) {
- kind = "page";
- }
-
- browser.test.onMessage.addListener((msg, ...args) => {
- if (msg == kind + "-check-current1") {
- browser.tabs.query({
- currentWindow: true,
- }, function(tabs) {
- browser.test.sendMessage("result", tabs[0].windowId);
- });
- } else if (msg == kind + "-check-current2") {
- browser.tabs.query({
- windowId: browser.windows.WINDOW_ID_CURRENT,
- }, function(tabs) {
- browser.test.sendMessage("result", tabs[0].windowId);
- });
- } else if (msg == kind + "-check-current3") {
- browser.windows.getCurrent(function(window) {
- browser.test.sendMessage("result", window.id);
- });
- } else if (msg == kind + "-open-page") {
- browser.tabs.create({windowId: args[0], url: browser.runtime.getURL("page.html")});
- } else if (msg == kind + "-close-page") {
- browser.tabs.query({
- windowId: args[0],
- }, tabs => {
- let tab = tabs.find(tab => tab.url.includes("/page.html"));
- browser.tabs.remove(tab.id, () => {
- browser.test.sendMessage("closed");
- });
- });
- }
- });
- browser.test.sendMessage(kind + "-ready");
-}
-
-add_task(function* () {
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- yield focusWindow(win2);
-
- yield BrowserTestUtils.loadURI(win1.gBrowser.selectedBrowser, "about:robots");
- yield BrowserTestUtils.browserLoaded(win1.gBrowser.selectedBrowser);
-
- yield BrowserTestUtils.loadURI(win2.gBrowser.selectedBrowser, "about:config");
- yield BrowserTestUtils.browserLoaded(win2.gBrowser.selectedBrowser);
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "browser_action": {
- "default_popup": "popup.html",
- },
- },
-
- files: {
- "page.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="page.js"></script>
- </body></html>
- `,
-
- "page.js": genericChecker,
-
- "popup.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="popup.js"></script>
- </body></html>
- `,
-
- "popup.js": genericChecker,
- },
-
- background: genericChecker,
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]);
-
- let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let winId1 = WindowManager.getId(win1);
- let winId2 = WindowManager.getId(win2);
-
- function* checkWindow(kind, winId, name) {
- extension.sendMessage(kind + "-check-current1");
- is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 1) [${kind}]`);
- extension.sendMessage(kind + "-check-current2");
- is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 2) [${kind}]`);
- extension.sendMessage(kind + "-check-current3");
- is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 3) [${kind}]`);
- }
-
- yield focusWindow(win1);
- yield checkWindow("background", winId1, "win1");
- yield focusWindow(win2);
- yield checkWindow("background", winId2, "win2");
-
- function* triggerPopup(win, callback) {
- yield clickBrowserAction(extension, win);
- yield awaitExtensionPanel(extension, win);
-
- yield extension.awaitMessage("popup-ready");
-
- yield callback();
-
- closeBrowserAction(extension, win);
- }
-
- // Set focus to some other window.
- yield focusWindow(window);
-
- yield triggerPopup(win1, function* () {
- yield checkWindow("popup", winId1, "win1");
- });
-
- yield triggerPopup(win2, function* () {
- yield checkWindow("popup", winId2, "win2");
- });
-
- function* triggerPage(winId, name) {
- extension.sendMessage("background-open-page", winId);
- yield extension.awaitMessage("page-ready");
- yield checkWindow("page", winId, name);
- extension.sendMessage("background-close-page", winId);
- yield extension.awaitMessage("closed");
- }
-
- yield triggerPage(winId1, "win1");
- yield triggerPage(winId2, "win2");
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_getViews.js b/browser/components/extensions/test/browser/browser_ext_getViews.js
deleted file mode 100644
index 684e19ac5..000000000
--- a/browser/components/extensions/test/browser/browser_ext_getViews.js
+++ /dev/null
@@ -1,198 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function genericChecker() {
- let kind = "background";
- let path = window.location.pathname;
- if (path.indexOf("popup") != -1) {
- kind = "popup";
- } else if (path.indexOf("tab") != -1) {
- kind = "tab";
- }
- window.kind = kind;
-
- browser.test.onMessage.addListener((msg, ...args) => {
- if (msg == kind + "-check-views") {
- let windowId = args[0];
- let counts = {
- "background": 0,
- "tab": 0,
- "popup": 0,
- "kind": 0,
- "window": 0,
- };
- if (Number.isInteger(windowId)) {
- counts.window = browser.extension.getViews({windowId: windowId}).length;
- }
- if (kind !== "background") {
- counts.kind = browser.extension.getViews({type: kind}).length;
- }
- let views = browser.extension.getViews();
- let background;
- for (let i = 0; i < views.length; i++) {
- let view = views[i];
- browser.test.assertTrue(view.kind in counts, "view type is valid");
- counts[view.kind]++;
- if (view.kind == "background") {
- browser.test.assertTrue(view === browser.extension.getBackgroundPage(),
- "background page is correct");
- background = view;
- }
- }
- if (background) {
- browser.runtime.getBackgroundPage().then(view => {
- browser.test.assertEq(background, view, "runtime.getBackgroundPage() is correct");
- browser.test.sendMessage("counts", counts);
- });
- } else {
- browser.test.sendMessage("counts", counts);
- }
- } else if (msg == kind + "-open-tab") {
- browser.tabs.create({windowId: args[0], url: browser.runtime.getURL("tab.html")});
- } else if (msg == kind + "-close-tab") {
- browser.tabs.query({
- windowId: args[0],
- }, tabs => {
- let tab = tabs.find(tab => tab.url.indexOf("tab.html") != -1);
- browser.tabs.remove(tab.id, () => {
- browser.test.sendMessage("closed");
- });
- });
- }
- });
- browser.test.sendMessage(kind + "-ready");
-}
-
-add_task(function* () {
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "browser_action": {
- "default_popup": "popup.html",
- },
- },
-
- files: {
- "tab.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="tab.js"></script>
- </body></html>
- `,
-
- "tab.js": genericChecker,
-
- "popup.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="popup.js"></script>
- </body></html>
- `,
-
- "popup.js": genericChecker,
- },
-
- background: genericChecker,
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]);
-
- info("started");
-
- let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let winId1 = WindowManager.getId(win1);
- let winId2 = WindowManager.getId(win2);
-
- function* openTab(winId) {
- extension.sendMessage("background-open-tab", winId);
- yield extension.awaitMessage("tab-ready");
- }
-
- function* checkViews(kind, tabCount, popupCount, kindCount, windowId = undefined, windowCount = 0) {
- extension.sendMessage(kind + "-check-views", windowId);
- let counts = yield extension.awaitMessage("counts");
- is(counts.background, 1, "background count correct");
- is(counts.tab, tabCount, "tab count correct");
- is(counts.popup, popupCount, "popup count correct");
- is(counts.kind, kindCount, "count for type correct");
- is(counts.window, windowCount, "count for window correct");
- }
-
- yield checkViews("background", 0, 0, 0);
-
- yield openTab(winId1);
-
- yield checkViews("background", 1, 0, 0, winId1, 1);
- yield checkViews("tab", 1, 0, 1);
-
- yield openTab(winId2);
-
- yield checkViews("background", 2, 0, 0, winId2, 1);
-
- function* triggerPopup(win, callback) {
- yield clickBrowserAction(extension, win);
- yield awaitExtensionPanel(extension, win);
-
- yield extension.awaitMessage("popup-ready");
-
- yield callback();
-
- closeBrowserAction(extension, win);
- }
-
- // The popup occasionally closes prematurely if we open it immediately here.
- // I'm not sure what causes it to close (it's something internal, and seems to
- // be focus-related, but it's not caused by JS calling hidePopup), but even a
- // short timeout seems to consistently fix it.
- yield new Promise(resolve => win1.setTimeout(resolve, 10));
-
- yield triggerPopup(win1, function* () {
- yield checkViews("background", 2, 1, 0, winId1, 2);
- yield checkViews("popup", 2, 1, 1);
- });
-
- yield triggerPopup(win2, function* () {
- yield checkViews("background", 2, 1, 0, winId2, 2);
- yield checkViews("popup", 2, 1, 1);
- });
-
- info("checking counts after popups");
-
- yield checkViews("background", 2, 0, 0, winId1, 1);
-
- info("closing one tab");
-
- extension.sendMessage("background-close-tab", winId1);
- yield extension.awaitMessage("closed");
-
- info("one tab closed, one remains");
-
- yield checkViews("background", 1, 0, 0);
-
- info("opening win1 popup");
-
- yield triggerPopup(win1, function* () {
- yield checkViews("background", 1, 1, 0);
- yield checkViews("tab", 1, 1, 1);
- yield checkViews("popup", 1, 1, 1);
- });
-
- info("opening win2 popup");
-
- yield triggerPopup(win2, function* () {
- yield checkViews("background", 1, 1, 0);
- yield checkViews("tab", 1, 1, 1);
- yield checkViews("popup", 1, 1, 1);
- });
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_incognito_popup.js b/browser/components/extensions/test/browser/browser_ext_incognito_popup.js
deleted file mode 100644
index 174b2179d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_incognito_popup.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testIncognitoPopup() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- "browser_action": {
- "default_popup": "popup.html",
- },
- "page_action": {
- "default_popup": "popup.html",
- },
- },
-
- background: async function() {
- let resolveMessage;
- browser.runtime.onMessage.addListener(msg => {
- if (resolveMessage && msg.message == "popup-details") {
- resolveMessage(msg);
- }
- });
-
- let awaitPopup = windowId => {
- return new Promise(resolve => {
- resolveMessage = resolve;
- }).then(msg => {
- browser.test.assertEq(windowId, msg.windowId, "Got popup message from correct window");
- return msg;
- });
- };
-
- let testWindow = async window => {
- let [tab] = await browser.tabs.query({active: true, windowId: window.id});
-
- await browser.pageAction.show(tab.id);
- browser.test.sendMessage("click-pageAction");
-
- let msg = await awaitPopup(window.id);
- browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in pageAction popup");
-
- browser.test.sendMessage("click-browserAction");
-
- msg = await awaitPopup(window.id);
- browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup");
- };
-
- const URL = "http://example.com/incognito";
- let windowReady = new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab) {
- if (changed.status == "complete" && tab.url == URL) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
-
- try {
- {
- let window = await browser.windows.getCurrent();
-
- await testWindow(window);
- }
-
- {
- let window = await browser.windows.create({incognito: true, url: URL});
- await windowReady;
-
- await testWindow(window);
-
- await browser.windows.remove(window.id);
- }
-
- browser.test.notifyPass("incognito");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("incognito");
- }
- },
-
- files: {
- "popup.html": '<html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>',
-
- "popup.js": async function() {
- let win = await browser.windows.getCurrent();
- browser.runtime.sendMessage({
- message: "popup-details",
- windowId: win.id,
- incognito: browser.extension.inIncognitoContext,
- });
- window.close();
- },
- },
- });
-
- extension.onMessage("click-browserAction", () => {
- clickBrowserAction(extension, Services.wm.getMostRecentWindow("navigator:browser"));
- });
-
- extension.onMessage("click-pageAction", () => {
- clickPageAction(extension, Services.wm.getMostRecentWindow("navigator:browser"));
- });
-
- yield extension.startup();
- yield extension.awaitFinish("incognito");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_incognito_views.js b/browser/components/extensions/test/browser/browser_ext_incognito_views.js
deleted file mode 100644
index 4865b2d4f..000000000
--- a/browser/components/extensions/test/browser/browser_ext_incognito_views.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testIncognitoViews() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- "browser_action": {
- "default_popup": "popup.html",
- },
- },
-
- background: async function() {
- window.isBackgroundPage = true;
-
- let resolveMessage;
- browser.runtime.onMessage.addListener(msg => {
- if (resolveMessage && msg.message == "popup-details") {
- resolveMessage(msg);
- }
- });
-
- let awaitPopup = windowId => {
- return new Promise(resolve => {
- resolveMessage = resolve;
- }).then(msg => {
- browser.test.assertEq(windowId, msg.windowId, "Got popup message from correct window");
- return msg;
- });
- };
-
- let testWindow = async window => {
- browser.test.sendMessage("click-browserAction");
-
- let msg = await awaitPopup(window.id);
- browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup");
- };
-
- const URL = "http://example.com/incognito";
- let windowReady = new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab) {
- if (changed.status == "complete" && tab.url == URL) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
-
- try {
- {
- let window = await browser.windows.getCurrent();
-
- await testWindow(window);
- }
-
- {
- let window = await browser.windows.create({incognito: true, url: URL});
- await windowReady;
-
- await testWindow(window);
-
- await browser.windows.remove(window.id);
- }
-
- browser.test.notifyPass("incognito-views");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("incognito-views");
- }
- },
-
- files: {
- "popup.html": '<html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>',
-
- "popup.js": async function() {
- let views = browser.extension.getViews();
-
- if (browser.extension.inIncognitoContext) {
- let bgPage = browser.extension.getBackgroundPage();
- browser.test.assertEq(null, bgPage, "Should not be able to access background page in incognito context");
-
- bgPage = await browser.runtime.getBackgroundPage();
- browser.test.assertEq(null, bgPage, "Should not be able to access background page in incognito context");
-
- browser.test.assertEq(1, views.length, "Should only see one view in incognito popup");
- browser.test.assertEq(window, views[0], "This window should be the only view");
- } else {
- let bgPage = browser.extension.getBackgroundPage();
- browser.test.assertEq(true, bgPage.isBackgroundPage,
- "Should be able to access background page in non-incognito context");
-
- bgPage = await browser.runtime.getBackgroundPage();
- browser.test.assertEq(true, bgPage.isBackgroundPage,
- "Should be able to access background page in non-incognito context");
-
- browser.test.assertEq(2, views.length, "Should only two views in non-incognito popup");
- browser.test.assertEq(bgPage, views[0], "The background page should be the first view");
- browser.test.assertEq(window, views[1], "This window should be the second view");
- }
-
- let win = await browser.windows.getCurrent();
- browser.runtime.sendMessage({
- message: "popup-details",
- windowId: win.id,
- incognito: browser.extension.inIncognitoContext,
- });
-
- window.close();
- },
- },
- });
-
- extension.onMessage("click-browserAction", () => {
- clickBrowserAction(extension, Services.wm.getMostRecentWindow("navigator:browser"));
- });
-
- yield extension.startup();
- yield extension.awaitFinish("incognito-views");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_lastError.js b/browser/components/extensions/test/browser/browser_ext_lastError.js
deleted file mode 100644
index 499e709aa..000000000
--- a/browser/components/extensions/test/browser/browser_ext_lastError.js
+++ /dev/null
@@ -1,55 +0,0 @@
-"use strict";
-
-function* sendMessage(options) {
- function background(options) {
- browser.runtime.sendMessage(result => {
- browser.test.assertEq(undefined, result, "Argument value");
- if (options.checkLastError) {
- let lastError = browser[options.checkLastError].lastError;
- browser.test.assertEq("runtime.sendMessage's message argument is missing",
- lastError && lastError.message,
- "lastError value");
- }
- browser.test.sendMessage("done");
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: `(${background})(${JSON.stringify(options)})`,
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("done");
-
- yield extension.unload();
-}
-
-add_task(function* testLastError() {
- // Not necessary in browser-chrome tests, but monitorConsole gripes
- // if we don't call it.
- SimpleTest.waitForExplicitFinish();
-
- // Check that we have no unexpected console messages when lastError is
- // checked.
- for (let api of ["extension", "runtime"]) {
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{message: /message argument is missing/, forbid: true}]);
- });
-
- yield sendMessage({checkLastError: api});
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
- }
-
- // Check that we do have a console message when lastError is not checked.
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{message: /Unchecked lastError value: Error: runtime.sendMessage's message argument is missing/}]);
- });
-
- yield sendMessage({});
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js b/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js
deleted file mode 100644
index 01557a745..000000000
--- a/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js
+++ /dev/null
@@ -1,173 +0,0 @@
-"use strict";
-
-const {
- LegacyExtensionContext,
-} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {});
-
-function promiseAddonStartup(extension) {
- const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- return new Promise((resolve) => {
- let listener = (evt, extensionInstance) => {
- Management.off("startup", listener);
- resolve(extensionInstance);
- };
- Management.on("startup", listener);
- });
-}
-
-/**
- * This test case ensures that the LegacyExtensionContext can receive a connection
- * from a content script and that the received port contains the expected sender
- * tab info.
- */
-add_task(function* test_legacy_extension_context_contentscript_connection() {
- function backgroundScript() {
- // Extract the assigned uuid from the background page url and send it
- // in a test message.
- let uuid = window.location.hostname;
-
- browser.test.onMessage.addListener(async msg => {
- if (msg == "open-test-tab") {
- let tab = await browser.tabs.create({url: "http://example.com/"});
- browser.test.sendMessage("get-expected-sender-info",
- {uuid, tab});
- } else if (msg == "close-current-tab") {
- try {
- let [tab] = await browser.tabs.query({active: true});
- await browser.tabs.remove(tab.id);
- browser.test.sendMessage("current-tab-closed", true);
- } catch (e) {
- browser.test.sendMessage("current-tab-closed", false);
- }
- }
- });
-
- browser.test.sendMessage("ready");
- }
-
- function contentScript() {
- browser.runtime.sendMessage("webextension -> legacy_extension message", (reply) => {
- browser.test.assertEq("legacy_extension -> webextension reply", reply,
- "Got the expected reply from the LegacyExtensionContext");
- browser.test.sendMessage("got-reply-message");
- });
-
- let port = browser.runtime.connect();
-
- port.onMessage.addListener(msg => {
- browser.test.assertEq("legacy_extension -> webextension port message", msg,
- "Got the expected message from the LegacyExtensionContext");
- port.postMessage("webextension -> legacy_extension port message");
- });
- }
-
- let extensionData = {
- background: `new ${backgroundScript}`,
- manifest: {
- content_scripts: [
- {
- matches: ["http://example.com/*"],
- js: ["content-script.js"],
- },
- ],
- },
- files: {
- "content-script.js": `new ${contentScript}`,
- },
- };
-
- let extension = ExtensionTestUtils.loadExtension(extensionData);
-
- let waitForExtensionReady = extension.awaitMessage("ready");
-
- let waitForExtensionInstance = promiseAddonStartup(extension);
-
- extension.startup();
-
- let extensionInstance = yield waitForExtensionInstance;
-
- // Connect to the target extension.id as an external context
- // using the given custom sender info.
- let legacyContext = new LegacyExtensionContext(extensionInstance);
-
- let waitConnectPort = new Promise(resolve => {
- let {browser} = legacyContext.api;
- browser.runtime.onConnect.addListener(port => {
- resolve(port);
- });
- });
-
- let waitMessage = new Promise(resolve => {
- let {browser} = legacyContext.api;
- browser.runtime.onMessage.addListener((singleMsg, msgSender, sendReply) => {
- sendReply("legacy_extension -> webextension reply");
- resolve({singleMsg, msgSender});
- });
- });
-
- is(legacyContext.envType, "legacy_extension",
- "LegacyExtensionContext instance has the expected type");
-
- ok(legacyContext.api, "Got the API object");
-
- yield waitForExtensionReady;
-
- extension.sendMessage("open-test-tab");
-
- let {uuid, tab} = yield extension.awaitMessage("get-expected-sender-info");
-
- let {singleMsg, msgSender} = yield waitMessage;
- is(singleMsg, "webextension -> legacy_extension message",
- "Got the expected message");
- ok(msgSender, "Got a message sender object");
-
- is(msgSender.id, uuid, "The sender has the expected id property");
- is(msgSender.url, "http://example.com/", "The sender has the expected url property");
- ok(msgSender.tab, "The sender has a tab property");
- is(msgSender.tab.id, tab.id, "The port sender has the expected tab.id");
-
- // Wait confirmation that the reply has been received.
- yield extension.awaitMessage("got-reply-message");
-
- let port = yield waitConnectPort;
-
- ok(port, "Got the Port API object");
- ok(port.sender, "The port has a sender property");
-
- is(port.sender.id, uuid, "The port sender has an id property");
- is(port.sender.url, "http://example.com/", "The port sender has the expected url property");
- ok(port.sender.tab, "The port sender has a tab property");
- is(port.sender.tab.id, tab.id, "The port sender has the expected tab.id");
-
- let waitPortMessage = new Promise(resolve => {
- port.onMessage.addListener((msg) => {
- resolve(msg);
- });
- });
-
- port.postMessage("legacy_extension -> webextension port message");
-
- let msg = yield waitPortMessage;
-
- is(msg, "webextension -> legacy_extension port message",
- "LegacyExtensionContext received the expected message from the webextension");
-
- let waitForDisconnect = new Promise(resolve => {
- port.onDisconnect.addListener(resolve);
- });
-
- let waitForTestDone = extension.awaitMessage("current-tab-closed");
-
- extension.sendMessage("close-current-tab");
-
- yield waitForDisconnect;
-
- info("Got the disconnect event on tab closed");
-
- let success = yield waitForTestDone;
-
- ok(success, "Test completed successfully");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_omnibox.js b/browser/components/extensions/test/browser/browser_ext_omnibox.js
deleted file mode 100644
index 98d3573c5..000000000
--- a/browser/components/extensions/test/browser/browser_ext_omnibox.js
+++ /dev/null
@@ -1,286 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* setup() {
- const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, false);
-
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
- });
-}
-
-add_task(function* () {
- let keyword = "test";
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "omnibox": {
- "keyword": keyword,
- },
- },
-
- background: function() {
- browser.omnibox.onInputStarted.addListener(() => {
- browser.test.sendMessage("on-input-started-fired");
- });
-
- let synchronous = true;
- let suggestions = null;
- let suggestCallback = null;
-
- browser.omnibox.onInputChanged.addListener((text, suggest) => {
- if (synchronous && suggestions) {
- suggest(suggestions);
- } else {
- suggestCallback = suggest;
- }
- browser.test.sendMessage("on-input-changed-fired", {text});
- });
-
- browser.omnibox.onInputCancelled.addListener(() => {
- browser.test.sendMessage("on-input-cancelled-fired");
- });
-
- browser.omnibox.onInputEntered.addListener((text, disposition) => {
- browser.test.sendMessage("on-input-entered-fired", {text, disposition});
- });
-
- browser.test.onMessage.addListener((msg, data) => {
- switch (msg) {
- case "set-suggestions":
- suggestions = data.suggestions;
- browser.test.sendMessage("suggestions-set");
- break;
- case "set-default-suggestion":
- browser.omnibox.setDefaultSuggestion(data.suggestion);
- browser.test.sendMessage("default-suggestion-set");
- break;
- case "set-synchronous":
- synchronous = data.synchronous;
- break;
- case "test-multiple-suggest-calls":
- suggestions.forEach(suggestion => suggestCallback([suggestion]));
- browser.test.sendMessage("test-ready");
- break;
- case "test-suggestions-after-delay":
- Promise.resolve().then(() => {
- suggestCallback(suggestions);
- browser.test.sendMessage("test-ready");
- });
- break;
- }
- });
- },
- });
-
- function* expectEvent(event, expected = {}) {
- let actual = yield extension.awaitMessage(event);
- if (expected.text) {
- is(actual.text, expected.text,
- `Expected "${event}" to have fired with text: "${expected.text}".`);
- }
- if (expected.disposition) {
- is(actual.disposition, expected.disposition,
- `Expected "${event}" to have fired with disposition: "${expected.disposition}".`);
- }
- }
-
- function* startInputSession() {
- gURLBar.focus();
- gURLBar.value = keyword;
- EventUtils.synthesizeKey(" ", {});
- yield expectEvent("on-input-started-fired");
- EventUtils.synthesizeKey("t", {});
- yield expectEvent("on-input-changed-fired", {text: "t"});
- return "t";
- }
-
- function* testInputEvents() {
- gURLBar.focus();
-
- // Start an input session by typing in <keyword><space>.
- for (let letter of keyword) {
- EventUtils.synthesizeKey(letter, {});
- }
- EventUtils.synthesizeKey(" ", {});
- yield expectEvent("on-input-started-fired");
-
- // We should expect input changed events now that the keyword is active.
- EventUtils.synthesizeKey("b", {});
- yield expectEvent("on-input-changed-fired", {text: "b"});
-
- EventUtils.synthesizeKey("c", {});
- yield expectEvent("on-input-changed-fired", {text: "bc"});
-
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- yield expectEvent("on-input-changed-fired", {text: "b"});
-
- // Even though the input is <keyword><space> We should not expect an
- // input started event to fire since the keyword is active.
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- yield expectEvent("on-input-changed-fired", {text: ""});
-
- // Make the keyword inactive by hitting backspace.
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- yield expectEvent("on-input-cancelled-fired");
-
- // Activate the keyword by typing a space.
- // Expect onInputStarted to fire.
- EventUtils.synthesizeKey(" ", {});
- yield expectEvent("on-input-started-fired");
-
- // onInputChanged should fire even if a space is entered.
- EventUtils.synthesizeKey(" ", {});
- yield expectEvent("on-input-changed-fired", {text: " "});
-
- // The active session should cancel if the input blurs.
- gURLBar.blur();
- yield expectEvent("on-input-cancelled-fired");
- }
-
- function* testHeuristicResult(expectedText, setDefaultSuggestion) {
- if (setDefaultSuggestion) {
- extension.sendMessage("set-default-suggestion", {
- suggestion: {
- description: expectedText,
- },
- });
- yield extension.awaitMessage("default-suggestion-set");
- }
-
- let text = yield startInputSession();
-
- let item = gURLBar.popup.richlistbox.children[0];
-
- is(item.getAttribute("title"), expectedText,
- `Expected heuristic result to have title: "${expectedText}".`);
-
- is(item.getAttribute("displayurl"), `${keyword} ${text}`,
- `Expected heuristic result to have displayurl: "${keyword} ${text}".`);
-
- EventUtils.synthesizeMouseAtCenter(item, {});
-
- yield expectEvent("on-input-entered-fired", {
- text,
- disposition: "currentTab",
- });
- }
-
- function* testDisposition(suggestionIndex, expectedDisposition, expectedText) {
- yield startInputSession();
-
- // Select the suggestion.
- for (let i = 0; i < suggestionIndex; i++) {
- EventUtils.synthesizeKey("VK_DOWN", {});
- }
-
- let item = gURLBar.popup.richlistbox.children[suggestionIndex];
- if (expectedDisposition == "currentTab") {
- EventUtils.synthesizeMouseAtCenter(item, {});
- } else if (expectedDisposition == "newForegroundTab") {
- EventUtils.synthesizeMouseAtCenter(item, {accelKey: true});
- } else if (expectedDisposition == "newBackgroundTab") {
- EventUtils.synthesizeMouseAtCenter(item, {shiftKey: true, accelKey: true});
- }
-
- yield expectEvent("on-input-entered-fired", {
- text: expectedText,
- disposition: expectedDisposition,
- });
- }
-
- function* testSuggestions(info) {
- extension.sendMessage("set-synchronous", {synchronous: false});
-
- function expectSuggestion({content, description}, index) {
- let item = gURLBar.popup.richlistbox.children[index + 1]; // Skip the heuristic result.
-
- ok(!!item, "Expected item to exist");
- is(item.getAttribute("title"), description,
- `Expected suggestion to have title: "${description}".`);
-
- is(item.getAttribute("displayurl"), `${keyword} ${content}`,
- `Expected suggestion to have displayurl: "${keyword} ${content}".`);
- }
-
- let text = yield startInputSession();
-
- extension.sendMessage(info.test);
- yield extension.awaitMessage("test-ready");
-
- info.suggestions.forEach(expectSuggestion);
-
- EventUtils.synthesizeMouseAtCenter(gURLBar.popup.richlistbox.children[0], {});
- yield expectEvent("on-input-entered-fired", {
- text,
- disposition: "currentTab",
- });
- }
-
- yield setup();
- yield extension.startup();
-
- yield testInputEvents();
-
- // Test the heuristic result with default suggestions.
- yield testHeuristicResult("Generated extension", false /* setDefaultSuggestion */);
- yield testHeuristicResult("hello world", true /* setDefaultSuggestion */);
- yield testHeuristicResult("foo bar", true /* setDefaultSuggestion */);
-
- let suggestions = [
- {content: "a", description: "select a"},
- {content: "b", description: "select b"},
- {content: "c", description: "select c"},
- ];
-
- extension.sendMessage("set-suggestions", {suggestions});
- yield extension.awaitMessage("suggestions-set");
-
- // Test each suggestion and search disposition.
- yield testDisposition(1, "currentTab", suggestions[0].content);
- yield testDisposition(2, "newForegroundTab", suggestions[1].content);
- yield testDisposition(3, "newBackgroundTab", suggestions[2].content);
-
- extension.sendMessage("set-suggestions", {suggestions});
- yield extension.awaitMessage("suggestions-set");
-
- // Test adding suggestions asynchronously.
- yield testSuggestions({
- test: "test-multiple-suggest-calls",
- skipHeuristic: true,
- suggestions,
- });
- yield testSuggestions({
- test: "test-suggestions-after-delay",
- skipHeuristic: true,
- suggestions,
- });
-
- // Start monitoring the console.
- SimpleTest.waitForExplicitFinish();
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{
- message: new RegExp(`The keyword provided is already registered: "${keyword}"`),
- }]);
- });
-
- // Try registering another extension with the same keyword
- let extension2 = ExtensionTestUtils.loadExtension({
- manifest: {
- "omnibox": {
- "keyword": keyword,
- },
- },
- });
-
- yield extension2.startup();
-
- // Stop monitoring the console and confirm the correct errors are logged.
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
-
- yield extension2.unload();
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js b/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js
deleted file mode 100644
index 3e7342dd1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* test_tab_options_privileges() {
- function backgroundScript() {
- browser.runtime.onMessage.addListener(({msgName, tabId}) => {
- if (msgName == "removeTabId") {
- browser.tabs.remove(tabId).then(() => {
- browser.test.notifyPass("options-ui-privileges");
- }).catch(error => {
- browser.test.log(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("options-ui-privileges");
- });
- }
- });
- browser.runtime.openOptionsPage();
- }
-
- async function optionsScript() {
- try {
- let [tab] = await browser.tabs.query({url: "http://example.com/"});
- browser.test.assertEq("http://example.com/", tab.url, "Got the expect tab");
-
- tab = await browser.tabs.getCurrent();
- browser.runtime.sendMessage({msgName: "removeTabId", tabId: tab.id});
- } catch (error) {
- browser.test.log(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("options-ui-privileges");
- }
- }
-
- const ID = "options_privileges@tests.mozilla.org";
- let extension = ExtensionTestUtils.loadExtension({
- useAddonManager: "temporary",
-
- manifest: {
- applications: {gecko: {id: ID}},
- "permissions": ["tabs"],
- "options_ui": {
- "page": "options.html",
- },
- },
- files: {
- "options.html": `<!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script src="options.js" type="text/javascript"></script>
- </head>
- </html>`,
- "options.js": optionsScript,
- },
- background: backgroundScript,
- });
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- yield extension.startup();
-
- yield extension.awaitFinish("options-ui-privileges");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_context.js b/browser/components/extensions/test/browser/browser_ext_pageAction_context.js
deleted file mode 100644
index 2c2a4cd2f..000000000
--- a/browser/components/extensions/test/browser/browser_ext_pageAction_context.js
+++ /dev/null
@@ -1,178 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* global runTests */
-
-Services.scriptloader.loadSubScript(new URL("head_pageAction.js", gTestPath).href,
- this);
-
-add_task(function* testTabSwitchContext() {
- yield runTests({
- manifest: {
- "name": "Foo Extension",
-
- "page_action": {
- "default_icon": "default.png",
- "default_popup": "__MSG_popup__",
- "default_title": "Default __MSG_title__ \u263a",
- },
-
- "default_locale": "en",
-
- "permissions": ["tabs"],
- },
-
- "files": {
- "_locales/en/messages.json": {
- "popup": {
- "message": "default.html",
- "description": "Popup",
- },
-
- "title": {
- "message": "Title",
- "description": "Title",
- },
- },
-
- "_locales/es_ES/messages.json": {
- "popup": {
- "message": "default.html",
- "description": "Popup",
- },
-
- "title": {
- "message": "T\u00edtulo",
- "description": "Title",
- },
- },
-
- "default.png": imageBuffer,
- "1.png": imageBuffer,
- "2.png": imageBuffer,
- },
-
- getTests(tabs) {
- let details = [
- {"icon": browser.runtime.getURL("default.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default T\u00edtulo \u263a"},
- {"icon": browser.runtime.getURL("1.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default T\u00edtulo \u263a"},
- {"icon": browser.runtime.getURL("2.png"),
- "popup": browser.runtime.getURL("2.html"),
- "title": "Title 2"},
- {"icon": browser.runtime.getURL("2.png"),
- "popup": browser.runtime.getURL("2.html"),
- "title": "Default T\u00edtulo \u263a"},
- ];
-
- let promiseTabLoad = details => {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changed) {
- if (tabId == details.id && changed.url == details.url) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- };
-
- return [
- expect => {
- browser.test.log("Initial state. No icon visible.");
- expect(null);
- },
- async expect => {
- browser.test.log("Show the icon on the first tab, expect default properties.");
- await browser.pageAction.show(tabs[0]);
- expect(details[0]);
- },
- expect => {
- browser.test.log("Change the icon. Expect default properties excluding the icon.");
- browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"});
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Create a new tab. No icon visible.");
- let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
- tabs.push(tab.id);
- expect(null);
- },
- expect => {
- browser.test.log("Await tab load. No icon visible.");
- expect(null);
- },
- async expect => {
- browser.test.log("Change properties. Expect new properties.");
- let tabId = tabs[1];
- await browser.pageAction.show(tabId);
-
- browser.pageAction.setIcon({tabId, path: "2.png"});
- browser.pageAction.setPopup({tabId, popup: "2.html"});
- browser.pageAction.setTitle({tabId, title: "Title 2"});
-
- expect(details[2]);
- },
- async expect => {
- browser.test.log("Change the hash. Expect same properties.");
-
- let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"});
- browser.tabs.update(tabs[1], {url: "about:blank?0#ref"});
- await promise;
-
- expect(details[2]);
- },
- expect => {
- browser.test.log("Clear the title. Expect default title.");
- browser.pageAction.setTitle({tabId: tabs[1], title: ""});
-
- expect(details[3]);
- },
- async expect => {
- browser.test.log("Navigate to a new page. Expect icon hidden.");
-
- // TODO: This listener should not be necessary, but the |tabs.update|
- // callback currently fires too early in e10s windows.
- let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"});
-
- browser.tabs.update(tabs[1], {url: "about:blank?1"});
-
- await promise;
- expect(null);
- },
- async expect => {
- browser.test.log("Show the icon. Expect default properties again.");
-
- await browser.pageAction.show(tabs[1]);
- expect(details[0]);
- },
- async expect => {
- browser.test.log("Switch back to the first tab. Expect previously set properties.");
- await browser.tabs.update(tabs[0], {active: true});
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Hide the icon on tab 2. Switch back, expect hidden.");
- await browser.pageAction.hide(tabs[1]);
-
- await browser.tabs.update(tabs[1], {active: true});
- expect(null);
- },
- async expect => {
- browser.test.log("Switch back to tab 1. Expect previous results again.");
- await browser.tabs.remove(tabs[1]);
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Hide the icon. Expect hidden.");
-
- await browser.pageAction.hide(tabs[0]);
- expect(null);
- },
- ];
- },
- });
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js b/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js
deleted file mode 100644
index 83defdd68..000000000
--- a/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js
+++ /dev/null
@@ -1,238 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testPageActionPopup() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head></html>`;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "background": {
- "page": "data/background.html",
- },
- "page_action": {
- "default_popup": "popup-a.html",
- },
- },
-
- files: {
- "popup-a.html": scriptPage("popup-a.js"),
- "popup-a.js": function() {
- window.onload = () => {
- let background = window.getComputedStyle(document.body).backgroundColor;
- browser.test.assertEq("transparent", background);
- browser.runtime.sendMessage("from-popup-a");
- };
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "close-popup") {
- window.close();
- }
- });
- },
-
- "data/popup-b.html": scriptPage("popup-b.js"),
- "data/popup-b.js": function() {
- browser.runtime.sendMessage("from-popup-b");
- },
-
- "data/background.html": scriptPage("background.js"),
-
- "data/background.js": async function() {
- let tabId;
-
- let sendClick;
- let tests = [
- () => {
- sendClick({expectEvent: false, expectPopup: "a"});
- },
- () => {
- sendClick({expectEvent: false, expectPopup: "a"});
- },
- () => {
- browser.pageAction.setPopup({tabId, popup: "popup-b.html"});
- sendClick({expectEvent: false, expectPopup: "b"});
- },
- () => {
- sendClick({expectEvent: false, expectPopup: "b"});
- },
- () => {
- browser.pageAction.setPopup({tabId, popup: ""});
- sendClick({expectEvent: true, expectPopup: null});
- },
- () => {
- sendClick({expectEvent: true, expectPopup: null});
- },
- () => {
- browser.pageAction.setPopup({tabId, popup: "/popup-a.html"});
- sendClick({expectEvent: false, expectPopup: "a", runNextTest: true});
- },
- () => {
- browser.test.sendMessage("next-test", {expectClosed: true});
- },
- () => {
- sendClick({expectEvent: false, expectPopup: "a", runNextTest: true});
- },
- () => {
- browser.test.sendMessage("next-test", {closeOnTabSwitch: true});
- },
- ];
-
- let expect = {};
- sendClick = ({expectEvent, expectPopup, runNextTest}) => {
- expect = {event: expectEvent, popup: expectPopup, runNextTest};
- browser.test.sendMessage("send-click");
- };
-
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "close-popup") {
- return;
- } else if (expect.popup) {
- browser.test.assertEq(msg, `from-popup-${expect.popup}`,
- "expected popup opened");
- } else {
- browser.test.fail(`unexpected popup: ${msg}`);
- }
-
- expect.popup = null;
- if (expect.runNextTest) {
- expect.runNextTest = false;
- tests.shift()();
- } else {
- browser.test.sendMessage("next-test");
- }
- });
-
- browser.pageAction.onClicked.addListener(() => {
- if (expect.event) {
- browser.test.succeed("expected click event received");
- } else {
- browser.test.fail("unexpected click event");
- }
-
- expect.event = false;
- browser.test.sendMessage("next-test");
- });
-
- browser.test.onMessage.addListener(msg => {
- if (msg == "close-popup") {
- browser.runtime.sendMessage("close-popup");
- return;
- }
-
- if (msg != "next-test") {
- browser.test.fail("Expecting 'next-test' message");
- }
-
- if (tests.length) {
- let test = tests.shift();
- test();
- } else {
- browser.test.notifyPass("pageaction-tests-done");
- }
- });
-
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- tabId = tab.id;
-
- await browser.pageAction.show(tabId);
- browser.test.sendMessage("next-test");
- },
- },
- });
-
- extension.onMessage("send-click", () => {
- clickPageAction(extension);
- });
-
- let pageActionId, panelId;
- extension.onMessage("next-test", Task.async(function* (expecting = {}) {
- pageActionId = `${makeWidgetId(extension.id)}-page-action`;
- panelId = `${makeWidgetId(extension.id)}-panel`;
- let panel = document.getElementById(panelId);
- if (expecting.expectClosed) {
- ok(panel, "Expect panel to exist");
- yield promisePopupShown(panel);
-
- extension.sendMessage("close-popup");
-
- yield promisePopupHidden(panel);
- ok(true, `Panel is closed`);
- } else if (expecting.closeOnTabSwitch) {
- ok(panel, "Expect panel to exist");
- yield promisePopupShown(panel);
-
- let oldTab = gBrowser.selectedTab;
- ok(oldTab != gBrowser.tabs[0], "Should have an inactive tab to switch to");
-
- let hiddenPromise = promisePopupHidden(panel);
-
- gBrowser.selectedTab = gBrowser.tabs[0];
- yield hiddenPromise;
- info("Panel closed");
-
- gBrowser.selectedTab = oldTab;
- } else if (panel) {
- yield promisePopupShown(panel);
- panel.hidePopup();
- }
-
- if (panel) {
- panel = document.getElementById(panelId);
- is(panel, null, "panel successfully removed from document after hiding");
- }
-
- extension.sendMessage("next-test");
- }));
-
-
- yield extension.startup();
- yield extension.awaitFinish("pageaction-tests-done");
-
- yield extension.unload();
-
- let node = document.getElementById(pageActionId);
- is(node, null, "pageAction image removed from document");
-
- let panel = document.getElementById(panelId);
- is(panel, null, "pageAction panel removed from document");
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-
-add_task(function* testPageActionSecurity() {
- const URL = "chrome://browser/content/browser.xul";
-
- let apis = ["browser_action", "page_action"];
-
- for (let api of apis) {
- info(`TEST ${api} icon url: ${URL}`);
-
- let messages = [/Access to restricted URI denied/];
-
- let waitForConsole = new Promise(resolve => {
- // Not necessary in browser-chrome tests, but monitorConsole gripes
- // if we don't call it.
- SimpleTest.waitForExplicitFinish();
-
- SimpleTest.monitorConsole(resolve, messages);
- });
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- [api]: {"default_popup": URL},
- },
- });
-
- yield Assert.rejects(extension.startup(),
- null,
- "Manifest rejected");
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
- }
-});
-
-add_task(forceGC);
diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js b/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js
deleted file mode 100644
index 98c4c3488..000000000
--- a/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js
+++ /dev/null
@@ -1,169 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-let delay = ms => new Promise(resolve => {
- setTimeout(resolve, ms);
-});
-
-add_task(function* testPageActionPopupResize() {
- let browser;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- },
- background: function() {
- /* global browser */
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- const tabId = tabs[0].id;
-
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("action-shown");
- });
- });
- },
-
- files: {
- "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><div></div></body></html>`,
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("action-shown");
-
- clickPageAction(extension, window);
-
- browser = yield awaitExtensionPanel(extension);
-
- function* checkSize(expected) {
- let dims = yield promiseContentDimensions(browser);
- let {body, root} = dims;
-
- is(dims.window.innerHeight, expected, `Panel window should be ${expected}px tall`);
- is(body.clientHeight, body.scrollHeight,
- "Panel body should be tall enough to fit its contents");
- is(root.clientHeight, root.scrollHeight,
- "Panel root should be tall enough to fit its contents");
-
- // Tolerate if it is 1px too wide, as that may happen with the current resizing method.
- ok(Math.abs(dims.window.innerWidth - expected) <= 1, `Panel window should be ${expected}px wide`);
- is(body.clientWidth, body.scrollWidth,
- "Panel body should be wide enough to fit its contents");
- }
-
- /* eslint-disable mozilla/no-cpows-in-tests */
- function setSize(size) {
- let elem = content.document.body.firstChild;
- elem.style.height = `${size}px`;
- elem.style.width = `${size}px`;
- }
- /* eslint-enable mozilla/no-cpows-in-tests */
-
- let sizes = [
- 200,
- 400,
- 300,
- ];
-
- for (let size of sizes) {
- yield alterContent(browser, setSize, size);
- yield checkSize(size);
- }
-
- yield alterContent(browser, setSize, 1400);
-
- let dims = yield promiseContentDimensions(browser);
- let {body, root} = dims;
-
- if (AppConstants.platform == "win") {
- while (dims.window.innerWidth < 800) {
- yield delay(50);
- dims = yield promiseContentDimensions(browser);
- }
- }
-
- is(dims.window.innerWidth, 800, "Panel window width");
- ok(body.clientWidth <= 800, `Panel body width ${body.clientWidth} is less than 800`);
- is(body.scrollWidth, 1400, "Panel body scroll width");
-
- is(dims.window.innerHeight, 600, "Panel window height");
- ok(root.clientHeight <= 600, `Panel root height (${root.clientHeight}px) is less than 600px`);
- is(root.scrollHeight, 1400, "Panel root scroll height");
-
- yield extension.unload();
-});
-
-add_task(function* testPageActionPopupReflow() {
- let browser;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- },
- background: function() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- const tabId = tabs[0].id;
-
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("action-shown");
- });
- });
- },
-
- files: {
- "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head>
- <body>
- The quick mauve fox jumps over the opalescent toad, with its glowing
- eyes, and its vantablack mouth, and its bottomless chasm where you
- would hope to find a heart, that looks straight into the deepest
- pits of hell. The fox shivers, and cowers, and tries to run, but
- the toad is utterly without pity. It turns, ever so slightly...
- </body>
- </html>`,
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("action-shown");
-
- clickPageAction(extension, window);
-
- browser = yield awaitExtensionPanel(extension);
-
- /* eslint-disable mozilla/no-cpows-in-tests */
- function setSize(size) {
- content.document.body.style.fontSize = `${size}px`;
- }
- /* eslint-enable mozilla/no-cpows-in-tests */
-
- let dims = yield alterContent(browser, setSize, 18);
-
- if (AppConstants.platform == "win") {
- while (dims.window.innerWidth < 800) {
- yield delay(50);
- dims = yield promiseContentDimensions(browser);
- }
- }
-
- is(dims.window.innerWidth, 800, "Panel window should be 800px wide");
- is(dims.body.clientWidth, 800, "Panel body should be 800px wide");
- is(dims.body.clientWidth, dims.body.scrollWidth,
- "Panel body should be wide enough to fit its contents");
-
- ok(dims.window.innerHeight > 36,
- `Panel window height (${dims.window.innerHeight}px) should be taller than two lines of text.`);
-
- is(dims.body.clientHeight, dims.body.scrollHeight,
- "Panel body should be tall enough to fit its contents");
- is(dims.root.clientHeight, dims.root.scrollHeight,
- "Panel root should be tall enough to fit its contents");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js b/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js
deleted file mode 100644
index d1d173801..000000000
--- a/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "page_action": {
- "default_popup": "popup.html",
- "unrecognized_property": "with-a-random-value",
- },
- },
-
- files: {
- "popup.html": `
- <!DOCTYPE html>
- <html><body>
- <script src="popup.js"></script>
- </body></html>
- `,
-
- "popup.js": function() {
- browser.runtime.sendMessage("from-popup");
- },
- },
-
- background: function() {
- browser.runtime.onMessage.addListener(msg => {
- browser.test.assertEq(msg, "from-popup", "correct message received");
- browser.test.sendMessage("popup");
- });
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- let tabId = tabs[0].id;
-
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("page-action-shown");
- });
- });
- },
- });
-
- SimpleTest.waitForExplicitFinish();
- let waitForConsole = new Promise(resolve => {
- SimpleTest.monitorConsole(resolve, [{
- message: /Reading manifest: Error processing page_action.unrecognized_property: An unexpected property was found/,
- }]);
- });
-
- yield extension.startup();
- yield extension.awaitMessage("page-action-shown");
-
- clickPageAction(extension);
-
- yield extension.awaitMessage("popup");
-
- yield extension.unload();
-
- SimpleTest.endMonitorConsole();
- yield waitForConsole;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_title.js b/browser/components/extensions/test/browser/browser_ext_pageAction_title.js
deleted file mode 100644
index 793cd4499..000000000
--- a/browser/components/extensions/test/browser/browser_ext_pageAction_title.js
+++ /dev/null
@@ -1,226 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* global runTests */
-
-Services.scriptloader.loadSubScript(new URL("head_pageAction.js", gTestPath).href,
- this);
-
-add_task(function* testTabSwitchContext() {
- yield runTests({
- manifest: {
- "name": "Foo Extension",
-
- "page_action": {
- "default_icon": "default.png",
- "default_popup": "__MSG_popup__",
- "default_title": "Default __MSG_title__ \u263a",
- },
-
- "default_locale": "en",
-
- "permissions": ["tabs"],
- },
-
- "files": {
- "_locales/en/messages.json": {
- "popup": {
- "message": "default.html",
- "description": "Popup",
- },
-
- "title": {
- "message": "Title",
- "description": "Title",
- },
- },
-
- "_locales/es_ES/messages.json": {
- "popup": {
- "message": "default.html",
- "description": "Popup",
- },
-
- "title": {
- "message": "T\u00edtulo",
- "description": "Title",
- },
- },
-
- "default.png": imageBuffer,
- "1.png": imageBuffer,
- "2.png": imageBuffer,
- },
-
- getTests(tabs) {
- let details = [
- {"icon": browser.runtime.getURL("default.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default T\u00edtulo \u263a"},
- {"icon": browser.runtime.getURL("1.png"),
- "popup": browser.runtime.getURL("default.html"),
- "title": "Default T\u00edtulo \u263a"},
- {"icon": browser.runtime.getURL("2.png"),
- "popup": browser.runtime.getURL("2.html"),
- "title": "Title 2"},
- {"icon": browser.runtime.getURL("2.png"),
- "popup": browser.runtime.getURL("2.html"),
- "title": "Default T\u00edtulo \u263a"},
- ];
-
- let promiseTabLoad = details => {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changed) {
- if (tabId == details.id && changed.url == details.url) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- };
- return [
- expect => {
- browser.test.log("Initial state. No icon visible.");
- expect(null);
- },
- async expect => {
- browser.test.log("Show the icon on the first tab, expect default properties.");
- await browser.pageAction.show(tabs[0]);
- expect(details[0]);
- },
- expect => {
- browser.test.log("Change the icon. Expect default properties excluding the icon.");
- browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"});
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Create a new tab. No icon visible.");
- let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
- tabs.push(tab.id);
- expect(null);
- },
- expect => {
- browser.test.log("Await tab load. No icon visible.");
- expect(null);
- },
- async expect => {
- browser.test.log("Change properties. Expect new properties.");
- let tabId = tabs[1];
-
- await browser.pageAction.show(tabId);
- browser.pageAction.setIcon({tabId, path: "2.png"});
- browser.pageAction.setPopup({tabId, popup: "2.html"});
- browser.pageAction.setTitle({tabId, title: "Title 2"});
-
- expect(details[2]);
- },
- async expect => {
- browser.test.log("Change the hash. Expect same properties.");
-
- let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"});
-
- browser.tabs.update(tabs[1], {url: "about:blank?0#ref"});
-
- await promise;
- expect(details[2]);
- },
- expect => {
- browser.test.log("Clear the title. Expect default title.");
- browser.pageAction.setTitle({tabId: tabs[1], title: ""});
-
- expect(details[3]);
- },
- async expect => {
- browser.test.log("Navigate to a new page. Expect icon hidden.");
-
- // TODO: This listener should not be necessary, but the |tabs.update|
- // callback currently fires too early in e10s windows.
- let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"});
-
- browser.tabs.update(tabs[1], {url: "about:blank?1"});
-
- await promise;
- expect(null);
- },
- async expect => {
- browser.test.log("Show the icon. Expect default properties again.");
- await browser.pageAction.show(tabs[1]);
- expect(details[0]);
- },
- async expect => {
- browser.test.log("Switch back to the first tab. Expect previously set properties.");
- await browser.tabs.update(tabs[0], {active: true});
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Hide the icon on tab 2. Switch back, expect hidden.");
- await browser.pageAction.hide(tabs[1]);
- await browser.tabs.update(tabs[1], {active: true});
- expect(null);
- },
- async expect => {
- browser.test.log("Switch back to tab 1. Expect previous results again.");
- await browser.tabs.remove(tabs[1]);
- expect(details[1]);
- },
- async expect => {
- browser.test.log("Hide the icon. Expect hidden.");
- await browser.pageAction.hide(tabs[0]);
- expect(null);
- },
- ];
- },
- });
-});
-
-add_task(function* testDefaultTitle() {
- yield runTests({
- manifest: {
- "name": "Foo Extension",
-
- "page_action": {
- "default_icon": "icon.png",
- },
-
- "permissions": ["tabs"],
- },
-
- files: {
- "icon.png": imageBuffer,
- },
-
- getTests(tabs) {
- let details = [
- {"title": "Foo Extension",
- "popup": "",
- "icon": browser.runtime.getURL("icon.png")},
- {"title": "Foo Title",
- "popup": "",
- "icon": browser.runtime.getURL("icon.png")},
- ];
-
- return [
- expect => {
- browser.test.log("Initial state. No icon visible.");
- expect(null);
- },
- async expect => {
- browser.test.log("Show the icon on the first tab, expect extension title as default title.");
- await browser.pageAction.show(tabs[0]);
- expect(details[0]);
- },
- expect => {
- browser.test.log("Change the title. Expect new title.");
- browser.pageAction.setTitle({tabId: tabs[0], title: "Foo Title"});
- expect(details[1]);
- },
- expect => {
- browser.test.log("Clear the title. Expect extension title.");
- browser.pageAction.setTitle({tabId: tabs[0], title: ""});
- expect(details[0]);
- },
- ];
- },
- });
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js b/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js
deleted file mode 100644
index 6f8a541a9..000000000
--- a/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testPageActionPopup() {
- const BASE = "http://example.com/browser/browser/components/extensions/test/browser";
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": `${BASE}/file_popup_api_injection_a.html`,
- },
- "page_action": {
- "default_popup": `${BASE}/file_popup_api_injection_b.html`,
- },
- },
-
- files: {
- "popup-a.html": `<html><head><meta charset="utf-8">
- <script type="application/javascript" src="popup-a.js"></script></head></html>`,
- "popup-a.js": 'browser.test.sendMessage("from-popup-a");',
-
- "popup-b.html": `<html><head><meta charset="utf-8">
- <script type="application/javascript" src="popup-b.js"></script></head></html>`,
- "popup-b.js": 'browser.test.sendMessage("from-popup-b");',
- },
-
- background: function() {
- let tabId;
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- tabId = tabs[0].id;
- browser.pageAction.show(tabId).then(() => {
- browser.test.sendMessage("ready");
- });
- });
-
- browser.test.onMessage.addListener(() => {
- browser.browserAction.setPopup({popup: "/popup-a.html"});
- browser.pageAction.setPopup({tabId, popup: "popup-b.html"});
-
- browser.test.sendMessage("ok");
- });
- },
- });
-
- let promiseConsoleMessage = pattern => new Promise(resolve => {
- Services.console.registerListener(function listener(msg) {
- if (pattern.test(msg.message)) {
- resolve(msg.message);
- Services.console.unregisterListener(listener);
- }
- });
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
-
- // Check that unprivileged documents don't get the API.
- // BrowserAction:
- let awaitMessage = promiseConsoleMessage(/WebExt Privilege Escalation: BrowserAction/);
- SimpleTest.expectUncaughtException();
- yield clickBrowserAction(extension);
- yield promisePopupShown(getBrowserActionPopup(extension));
-
- let message = yield awaitMessage;
- ok(message.includes("WebExt Privilege Escalation: BrowserAction: typeof(browser) = undefined"),
- `No BrowserAction API injection`);
-
- yield closeBrowserAction(extension);
-
- // PageAction
- awaitMessage = promiseConsoleMessage(/WebExt Privilege Escalation: PageAction/);
- SimpleTest.expectUncaughtException();
- yield clickPageAction(extension);
-
- message = yield awaitMessage;
- ok(message.includes("WebExt Privilege Escalation: PageAction: typeof(browser) = undefined"),
- `No PageAction API injection: ${message}`);
-
- yield closePageAction(extension);
-
- SimpleTest.expectUncaughtException(false);
-
-
- // Check that privileged documents *do* get the API.
- extension.sendMessage("next");
- yield extension.awaitMessage("ok");
-
-
- yield clickBrowserAction(extension);
- yield extension.awaitMessage("from-popup-a");
- yield promisePopupShown(getBrowserActionPopup(extension));
- yield closeBrowserAction(extension);
-
- yield clickPageAction(extension);
- yield extension.awaitMessage("from-popup-b");
- yield closePageAction(extension);
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_popup_background.js b/browser/components/extensions/test/browser/browser_ext_popup_background.js
deleted file mode 100644
index 8b310c674..000000000
--- a/browser/components/extensions/test/browser/browser_ext_popup_background.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testPopupBackground() {
- let extension = ExtensionTestUtils.loadExtension({
- background() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- browser.pageAction.show(tabs[0].id);
- });
- },
-
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
-
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
- },
-
- files: {
- "popup.html": `<!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body style="width: 100px; height: 100px; background-color: green;">
- </body>
- </html>`,
- },
- });
-
- yield extension.startup();
-
- function* testPanel(browser, standAlone) {
- let panel = getPanelForNode(browser);
- let arrowContent = document.getAnonymousElementByAttribute(panel, "class", "panel-arrowcontent");
- let arrow = document.getAnonymousElementByAttribute(panel, "anonid", "arrow");
-
- let borderColor = getComputedStyle(arrowContent).borderTopColor;
-
- let checkArrow = (background = null) => {
- let image = getComputedStyle(arrow).listStyleImage;
-
- if (background == null || !standAlone) {
- ok(image.startsWith('url("chrome://'), `We should have the built-in background image (got: ${image})`);
- return;
- }
-
- if (AppConstants.platform == "mac") {
- // Panels have a drop shadow rather than a border on OS-X, so we extend
- // the background color through the border area instead.
- borderColor = background;
- }
-
- image = decodeURIComponent(image);
- let borderIndex = image.indexOf(`fill="${borderColor}"`);
- let backgroundIndex = image.lastIndexOf(`fill="${background}"`);
-
- ok(borderIndex >= 0, `Have border fill (index=${borderIndex})`);
- ok(backgroundIndex >= 0, `Have background fill (index=${backgroundIndex})`);
- is(getComputedStyle(arrowContent).backgroundColor, background, "Arrow content should have correct background");
- isnot(borderIndex, backgroundIndex, "Border and background fills are separate elements");
- };
-
- function getBackground(browser) {
- return ContentTask.spawn(browser, null, function* () {
- return content.getComputedStyle(content.document.body)
- .backgroundColor;
- });
- }
-
- /* eslint-disable mozilla/no-cpows-in-tests */
- let setBackground = color => {
- content.document.body.style.backgroundColor = color;
- };
- /* eslint-enable mozilla/no-cpows-in-tests */
-
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- info("Test that initial background color is applied");
-
- checkArrow(yield getBackground(browser));
-
- info("Test that dynamically-changed background color is applied");
-
- yield alterContent(browser, setBackground, "black");
-
- checkArrow(yield getBackground(browser));
-
- info("Test that non-opaque background color results in default styling");
-
- yield alterContent(browser, setBackground, "rgba(1, 2, 3, .9)");
-
- checkArrow(null);
- }
-
- {
- info("Test stand-alone browserAction popup");
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser, true);
- yield closeBrowserAction(extension);
- }
-
- {
- info("Test menu panel browserAction popup");
-
- let widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL);
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser, false);
- yield closeBrowserAction(extension);
- }
-
- {
- info("Test pageAction popup");
-
- clickPageAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser, true);
- yield closePageAction(extension);
- }
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_popup_corners.js b/browser/components/extensions/test/browser/browser_ext_popup_corners.js
deleted file mode 100644
index 52985ee46..000000000
--- a/browser/components/extensions/test/browser/browser_ext_popup_corners.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testPopupBorderRadius() {
- let extension = ExtensionTestUtils.loadExtension({
- background() {
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- browser.pageAction.show(tabs[0].id);
- });
- },
-
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
-
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
- },
-
- files: {
- "popup.html": `<!DOCTYPE html>
- <html>
- <head><meta charset="utf-8"></head>
- <body style="width: 100px; height: 100px;"></body>
- </html>`,
- },
- });
-
- yield extension.startup();
-
- function* testPanel(browser, standAlone = true) {
- let panel = getPanelForNode(browser);
- let arrowContent = document.getAnonymousElementByAttribute(panel, "class", "panel-arrowcontent");
-
- let panelStyle = getComputedStyle(arrowContent);
-
- let viewNode = browser.parentNode === panel ? browser : browser.parentNode;
- let viewStyle = getComputedStyle(viewNode);
-
- let props = ["borderTopLeftRadius", "borderTopRightRadius",
- "borderBottomRightRadius", "borderBottomLeftRadius"];
-
- /* eslint-disable mozilla/no-cpows-in-tests */
- let bodyStyle = yield ContentTask.spawn(browser, props, function* (props) {
- let bodyStyle = content.getComputedStyle(content.document.body);
-
- return new Map(props.map(prop => [prop, bodyStyle[prop]]));
- });
- /* eslint-enable mozilla/no-cpows-in-tests */
-
- for (let prop of props) {
- if (standAlone) {
- is(viewStyle[prop], panelStyle[prop], `Panel and view ${prop} should be the same`);
- is(bodyStyle.get(prop), panelStyle[prop], `Panel and body ${prop} should be the same`);
- } else {
- is(viewStyle[prop], "0px", `View node ${prop} should be 0px`);
- is(bodyStyle.get(prop), "0px", `Body node ${prop} should be 0px`);
- }
- }
- }
-
- {
- info("Test stand-alone browserAction popup");
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser);
- yield closeBrowserAction(extension);
- }
-
- {
- info("Test menu panel browserAction popup");
-
- let widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL);
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser, false);
- yield closeBrowserAction(extension);
- }
-
- {
- info("Test pageAction popup");
-
- clickPageAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- yield testPanel(browser);
- yield closePageAction(extension);
- }
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js b/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js
deleted file mode 100644
index 472ee7bbd..000000000
--- a/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* test_popup_sendMessage_reply() {
- let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>${url}</body></html>`;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
-
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": true,
- },
- },
-
- files: {
- "popup.html": scriptPage("popup.js"),
- "popup.js": async function() {
- browser.runtime.onMessage.addListener(async msg => {
- if (msg == "popup-ping") {
- return Promise.resolve("popup-pong");
- }
- });
-
- let response = await browser.runtime.sendMessage("background-ping");
- browser.test.sendMessage("background-ping-response", response);
- },
- },
-
- async background() {
- browser.runtime.onMessage.addListener(async msg => {
- if (msg == "background-ping") {
- let response = await browser.runtime.sendMessage("popup-ping");
-
- browser.test.sendMessage("popup-ping-response", response);
-
- await new Promise(resolve => {
- // Wait long enough that we're relatively sure the docShells have
- // been swapped. Note that this value is fairly arbitrary. The load
- // event that triggers the swap should happen almost immediately
- // after the message is sent. The extra quarter of a second gives us
- // enough leeway that we can expect to respond after the swap in the
- // vast majority of cases.
- setTimeout(resolve, 250);
- });
-
- return "background-pong";
- }
- });
-
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
-
- await browser.pageAction.show(tab.id);
-
- browser.test.sendMessage("page-action-ready");
- },
- });
-
- yield extension.startup();
-
- {
- clickBrowserAction(extension);
-
- let pong = yield extension.awaitMessage("background-ping-response");
- is(pong, "background-pong", "Got pong");
-
- pong = yield extension.awaitMessage("popup-ping-response");
- is(pong, "popup-pong", "Got pong");
-
- yield closeBrowserAction(extension);
- }
-
- yield extension.awaitMessage("page-action-ready");
-
- {
- clickPageAction(extension);
-
- let pong = yield extension.awaitMessage("background-ping-response");
- is(pong, "background-pong", "Got pong");
-
- pong = yield extension.awaitMessage("popup-ping-response");
- is(pong, "popup-pong", "Got pong");
-
- yield closePageAction(extension);
- }
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js b/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js
deleted file mode 100644
index 66d37e857..000000000
--- a/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-let getExtension = () => {
- return ExtensionTestUtils.loadExtension({
- background: async function() {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- await browser.pageAction.show(tab.id);
- browser.test.sendMessage("pageAction ready");
- },
-
- manifest: {
- "browser_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
-
- "page_action": {
- "default_popup": "popup.html",
- "browser_style": false,
- },
- },
-
- files: {
- "popup.html": `<!DOCTYPE html>
- <html><head><meta charset="utf-8"></head></html>`,
- },
- });
-};
-
-add_task(function* testStandaloneBrowserAction() {
- info("Test stand-alone browserAction popup");
-
- let extension = getExtension();
- yield extension.startup();
- yield extension.awaitMessage("pageAction ready");
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- let panel = getPanelForNode(browser);
-
- yield extension.unload();
-
- is(panel.parentNode, null, "Panel should be removed from the document");
-});
-
-add_task(function* testMenuPanelBrowserAction() {
- let extension = getExtension();
- yield extension.startup();
- yield extension.awaitMessage("pageAction ready");
-
- let widget = getBrowserActionWidget(extension);
- CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL);
-
- clickBrowserAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- let panel = getPanelForNode(browser);
-
- yield extension.unload();
-
- is(panel.state, "closed", "Panel should be closed");
-});
-
-add_task(function* testPageAction() {
- let extension = getExtension();
- yield extension.startup();
- yield extension.awaitMessage("pageAction ready");
-
- clickPageAction(extension);
- let browser = yield awaitExtensionPanel(extension);
- let panel = getPanelForNode(browser);
-
- yield extension.unload();
-
- is(panel.parentNode, null, "Panel should be removed from the document");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js b/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js
deleted file mode 100644
index 1631ececa..000000000
--- a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js
+++ /dev/null
@@ -1,276 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-requestLongerTimeout(2);
-
-function add_tasks(task) {
- add_task(task.bind(null, {embedded: false}));
-
- add_task(task.bind(null, {embedded: true}));
-}
-
-function* loadExtension(options) {
- let extension = ExtensionTestUtils.loadExtension({
- useAddonManager: "temporary",
-
- embedded: options.embedded,
-
- manifest: Object.assign({
- "permissions": ["tabs"],
- }, options.manifest),
-
- files: {
- "options.html": `<!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script src="options.js" type="text/javascript"></script>
- </head>
- </html>`,
-
- "options.js": function() {
- window.iAmOption = true;
- browser.runtime.sendMessage("options.html");
- browser.runtime.onMessage.addListener((msg, sender, respond) => {
- if (msg == "ping") {
- respond("pong");
- }
- });
- },
- },
-
- background: options.background,
- });
-
- yield extension.startup();
-
- return extension;
-}
-
-add_tasks(function* test_inline_options(extraOptions) {
- info(`Test options opened inline (${JSON.stringify(extraOptions)})`);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- let extension = yield loadExtension(Object.assign({}, extraOptions, {
- manifest: {
- applications: {gecko: {id: "inline_options@tests.mozilla.org"}},
- "options_ui": {
- "page": "options.html",
- },
- },
-
- background: async function() {
- let _optionsPromise;
- let awaitOptions = () => {
- browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
-
- return new Promise(resolve => {
- _optionsPromise = {resolve};
- });
- };
-
- browser.runtime.onMessage.addListener((msg, sender) => {
- if (msg == "options.html") {
- if (_optionsPromise) {
- _optionsPromise.resolve(sender.tab);
- _optionsPromise = null;
- } else {
- browser.test.fail("Saw unexpected options page load");
- }
- }
- });
-
- try {
- let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
-
- browser.test.log("Open options page. Expect fresh load.");
-
- let [, optionsTab] = await Promise.all([
- browser.runtime.openOptionsPage(),
- awaitOptions(),
- ]);
-
- browser.test.assertEq("about:addons", optionsTab.url, "Tab contains AddonManager");
- browser.test.assertTrue(optionsTab.active, "Tab is active");
- browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab");
-
- browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup");
- browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab");
- browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches");
-
- let views = browser.extension.getViews();
- browser.test.assertEq(2, views.length, "Expected the options page and the background page");
- browser.test.assertTrue(views.includes(window), "One of the views is the background page");
- browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page");
-
- browser.test.log("Switch tabs.");
- await browser.tabs.update(firstTab.id, {active: true});
-
- browser.test.log("Open options page again. Expect tab re-selected, no new load.");
-
- await browser.runtime.openOptionsPage();
- let [tab] = await browser.tabs.query({currentWindow: true, active: true});
-
- browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab");
- browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
-
- browser.test.log("Ping options page.");
- let pong = await browser.runtime.sendMessage("ping");
- browser.test.assertEq("pong", pong, "Got pong.");
-
- browser.test.log("Remove options tab.");
- await browser.tabs.remove(optionsTab.id);
-
- browser.test.log("Open options page again. Expect fresh load.");
- [, tab] = await Promise.all([
- browser.runtime.openOptionsPage(),
- awaitOptions(),
- ]);
- browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
- browser.test.assertTrue(tab.active, "Tab is active");
- browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab");
-
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("options-ui");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("options-ui");
- }
- },
- }));
-
- yield extension.awaitFinish("options-ui");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_tasks(function* test_tab_options(extraOptions) {
- info(`Test options opened in a tab (${JSON.stringify(extraOptions)})`);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- let extension = yield loadExtension(Object.assign({}, extraOptions, {
- manifest: {
- applications: {gecko: {id: "tab_options@tests.mozilla.org"}},
- "options_ui": {
- "page": "options.html",
- "open_in_tab": true,
- },
- },
-
- background: async function() {
- let _optionsPromise;
- let awaitOptions = () => {
- browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
-
- return new Promise(resolve => {
- _optionsPromise = {resolve};
- });
- };
-
- browser.runtime.onMessage.addListener((msg, sender) => {
- if (msg == "options.html") {
- if (_optionsPromise) {
- _optionsPromise.resolve(sender.tab);
- _optionsPromise = null;
- } else {
- browser.test.fail("Saw unexpected options page load");
- }
- }
- });
-
- let optionsURL = browser.extension.getURL("options.html");
-
- try {
- let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
-
- browser.test.log("Open options page. Expect fresh load.");
- let [, optionsTab] = await Promise.all([
- browser.runtime.openOptionsPage(),
- awaitOptions(),
- ]);
- browser.test.assertEq(optionsURL, optionsTab.url, "Tab contains options.html");
- browser.test.assertTrue(optionsTab.active, "Tab is active");
- browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab");
-
- browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup");
- browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab");
- browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches");
-
- let views = browser.extension.getViews();
- browser.test.assertEq(2, views.length, "Expected the options page and the background page");
- browser.test.assertTrue(views.includes(window), "One of the views is the background page");
- browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page");
-
- browser.test.log("Switch tabs.");
- await browser.tabs.update(firstTab.id, {active: true});
-
- browser.test.log("Open options page again. Expect tab re-selected, no new load.");
-
- await browser.runtime.openOptionsPage();
- let [tab] = await browser.tabs.query({currentWindow: true, active: true});
-
- browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab");
- browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html");
-
- // Unfortunately, we can't currently do this, since onMessage doesn't
- // currently support responses when there are multiple listeners.
- //
- // browser.test.log("Ping options page.");
- // return new Promise(resolve => browser.runtime.sendMessage("ping", resolve));
-
- browser.test.log("Remove options tab.");
- await browser.tabs.remove(optionsTab.id);
-
- browser.test.log("Open options page again. Expect fresh load.");
- [, tab] = await Promise.all([
- browser.runtime.openOptionsPage(),
- awaitOptions(),
- ]);
- browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html");
- browser.test.assertTrue(tab.active, "Tab is active");
- browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab");
-
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("options-ui-tab");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("options-ui-tab");
- }
- },
- }));
-
- yield extension.awaitFinish("options-ui-tab");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_tasks(function* test_options_no_manifest(extraOptions) {
- info(`Test with no manifest key (${JSON.stringify(extraOptions)})`);
-
- let extension = yield loadExtension(Object.assign({}, extraOptions, {
- manifest: {
- applications: {gecko: {id: "no_options@tests.mozilla.org"}},
- },
-
- async background() {
- browser.test.log("Try to open options page when not specified in the manifest.");
-
- await browser.test.assertRejects(
- browser.runtime.openOptionsPage(),
- /No `options_ui` declared/,
- "Expected error from openOptionsPage()");
-
- browser.test.notifyPass("options-no-manifest");
- },
- }));
-
- yield extension.awaitFinish("options-no-manifest");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js b/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js
deleted file mode 100644
index 0c123b70e..000000000
--- a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* loadExtension(options) {
- let extension = ExtensionTestUtils.loadExtension({
- useAddonManager: "temporary",
-
- manifest: Object.assign({
- "permissions": ["tabs"],
- }, options.manifest),
-
- files: {
- "options.html": `<!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script src="options.js" type="text/javascript"></script>
- </head>
- </html>`,
-
- "options.js": function() {
- browser.runtime.sendMessage("options.html");
- browser.runtime.onMessage.addListener((msg, sender, respond) => {
- if (msg == "ping") {
- respond("pong");
- }
- });
- },
- },
-
- background: options.background,
- });
-
- yield extension.startup();
-
- return extension;
-}
-
-add_task(function* test_inline_options_uninstall() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- let extension = yield loadExtension({
- manifest: {
- applications: {gecko: {id: "inline_options_uninstall@tests.mozilla.org"}},
- "options_ui": {
- "page": "options.html",
- },
- },
-
- background: async function() {
- let _optionsPromise;
- let awaitOptions = () => {
- browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
-
- return new Promise(resolve => {
- _optionsPromise = {resolve};
- });
- };
-
- browser.runtime.onMessage.addListener((msg, sender) => {
- if (msg == "options.html") {
- if (_optionsPromise) {
- _optionsPromise.resolve(sender.tab);
- _optionsPromise = null;
- } else {
- browser.test.fail("Saw unexpected options page load");
- }
- }
- });
-
- try {
- let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
-
- browser.test.log("Open options page. Expect fresh load.");
- let [, tab] = await Promise.all([
- browser.runtime.openOptionsPage(),
- awaitOptions(),
- ]);
-
- browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
- browser.test.assertTrue(tab.active, "Tab is active");
- browser.test.assertTrue(tab.id != firstTab.id, "Tab is a new tab");
-
- browser.test.sendMessage("options-ui-open");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- }
- },
- });
-
- yield extension.awaitMessage("options-ui-open");
- yield extension.unload();
-
- is(gBrowser.selectedBrowser.currentURI.spec, "about:addons",
- "Add-on manager tab should still be open");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js b/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js
deleted file mode 100644
index 1c7ef4969..000000000
--- a/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js
+++ /dev/null
@@ -1,94 +0,0 @@
-"use strict";
-
-let {AddonManager} = Components.utils.import("resource://gre/modules/AddonManager.jsm", {});
-let {Extension} = Components.utils.import("resource://gre/modules/Extension.jsm", {});
-
-function* makeAndInstallXPI(id, backgroundScript, loadedURL) {
- let xpi = Extension.generateXPI({
- manifest: {applications: {gecko: {id}}},
- background: backgroundScript,
- });
- SimpleTest.registerCleanupFunction(function cleanupXPI() {
- Services.obs.notifyObservers(xpi, "flush-cache-entry", null);
- xpi.remove(false);
- });
-
- let loadPromise = BrowserTestUtils.waitForNewTab(gBrowser, loadedURL);
-
-
- info(`installing ${xpi.path}`);
- let addon = yield AddonManager.installTemporaryAddon(xpi);
- info("installed");
-
- // A WebExtension is started asynchronously, we have our test extension
- // open a new tab to signal that the background script has executed.
- let loadTab = yield loadPromise;
- yield BrowserTestUtils.removeTab(loadTab);
-
- return addon;
-}
-
-
-add_task(function* test_setuninstallurl_badargs() {
- async function background() {
- await browser.test.assertRejects(
- browser.runtime.setUninstallURL("this is not a url"),
- /Invalid URL/,
- "setUninstallURL with an invalid URL should fail");
-
- await browser.test.assertRejects(
- browser.runtime.setUninstallURL("file:///etc/passwd"),
- /must have the scheme http or https/,
- "setUninstallURL with an illegal URL should fail");
-
- browser.test.notifyPass("setUninstallURL bad params");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background,
- });
- yield extension.startup();
- yield extension.awaitFinish();
- yield extension.unload();
-});
-
-// Test the documented behavior of setUninstallURL() that passing an
-// empty string is equivalent to not setting an uninstall URL
-// (i.e., no new tab is opened upon uninstall)
-add_task(function* test_setuninstall_empty_url() {
- async function backgroundScript() {
- await browser.runtime.setUninstallURL("");
- browser.tabs.create({url: "http://example.com/addon_loaded"});
- }
-
- let addon = yield makeAndInstallXPI("test_uinstallurl2@tests.mozilla.org",
- backgroundScript,
- "http://example.com/addon_loaded");
-
- addon.uninstall(true);
- info("uninstalled");
-
- // no need to explicitly check for the absence of a new tab,
- // BrowserTestUtils will eventually complain if one is opened.
-});
-
-add_task(function* test_setuninstallurl() {
- async function backgroundScript() {
- await browser.runtime.setUninstallURL("http://example.com/addon_uninstalled");
- browser.tabs.create({url: "http://example.com/addon_loaded"});
- }
-
- let addon = yield makeAndInstallXPI("test_uinstallurl@tests.mozilla.org",
- backgroundScript,
- "http://example.com/addon_loaded");
-
- // look for a new tab with the uninstall url.
- let uninstallPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://example.com/addon_uninstalled");
-
- addon.uninstall(true);
- info("uninstalled");
-
- let uninstalledTab = yield uninstallPromise;
- isnot(uninstalledTab, null, "opened tab with uninstall url");
- yield BrowserTestUtils.removeTab(uninstalledTab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js
deleted file mode 100644
index 413f7bde6..000000000
--- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* globals recordInitialTimestamps, onlyNewItemsFilter, checkRecentlyClosed */
-
-requestLongerTimeout(2);
-
-Services.scriptloader.loadSubScript(new URL("head_sessions.js", gTestPath).href,
- this);
-
-add_task(function* test_sessions_get_recently_closed() {
- function* openAndCloseWindow(url = "http://example.com", tabUrls) {
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, url);
- yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
- if (tabUrls) {
- for (let url of tabUrls) {
- yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url);
- }
- }
- yield BrowserTestUtils.closeWindow(win);
- }
-
- function background() {
- Promise.all([
- browser.sessions.getRecentlyClosed(),
- browser.tabs.query({active: true, currentWindow: true}),
- ]).then(([recentlyClosed, tabs]) => {
- browser.test.sendMessage("initialData", {recentlyClosed, currentWindowId: tabs[0].windowId});
- });
-
- browser.test.onMessage.addListener((msg, filter) => {
- if (msg == "check-sessions") {
- browser.sessions.getRecentlyClosed(filter).then(recentlyClosed => {
- browser.test.sendMessage("recentlyClosed", recentlyClosed);
- });
- }
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["sessions", "tabs"],
- },
- background,
- });
-
- // Open and close a window that will be ignored, to prove that we are removing previous entries
- yield openAndCloseWindow();
-
- yield extension.startup();
-
- let {recentlyClosed, currentWindowId} = yield extension.awaitMessage("initialData");
- recordInitialTimestamps(recentlyClosed.map(item => item.lastModified));
-
- yield openAndCloseWindow();
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 1, currentWindowId);
-
- yield openAndCloseWindow("about:config", ["about:robots", "about:mozilla"]);
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- // Check for multiple tabs in most recently closed window
- is(recentlyClosed[0].window.tabs.length, 3, "most recently closed window has the expected number of tabs");
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
- yield BrowserTestUtils.removeTab(tab);
-
- tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
- yield BrowserTestUtils.removeTab(tab);
-
- yield openAndCloseWindow();
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- let finalResult = recentlyClosed.filter(onlyNewItemsFilter);
- checkRecentlyClosed(finalResult, 5, currentWindowId);
-
- isnot(finalResult[0].window, undefined, "first item is a window");
- is(finalResult[0].tab, undefined, "first item is not a tab");
- isnot(finalResult[1].tab, undefined, "second item is a tab");
- is(finalResult[1].window, undefined, "second item is not a window");
- isnot(finalResult[2].tab, undefined, "third item is a tab");
- is(finalResult[2].window, undefined, "third item is not a window");
- isnot(finalResult[3].window, undefined, "fourth item is a window");
- is(finalResult[3].tab, undefined, "fourth item is not a tab");
- isnot(finalResult[4].window, undefined, "fifth item is a window");
- is(finalResult[4].tab, undefined, "fifth item is not a tab");
-
- // test with filter
- extension.sendMessage("check-sessions", {maxResults: 2});
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 2, currentWindowId);
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js
deleted file mode 100644
index 217c8e130..000000000
--- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* globals recordInitialTimestamps, onlyNewItemsFilter, checkRecentlyClosed */
-
-SimpleTest.requestCompleteLog();
-
-Services.scriptloader.loadSubScript(new URL("head_sessions.js", gTestPath).href,
- this);
-
-add_task(function* test_sessions_get_recently_closed_private() {
- function background() {
- browser.test.onMessage.addListener((msg, filter) => {
- if (msg == "check-sessions") {
- browser.sessions.getRecentlyClosed(filter).then(recentlyClosed => {
- browser.test.sendMessage("recentlyClosed", recentlyClosed);
- });
- }
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["sessions", "tabs"],
- },
- background,
- });
-
- // Open a private browsing window.
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- yield extension.startup();
-
- let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
- let privateWinId = WindowManager.getId(privateWin);
-
- extension.sendMessage("check-sessions");
- let recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- recordInitialTimestamps(recentlyClosed.map(item => item.lastModified));
-
- // Open and close two tabs in the private window
- let tab = yield BrowserTestUtils.openNewForegroundTab(privateWin.gBrowser, "http://example.com");
- yield BrowserTestUtils.removeTab(tab);
-
- tab = yield BrowserTestUtils.openNewForegroundTab(privateWin.gBrowser, "http://example.com");
- yield BrowserTestUtils.removeTab(tab);
-
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 2, privateWinId, true);
-
- // Close the private window.
- yield BrowserTestUtils.closeWindow(privateWin);
-
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- is(recentlyClosed.filter(onlyNewItemsFilter).length, 0, "the closed private window info was not found in recently closed data");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js
deleted file mode 100644
index ae0daff9a..000000000
--- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function expectedTabInfo(tab, window) {
- let browser = tab.linkedBrowser;
- return {
- url: browser.currentURI.spec,
- title: browser.contentTitle,
- favIconUrl: window.gBrowser.getIcon(tab),
- };
-}
-
-function checkTabInfo(expected, actual) {
- for (let prop in expected) {
- is(actual[prop], expected[prop], `Expected value found for ${prop} of tab object.`);
- }
-}
-
-add_task(async function test_sessions_get_recently_closed_tabs() {
- async function background() {
- browser.test.onMessage.addListener(async msg => {
- if (msg == "check-sessions") {
- let recentlyClosed = await browser.sessions.getRecentlyClosed();
- browser.test.sendMessage("recentlyClosed", recentlyClosed);
- }
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["sessions", "tabs"],
- },
- background,
- });
-
- let win = await BrowserTestUtils.openNewBrowserWindow();
- await BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "about:addons");
- await BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
- let expectedTabs = [];
- let tab = win.gBrowser.selectedTab;
- expectedTabs.push(expectedTabInfo(tab, win));
-
- for (let url of ["about:robots", "about:mozilla"]) {
- tab = await BrowserTestUtils.openNewForegroundTab(win.gBrowser, url);
- expectedTabs.push(expectedTabInfo(tab, win));
- }
-
- await extension.startup();
-
- // Test with a closed tab.
- await BrowserTestUtils.removeTab(tab);
-
- extension.sendMessage("check-sessions");
- let recentlyClosed = await extension.awaitMessage("recentlyClosed");
- let tabInfo = recentlyClosed[0].tab;
- let expectedTab = expectedTabs.pop();
- checkTabInfo(expectedTab, tabInfo);
-
- // Test with a closed window containing tabs.
- await BrowserTestUtils.closeWindow(win);
-
- extension.sendMessage("check-sessions");
- recentlyClosed = await extension.awaitMessage("recentlyClosed");
- let tabInfos = recentlyClosed[0].window.tabs;
- is(tabInfos.length, 2, "Expected number of tabs in closed window.");
- for (let x = 0; x < tabInfos.length; x++) {
- checkTabInfo(expectedTabs[x], tabInfos[x]);
- }
-
- await extension.unload();
-
- // Test without tabs permission.
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["sessions"],
- },
- background,
- });
-
- await extension.startup();
-
- extension.sendMessage("check-sessions");
- recentlyClosed = await extension.awaitMessage("recentlyClosed");
- tabInfos = recentlyClosed[0].window.tabs;
- is(tabInfos.length, 2, "Expected number of tabs in closed window.");
- for (let tabInfo of tabInfos) {
- for (let prop in expectedTabs[0]) {
- is(undefined,
- tabInfo[prop],
- `${prop} of tab object is undefined without tabs permission.`);
- }
- }
-
- await extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_restore.js b/browser/components/extensions/test/browser/browser_ext_sessions_restore.js
deleted file mode 100644
index 6f1c6cf9a..000000000
--- a/browser/components/extensions/test/browser/browser_ext_sessions_restore.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-SimpleTest.requestCompleteLog();
-
-XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
- "resource:///modules/sessionstore/SessionStore.jsm");
-
-add_task(function* test_sessions_restore() {
- function background() {
- browser.test.onMessage.addListener((msg, data) => {
- if (msg == "check-sessions") {
- browser.sessions.getRecentlyClosed().then(recentlyClosed => {
- browser.test.sendMessage("recentlyClosed", recentlyClosed);
- });
- } else if (msg == "restore") {
- browser.sessions.restore(data).then(sessions => {
- browser.test.sendMessage("restored", sessions);
- });
- } else if (msg == "restore-reject") {
- browser.sessions.restore("not-a-valid-session-id").then(
- sessions => {
- browser.test.fail("restore rejected with an invalid sessionId");
- },
- error => {
- browser.test.assertTrue(
- error.message.includes("Could not restore object using sessionId not-a-valid-session-id."));
- browser.test.sendMessage("restore-rejected");
- }
- );
- }
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["sessions", "tabs"],
- },
- background,
- });
-
- yield extension.startup();
-
- let {Management: {global: {WindowManager, TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- function checkLocalTab(tab, expectedUrl) {
- let realTab = TabManager.getTab(tab.id);
- let tabState = JSON.parse(SessionStore.getTabState(realTab));
- is(tabState.entries[0].url, expectedUrl, "restored tab has the expected url");
- }
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "about:config");
- yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
- for (let url of ["about:robots", "about:mozilla"]) {
- yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url);
- }
- yield BrowserTestUtils.closeWindow(win);
-
- extension.sendMessage("check-sessions");
- let recentlyClosed = yield extension.awaitMessage("recentlyClosed");
-
- // Check that our expected window is the most recently closed.
- is(recentlyClosed[0].window.tabs.length, 3, "most recently closed window has the expected number of tabs");
-
- // Restore the window.
- extension.sendMessage("restore");
- let restored = yield extension.awaitMessage("restored");
-
- is(restored.length, 1, "restore returned the expected number of sessions");
- is(restored[0].window.tabs.length, 3, "restore returned a window with the expected number of tabs");
- checkLocalTab(restored[0].window.tabs[0], "about:config");
- checkLocalTab(restored[0].window.tabs[1], "about:robots");
- checkLocalTab(restored[0].window.tabs[2], "about:mozilla");
-
- // Close the window again.
- let window = WindowManager.getWindow(restored[0].window.id);
- yield BrowserTestUtils.closeWindow(window);
-
- // Restore the window using the sessionId.
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- extension.sendMessage("restore", recentlyClosed[0].window.sessionId);
- restored = yield extension.awaitMessage("restored");
-
- is(restored.length, 1, "restore returned the expected number of sessions");
- is(restored[0].window.tabs.length, 3, "restore returned a window with the expected number of tabs");
- checkLocalTab(restored[0].window.tabs[0], "about:config");
- checkLocalTab(restored[0].window.tabs[1], "about:robots");
- checkLocalTab(restored[0].window.tabs[2], "about:mozilla");
-
- // Close the window again.
- window = WindowManager.getWindow(restored[0].window.id);
- yield BrowserTestUtils.closeWindow(window);
-
- // Open and close a tab.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots");
- yield BrowserTestUtils.removeTab(tab);
-
- // Restore the most recently closed item.
- extension.sendMessage("restore");
- restored = yield extension.awaitMessage("restored");
-
- is(restored.length, 1, "restore returned the expected number of sessions");
- tab = restored[0].tab;
- ok(tab, "restore returned a tab");
- checkLocalTab(tab, "about:robots");
-
- // Close the tab again.
- let realTab = TabManager.getTab(tab.id);
- yield BrowserTestUtils.removeTab(realTab);
-
- // Restore the tab using the sessionId.
- extension.sendMessage("check-sessions");
- recentlyClosed = yield extension.awaitMessage("recentlyClosed");
- extension.sendMessage("restore", recentlyClosed[0].tab.sessionId);
- restored = yield extension.awaitMessage("restored");
-
- is(restored.length, 1, "restore returned the expected number of sessions");
- tab = restored[0].tab;
- ok(tab, "restore returned a tab");
- checkLocalTab(tab, "about:robots");
-
- // Close the tab again.
- realTab = TabManager.getTab(tab.id);
- yield BrowserTestUtils.removeTab(realTab);
-
- // Try to restore something with an invalid sessionId.
- extension.sendMessage("restore-reject");
- restored = yield extension.awaitMessage("restore-rejected");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_simple.js b/browser/components/extensions/test/browser/browser_ext_simple.js
deleted file mode 100644
index ffa00c9db..000000000
--- a/browser/components/extensions/test/browser/browser_ext_simple.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* test_simple() {
- let extensionData = {
- manifest: {
- "name": "Simple extension test",
- "version": "1.0",
- "manifest_version": 2,
- "description": "",
- },
- };
-
- let extension = ExtensionTestUtils.loadExtension(extensionData);
- info("load complete");
- yield extension.startup();
- info("startup complete");
- yield extension.unload();
- info("extension unloaded successfully");
-});
-
-add_task(function* test_background() {
- function backgroundScript() {
- browser.test.log("running background script");
-
- browser.test.onMessage.addListener((x, y) => {
- browser.test.assertEq(x, 10, "x is 10");
- browser.test.assertEq(y, 20, "y is 20");
-
- browser.test.notifyPass("background test passed");
- });
-
- browser.test.sendMessage("running", 1);
- }
-
- let extensionData = {
- background: "(" + backgroundScript.toString() + ")()",
- manifest: {
- "name": "Simple extension test",
- "version": "1.0",
- "manifest_version": 2,
- "description": "",
- },
- };
-
- let extension = ExtensionTestUtils.loadExtension(extensionData);
- info("load complete");
- let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
- is(x, 1, "got correct value from extension");
- info("startup complete");
- extension.sendMessage(10, 20);
- yield extension.awaitFinish();
- info("test complete");
- yield extension.unload();
- info("extension unloaded successfully");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js b/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js
deleted file mode 100644
index a5541a002..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- let messages_received = [];
-
- let tabId;
-
- browser.runtime.onConnect.addListener((port) => {
- browser.test.assertTrue(!!port, "tab to background port received");
- browser.test.assertEq("tab-connection-name", port.name, "port name should be defined and equal to connectInfo.name");
- browser.test.assertTrue(!!port.sender.tab, "port.sender.tab should be defined");
- browser.test.assertEq(tabId, port.sender.tab.id, "port.sender.tab.id should be equal to the expected tabId");
-
- port.onMessage.addListener((msg) => {
- messages_received.push(msg);
-
- if (messages_received.length == 1) {
- browser.test.assertEq("tab to background port message", msg, "'tab to background' port message received");
- port.postMessage("background to tab port message");
- }
-
- if (messages_received.length == 2) {
- browser.test.assertTrue(!!msg.tabReceived, "'background to tab' reply port message received");
- browser.test.assertEq("background to tab port message", msg.tabReceived, "reply port content contains the message received");
-
- browser.test.notifyPass("tabRuntimeConnect.pass");
- }
- });
- });
-
- browser.tabs.create({url: "tab.html"},
- (tab) => { tabId = tab.id; });
- },
-
- files: {
- "tab.js": function() {
- let port = browser.runtime.connect({name: "tab-connection-name"});
- port.postMessage("tab to background port message");
- port.onMessage.addListener((msg) => {
- port.postMessage({tabReceived: msg});
- });
- },
- "tab.html": `
- <!DOCTYPE html>
- <html>
- <head>
- <title>test tab extension page</title>
- <meta charset="utf-8">
- <script src="tab.js" async></script>
- </head>
- <body>
- <h1>test tab extension page</h1>
- </body>
- </html>
- `,
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabRuntimeConnect.pass");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_audio.js b/browser/components/extensions/test/browser/browser_ext_tabs_audio.js
deleted file mode 100644
index f9f6956d4..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_audio.js
+++ /dev/null
@@ -1,203 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank?1");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank?2");
-
- gBrowser.selectedTab = tab1;
-
- async function background() {
- function promiseUpdated(tabId, attr) {
- return new Promise(resolve => {
- let onUpdated = (tabId_, changeInfo, tab) => {
- if (tabId == tabId_ && attr in changeInfo) {
- browser.tabs.onUpdated.removeListener(onUpdated);
-
- resolve({changeInfo, tab});
- }
- };
- browser.tabs.onUpdated.addListener(onUpdated);
- });
- }
-
- let deferred = {};
- browser.test.onMessage.addListener((message, tabId, result) => {
- if (message == "change-tab-done" && deferred[tabId]) {
- deferred[tabId].resolve(result);
- }
- });
-
- function changeTab(tabId, attr, on) {
- return new Promise((resolve, reject) => {
- deferred[tabId] = {resolve, reject};
- browser.test.sendMessage("change-tab", tabId, attr, on);
- });
- }
-
-
- try {
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
- browser.test.assertEq(tabs.length, 3, "We have three tabs");
-
- for (let tab of tabs) {
- // Note: We want to check that these are actual boolean values, not
- // just that they evaluate as false.
- browser.test.assertEq(false, tab.mutedInfo.muted, "Tab is not muted");
- browser.test.assertEq(undefined, tab.mutedInfo.reason, "Tab has no muted info reason");
- browser.test.assertEq(false, tab.audible, "Tab is not audible");
- }
-
- let windowId = tabs[0].windowId;
- let tabIds = [tabs[1].id, tabs[2].id];
-
- browser.test.log("Test initial queries for muted and audible return no tabs");
- let silent = await browser.tabs.query({windowId, audible: false});
- let audible = await browser.tabs.query({windowId, audible: true});
- let muted = await browser.tabs.query({windowId, muted: true});
- let nonMuted = await browser.tabs.query({windowId, muted: false});
-
- browser.test.assertEq(3, silent.length, "Three silent tabs");
- browser.test.assertEq(0, audible.length, "No audible tabs");
-
- browser.test.assertEq(0, muted.length, "No muted tabs");
- browser.test.assertEq(3, nonMuted.length, "Three non-muted tabs");
-
- browser.test.log("Toggle muted and audible externally on one tab each, and check results");
- [muted, audible] = await Promise.all([
- promiseUpdated(tabIds[0], "mutedInfo"),
- promiseUpdated(tabIds[1], "audible"),
- changeTab(tabIds[0], "muted", true),
- changeTab(tabIds[1], "audible", true),
- ]);
-
- for (let obj of [muted.changeInfo, muted.tab]) {
- browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted");
- browser.test.assertEq("user", obj.mutedInfo.reason, "Tab was muted by the user");
- }
-
- browser.test.assertEq(true, audible.changeInfo.audible, "Tab audible state changed");
- browser.test.assertEq(true, audible.tab.audible, "Tab is audible");
-
- browser.test.log("Re-check queries. Expect one audible and one muted tab");
- silent = await browser.tabs.query({windowId, audible: false});
- audible = await browser.tabs.query({windowId, audible: true});
- muted = await browser.tabs.query({windowId, muted: true});
- nonMuted = await browser.tabs.query({windowId, muted: false});
-
- browser.test.assertEq(2, silent.length, "Two silent tabs");
- browser.test.assertEq(1, audible.length, "One audible tab");
-
- browser.test.assertEq(1, muted.length, "One muted tab");
- browser.test.assertEq(2, nonMuted.length, "Two non-muted tabs");
-
- browser.test.assertEq(true, muted[0].mutedInfo.muted, "Tab is muted");
- browser.test.assertEq("user", muted[0].mutedInfo.reason, "Tab was muted by the user");
-
- browser.test.assertEq(true, audible[0].audible, "Tab is audible");
-
- browser.test.log("Toggle muted internally on two tabs, and check results");
- [nonMuted, muted] = await Promise.all([
- promiseUpdated(tabIds[0], "mutedInfo"),
- promiseUpdated(tabIds[1], "mutedInfo"),
- browser.tabs.update(tabIds[0], {muted: false}),
- browser.tabs.update(tabIds[1], {muted: true}),
- ]);
-
- for (let obj of [nonMuted.changeInfo, nonMuted.tab]) {
- browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted");
- }
- for (let obj of [muted.changeInfo, muted.tab]) {
- browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted");
- }
-
- for (let obj of [nonMuted.changeInfo, nonMuted.tab, muted.changeInfo, muted.tab]) {
- browser.test.assertEq("extension", obj.mutedInfo.reason, "Mute state changed by extension");
-
- // FIXME: browser.runtime.id is currently broken.
- browser.test.assertEq(browser.i18n.getMessage("@@extension_id"),
- obj.mutedInfo.extensionId,
- "Mute state changed by extension");
- }
-
- browser.test.log("Test that mutedInfo is preserved by sessionstore");
- let tab = await changeTab(tabIds[1], "duplicate").then(browser.tabs.get);
-
- browser.test.assertEq(true, tab.mutedInfo.muted, "Tab is muted");
-
- browser.test.assertEq("extension", tab.mutedInfo.reason, "Mute state changed by extension");
-
- // FIXME: browser.runtime.id is currently broken.
- browser.test.assertEq(browser.i18n.getMessage("@@extension_id"),
- tab.mutedInfo.extensionId,
- "Mute state changed by extension");
-
- browser.test.log("Unmute externally, and check results");
- [nonMuted] = await Promise.all([
- promiseUpdated(tabIds[1], "mutedInfo"),
- changeTab(tabIds[1], "muted", false),
- browser.tabs.remove(tab.id),
- ]);
-
- for (let obj of [nonMuted.changeInfo, nonMuted.tab]) {
- browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted");
- browser.test.assertEq("user", obj.mutedInfo.reason, "Mute state changed by user");
- }
-
- browser.test.notifyPass("tab-audio");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("tab-audio");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- extension.onMessage("change-tab", (tabId, attr, on) => {
- let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let tab = TabManager.getTab(tabId);
-
- if (attr == "muted") {
- // Ideally we'd simulate a click on the tab audio icon for this, but the
- // handler relies on CSS :hover states, which are complicated and fragile
- // to simulate.
- if (tab.muted != on) {
- tab.toggleMuteAudio();
- }
- } else if (attr == "audible") {
- let browser = tab.linkedBrowser;
- if (on) {
- browser.audioPlaybackStarted();
- } else {
- browser.audioPlaybackStopped();
- }
- } else if (attr == "duplicate") {
- // This is a bit of a hack. It won't be necessary once we have
- // `tabs.duplicate`.
- let newTab = gBrowser.duplicateTab(tab);
- BrowserTestUtils.waitForEvent(newTab, "SSTabRestored", () => true).then(() => {
- extension.sendMessage("change-tab-done", tabId, TabManager.getId(newTab));
- });
- return;
- }
-
- extension.sendMessage("change-tab-done", tabId);
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("tab-audio");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js b/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js
deleted file mode 100644
index 1491a19ab..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js
+++ /dev/null
@@ -1,155 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* runTest(options) {
- options.neutral = [0xaa, 0xaa, 0xaa];
-
- let html = `
- <!DOCTYPE html>
- <html lang="en">
- <head><meta charset="UTF-8"></head>
- <body style="background-color: rgb(${options.color})">
- <!-- Fill most of the image with a neutral color to test edge-to-edge scaling. -->
- <div style="position: absolute;
- left: 2px;
- right: 2px;
- top: 2px;
- bottom: 2px;
- background: rgb(${options.neutral});"></div>
- </body>
- </html>
- `;
-
- let url = `data:text/html,${encodeURIComponent(html)}`;
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, true);
-
- tab.linkedBrowser.fullZoom = options.fullZoom;
-
- async function background(options) {
- browser.test.log(`Test color ${options.color} at fullZoom=${options.fullZoom}`);
-
- try {
- let [tab] = await browser.tabs.query({currentWindow: true, active: true});
-
- let [jpeg, png, ...pngs] = await Promise.all([
- browser.tabs.captureVisibleTab(tab.windowId, {format: "jpeg", quality: 95}),
- browser.tabs.captureVisibleTab(tab.windowId, {format: "png", quality: 95}),
- browser.tabs.captureVisibleTab(tab.windowId, {quality: 95}),
- browser.tabs.captureVisibleTab(tab.windowId),
- ]);
-
- browser.test.assertTrue(pngs.every(url => url == png), "All PNGs are identical");
-
- browser.test.assertTrue(jpeg.startsWith("data:image/jpeg;base64,"), "jpeg is JPEG");
- browser.test.assertTrue(png.startsWith("data:image/png;base64,"), "png is PNG");
-
- let promises = [jpeg, png].map(url => new Promise(resolve => {
- let img = new Image();
- img.src = url;
- img.onload = () => resolve(img);
- }));
-
- [jpeg, png] = await Promise.all(promises);
- let tabDims = `${tab.width}\u00d7${tab.height}`;
-
- let images = {jpeg, png};
- for (let format of Object.keys(images)) {
- let img = images[format];
-
- let dims = `${img.width}\u00d7${img.height}`;
- browser.test.assertEq(tabDims, dims, `${format} dimensions are correct`);
-
- let canvas = document.createElement("canvas");
- canvas.width = img.width;
- canvas.height = img.height;
- canvas.mozOpaque = true;
-
- let ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0);
-
- // Check the colors of the first and last pixels of the image, to make
- // sure we capture the entire frame, and scale it correctly.
- let coords = [
- {x: 0, y: 0,
- color: options.color},
- {x: img.width - 1,
- y: img.height - 1,
- color: options.color},
- {x: img.width / 2 | 0,
- y: img.height / 2 | 0,
- color: options.neutral},
- ];
-
- for (let {x, y, color} of coords) {
- let imageData = ctx.getImageData(x, y, 1, 1).data;
-
- if (format == "png") {
- browser.test.assertEq(`rgba(${color},255)`, `rgba(${[...imageData]})`, `${format} image color is correct at (${x}, ${y})`);
- } else {
- // Allow for some deviation in JPEG version due to lossy compression.
- const SLOP = 3;
-
- browser.test.log(`Testing ${format} image color at (${x}, ${y}), have rgba(${[...imageData]}), expecting approx. rgba(${color},255)`);
-
- browser.test.assertTrue(Math.abs(color[0] - imageData[0]) <= SLOP, `${format} image color.red is correct at (${x}, ${y})`);
- browser.test.assertTrue(Math.abs(color[1] - imageData[1]) <= SLOP, `${format} image color.green is correct at (${x}, ${y})`);
- browser.test.assertTrue(Math.abs(color[2] - imageData[2]) <= SLOP, `${format} image color.blue is correct at (${x}, ${y})`);
- browser.test.assertEq(255, imageData[3], `${format} image color.alpha is correct at (${x}, ${y})`);
- }
- }
- }
-
- browser.test.notifyPass("captureVisibleTab");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("captureVisibleTab");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["<all_urls>"],
- },
-
- background: `(${background})(${JSON.stringify(options)})`,
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("captureVisibleTab");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-}
-
-add_task(function* testCaptureVisibleTab() {
- yield runTest({color: [0, 0, 0], fullZoom: 1});
-
- yield runTest({color: [0, 0, 0], fullZoom: 2});
-
- yield runTest({color: [0, 0, 0], fullZoom: 0.5});
-
- yield runTest({color: [255, 255, 255], fullZoom: 1});
-});
-
-add_task(function* testCaptureVisibleTabPermissions() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background() {
- browser.test.assertFalse("captureVisibleTab" in browser.tabs,
- 'Extension without "<all_tabs>" permission should not have access to captureVisibleTab');
- browser.test.notifyPass("captureVisibleTabPermissions");
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("captureVisibleTabPermissions");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js b/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js
deleted file mode 100644
index dc0647e3c..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js
+++ /dev/null
@@ -1,156 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* setup() {
- // make sure userContext is enabled.
- return SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true],
- ]});
-});
-
-add_task(function* () {
- info("Start testing tabs.create with cookieStoreId");
-
- let testCases = [
- // No private window
- {privateTab: false, cookieStoreId: null, success: true, expectedCookieStoreId: "firefox-default"},
- {privateTab: false, cookieStoreId: "firefox-default", success: true, expectedCookieStoreId: "firefox-default"},
- {privateTab: false, cookieStoreId: "firefox-container-1", success: true, expectedCookieStoreId: "firefox-container-1"},
- {privateTab: false, cookieStoreId: "firefox-container-2", success: true, expectedCookieStoreId: "firefox-container-2"},
- {privateTab: false, cookieStoreId: "firefox-container-42", failure: "exist"},
- {privateTab: false, cookieStoreId: "firefox-private", failure: "defaultToPrivate"},
- {privateTab: false, cookieStoreId: "wow", failure: "illegal"},
-
- // Private window
- {privateTab: true, cookieStoreId: null, success: true, expectedCookieStoreId: "firefox-private"},
- {privateTab: true, cookieStoreId: "firefox-private", success: true, expectedCookieStoreId: "firefox-private"},
- {privateTab: true, cookieStoreId: "firefox-default", failure: "privateToDefault"},
- {privateTab: true, cookieStoreId: "firefox-container-1", failure: "privateToDefault"},
- {privateTab: true, cookieStoreId: "wow", failure: "illegal"},
- ];
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs", "cookies"],
- },
-
- background: function() {
- function testTab(data, tab) {
- browser.test.assertTrue(data.success, "we want a success");
- browser.test.assertTrue(!!tab, "we have a tab");
- browser.test.assertEq(data.expectedCookieStoreId, tab.cookieStoreId, "tab should have the correct cookieStoreId");
- }
-
- async function runTest(data) {
- try {
- // Tab Creation
- let tab;
- try {
- tab = await browser.tabs.create({
- windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
- cookieStoreId: data.cookieStoreId,
- });
-
- browser.test.assertTrue(!data.failure, "we want a success");
- } catch (error) {
- browser.test.assertTrue(!!data.failure, "we want a failure");
-
- if (data.failure == "illegal") {
- browser.test.assertTrue(/Illegal cookieStoreId/.test(error.message),
- "runtime.lastError should report the expected error message");
- } else if (data.failure == "defaultToPrivate") {
- browser.test.assertTrue("Illegal to set private cookieStorageId in a non private window",
- error.message,
- "runtime.lastError should report the expected error message");
- } else if (data.failure == "privateToDefault") {
- browser.test.assertTrue("Illegal to set non private cookieStorageId in a private window",
- error.message,
- "runtime.lastError should report the expected error message");
- } else if (data.failure == "exist") {
- browser.test.assertTrue(/No cookie store exists/.test(error.message),
- "runtime.lastError should report the expected error message");
- } else {
- browser.test.fail("The test is broken");
- }
-
- browser.test.sendMessage("test-done");
- return;
- }
-
- // Tests for tab creation
- testTab(data, tab);
-
- {
- // Tests for tab querying
- let [tab] = await browser.tabs.query({
- windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
- cookieStoreId: data.cookieStoreId,
- });
-
- browser.test.assertTrue(tab != undefined, "Tab found!");
- testTab(data, tab);
- }
-
- let stores = await browser.cookies.getAllCookieStores();
-
- let store = stores.find(store => store.id === tab.cookieStoreId);
- browser.test.assertTrue(!!store, "We have a store for this tab.");
-
- await browser.tabs.remove(tab.id);
-
- browser.test.sendMessage("test-done");
- } catch (e) {
- browser.test.fail("An exception has been thrown");
- }
- }
-
- async function initialize() {
- let win = await browser.windows.create({incognito: true});
- this.privateWindowId = win.id;
-
- win = await browser.windows.create({incognito: false});
- this.defaultWindowId = win.id;
-
- browser.test.sendMessage("ready");
- }
-
- async function shutdown() {
- await browser.windows.remove(this.privateWindowId);
- await browser.windows.remove(this.defaultWindowId);
- browser.test.sendMessage("gone");
- }
-
- // Waiting for messages
- browser.test.onMessage.addListener((msg, data) => {
- if (msg == "be-ready") {
- initialize();
- } else if (msg == "test") {
- runTest(data);
- } else {
- browser.test.assertTrue("finish", msg, "Shutting down");
- shutdown();
- }
- });
- },
- });
-
- yield extension.startup();
-
- info("Tests must be ready...");
- extension.sendMessage("be-ready");
- yield extension.awaitMessage("ready");
- info("Tests are ready to run!");
-
- for (let test of testCases) {
- info(`test tab.create with cookieStoreId: "${test.cookieStoreId}"`);
- extension.sendMessage("test", test);
- yield extension.awaitMessage("test-done");
- }
-
- info("Waiting for shutting down...");
- extension.sendMessage("finish");
- yield extension.awaitMessage("gone");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_create.js b/browser/components/extensions/test/browser/browser_ext_tabs_create.js
deleted file mode 100644
index 8bc5a68a2..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_create.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots");
- gBrowser.selectedTab = tab;
-
- // TODO: Multiple windows.
-
- // Using pre-loaded new tab pages interferes with onUpdated events.
- // It probably shouldn't.
- SpecialPowers.setBoolPref("browser.newtab.preload", false);
- registerCleanupFunction(() => {
- SpecialPowers.clearUserPref("browser.newtab.preload");
- });
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "background": {"page": "bg/background.html"},
- },
-
- files: {
- "bg/blank.html": `<html><head><meta charset="utf-8"></head></html>`,
-
- "bg/background.html": `<html><head>
- <meta charset="utf-8">
- <script src="background.js"></script>
- </head></html>`,
-
- "bg/background.js": function() {
- let activeTab;
- let activeWindow;
-
- function runTests() {
- const DEFAULTS = {
- index: 2,
- windowId: activeWindow,
- active: true,
- pinned: false,
- url: "about:newtab",
- };
-
- let tests = [
- {
- create: {url: "http://example.com/"},
- result: {url: "http://example.com/"},
- },
- {
- create: {url: "blank.html"},
- result: {url: browser.runtime.getURL("bg/blank.html")},
- },
- {
- create: {},
- result: {url: "about:newtab"},
- },
- {
- create: {active: false},
- result: {active: false},
- },
- {
- create: {active: true},
- result: {active: true},
- },
- {
- create: {pinned: true},
- result: {pinned: true, index: 0},
- },
- {
- create: {pinned: true, active: true},
- result: {pinned: true, active: true, index: 0},
- },
- {
- create: {pinned: true, active: false},
- result: {pinned: true, active: false, index: 0},
- },
- {
- create: {index: 1},
- result: {index: 1},
- },
- {
- create: {index: 1, active: false},
- result: {index: 1, active: false},
- },
- {
- create: {windowId: activeWindow},
- result: {windowId: activeWindow},
- },
- ];
-
- async function nextTest() {
- if (!tests.length) {
- browser.test.notifyPass("tabs.create");
- return;
- }
-
- let test = tests.shift();
- let expected = Object.assign({}, DEFAULTS, test.result);
-
- browser.test.log(`Testing tabs.create(${JSON.stringify(test.create)}), expecting ${JSON.stringify(test.result)}`);
-
- let updatedPromise = new Promise(resolve => {
- let onUpdated = (changedTabId, changed) => {
- if (changed.url) {
- browser.tabs.onUpdated.removeListener(onUpdated);
- resolve({tabId: changedTabId, url: changed.url});
- }
- };
- browser.tabs.onUpdated.addListener(onUpdated);
- });
-
- let createdPromise = new Promise(resolve => {
- let onCreated = tab => {
- browser.test.assertTrue("id" in tab, `Expected tabs.onCreated callback to receive tab object`);
- resolve();
- };
- browser.tabs.onCreated.addListener(onCreated);
- });
-
- let [tab] = await Promise.all([
- browser.tabs.create(test.create),
- createdPromise,
- ]);
- let tabId = tab.id;
-
- for (let key of Object.keys(expected)) {
- if (key === "url") {
- // FIXME: This doesn't get updated until later in the load cycle.
- continue;
- }
-
- browser.test.assertEq(expected[key], tab[key], `Expected value for tab.${key}`);
- }
-
- let updated = await updatedPromise;
- browser.test.assertEq(tabId, updated.tabId, `Expected value for tab.id`);
- browser.test.assertEq(expected.url, updated.url, `Expected value for tab.url`);
-
- await browser.tabs.remove(tabId);
- await browser.tabs.update(activeTab, {active: true});
-
- nextTest();
- }
-
- nextTest();
- }
-
- browser.tabs.query({active: true, currentWindow: true}, tabs => {
- activeTab = tabs[0].id;
- activeWindow = tabs[0].windowId;
-
- runTests();
- });
- },
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.create");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js b/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js
deleted file mode 100644
index 49938bf22..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* testTabsCreateInvalidURL(tabsCreateURL) {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.test.sendMessage("ready");
- browser.test.onMessage.addListener((msg, tabsCreateURL) => {
- browser.tabs.create({url: tabsCreateURL}, (tab) => {
- browser.test.assertEq(undefined, tab, "on error tab should be undefined");
- browser.test.assertTrue(/Illegal URL/.test(browser.runtime.lastError.message),
- "runtime.lastError should report the expected error message");
-
- // Remove the opened tab is any.
- if (tab) {
- browser.tabs.remove(tab.id);
- }
- browser.test.sendMessage("done");
- });
- });
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("ready");
-
- info(`test tab.create on invalid URL "${tabsCreateURL}"`);
-
- extension.sendMessage("start", tabsCreateURL);
- yield extension.awaitMessage("done");
-
- yield extension.unload();
-}
-
-add_task(function* () {
- info("Start testing tabs.create on invalid URLs");
-
- let dataURLPage = `data:text/html,
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <h1>data url page</h1>
- </body>
- </html>`;
-
- let testCases = [
- {tabsCreateURL: "about:addons"},
- {tabsCreateURL: "javascript:console.log('tabs.update execute javascript')"},
- {tabsCreateURL: dataURLPage},
- ];
-
- for (let {tabsCreateURL} of testCases) {
- yield* testTabsCreateInvalidURL(tabsCreateURL);
- }
-
- info("done");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js b/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js
deleted file mode 100644
index f28606001..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testDetectLanguage() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: async function() {
- const BASE_PATH = "browser/browser/components/extensions/test/browser";
-
- function loadTab(url) {
- return browser.tabs.create({url});
- }
-
- try {
- let tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_ja.html`);
- let lang = await browser.tabs.detectLanguage(tab.id);
- browser.test.assertEq("ja", lang, "Japanese document should be detected as Japanese");
- await browser.tabs.remove(tab.id);
-
- tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_fr_en.html`);
- lang = await browser.tabs.detectLanguage(tab.id);
- browser.test.assertEq("fr", lang, "French/English document should be detected as primarily French");
- await browser.tabs.remove(tab.id);
-
- tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_tlh.html`);
- lang = await browser.tabs.detectLanguage(tab.id);
- browser.test.assertEq("und", lang, "Klingon document should not be detected, should return 'und'");
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("detectLanguage");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("detectLanguage");
- }
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("detectLanguage");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js b/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js
deleted file mode 100644
index c4b0ffd2d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testDuplicateTab() {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- lastFocusedWindow: true,
- }, function(tabs) {
- let source = tabs[1];
- // By moving it 0, we check that the new tab is created next
- // to the existing one.
- browser.tabs.move(source.id, {index: 0}, () => {
- browser.tabs.duplicate(source.id, (tab) => {
- browser.test.assertEq("http://example.net/", tab.url);
- // Should be the second tab, next to the one duplicated.
- browser.test.assertEq(1, tab.index);
- // Should be selected by default.
- browser.test.assertTrue(tab.selected);
- browser.test.notifyPass("tabs.duplicate");
- });
- });
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.duplicate");
- yield extension.unload();
-
- while (gBrowser.tabs[0].linkedBrowser.currentURI.spec === "http://example.net/") {
- yield BrowserTestUtils.removeTab(gBrowser.tabs[0]);
- }
-});
-
-add_task(function* testDuplicateTabLazily() {
- async function background() {
- let tabLoadComplete = new Promise(resolve => {
- browser.test.onMessage.addListener((message, tabId, result) => {
- if (message == "duplicate-tab-done") {
- resolve(tabId);
- }
- });
- });
-
- function awaitLoad(tabId) {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) {
- if (tabId == tabId_ && changed.status == "complete") {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- }
-
- try {
- let url = "http://example.com/browser/browser/components/extensions/test/browser/file_dummy.html";
- let tab = await browser.tabs.create({url});
- let startTabId = tab.id;
-
- await awaitLoad(startTabId);
- browser.test.sendMessage("duplicate-tab", startTabId);
-
- let unloadedTabId = await tabLoadComplete;
- let loadedtab = await browser.tabs.get(startTabId);
- browser.test.assertEq("Dummy test page", loadedtab.title, "Title should be returned for loaded pages");
- browser.test.assertEq("complete", loadedtab.status, "Tab status should be complete for loaded pages");
-
- let unloadedtab = await browser.tabs.get(unloadedTabId);
- browser.test.assertEq("Dummy test page", unloadedtab.title, "Title should be returned after page has been unloaded");
-
- await browser.tabs.remove([tab.id, unloadedTabId]);
- browser.test.notifyPass("tabs.hasCorrectTabTitle");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("tabs.hasCorrectTabTitle");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- extension.onMessage("duplicate-tab", tabId => {
- let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let tab = TabManager.getTab(tabId);
- // This is a bit of a hack to load a tab in the background.
- let newTab = gBrowser.duplicateTab(tab, false);
-
- BrowserTestUtils.waitForEvent(newTab, "SSTabRestored", () => true).then(() => {
- extension.sendMessage("duplicate-tab-done", TabManager.getId(newTab));
- });
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.hasCorrectTabTitle");
- yield extension.unload();
-});
-
-add_task(function* testDuplicatePinnedTab() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
- gBrowser.pinTab(tab);
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- lastFocusedWindow: true,
- }, function(tabs) {
- // Duplicate the pinned tab, example.net.
- browser.tabs.duplicate(tabs[0].id, (tab) => {
- browser.test.assertEq("http://example.net/", tab.url);
- // Should be the second tab, next to the one duplicated.
- browser.test.assertEq(1, tab.index);
- // Should be pinned.
- browser.test.assertTrue(tab.pinned);
- browser.test.notifyPass("tabs.duplicate.pinned");
- });
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.duplicate.pinned");
- yield extension.unload();
-
- while (gBrowser.tabs[0].linkedBrowser.currentURI.spec === "http://example.net/") {
- yield BrowserTestUtils.removeTab(gBrowser.tabs[0]);
- }
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_events.js b/browser/components/extensions/test/browser/browser_ext_tabs_events.js
deleted file mode 100644
index 75dea40fd..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_events.js
+++ /dev/null
@@ -1,280 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testTabEvents() {
- async function background() {
- let events = [];
- browser.tabs.onCreated.addListener(tab => {
- events.push({type: "onCreated", tab});
- });
-
- browser.tabs.onAttached.addListener((tabId, info) => {
- events.push(Object.assign({type: "onAttached", tabId}, info));
- });
-
- browser.tabs.onDetached.addListener((tabId, info) => {
- events.push(Object.assign({type: "onDetached", tabId}, info));
- });
-
- browser.tabs.onRemoved.addListener((tabId, info) => {
- events.push(Object.assign({type: "onRemoved", tabId}, info));
- });
-
- browser.tabs.onMoved.addListener((tabId, info) => {
- events.push(Object.assign({type: "onMoved", tabId}, info));
- });
-
- async function expectEvents(names) {
- browser.test.log(`Expecting events: ${names.join(", ")}`);
-
- await new Promise(resolve => setTimeout(resolve, 0));
-
- browser.test.assertEq(names.length, events.length, "Got expected number of events");
- for (let [i, name] of names.entries()) {
- browser.test.assertEq(name, i in events && events[i].type,
- `Got expected ${name} event`);
- }
- return events.splice(0);
- }
-
- try {
- browser.test.log("Create second browser window");
-
- let windows = await Promise.all([
- browser.windows.getCurrent(),
- browser.windows.create({url: "about:blank"}),
- ]);
-
- let windowId = windows[0].id;
- let otherWindowId = windows[1].id;
-
- let [created] = await expectEvents(["onCreated"]);
- let initialTab = created.tab;
-
-
- browser.test.log("Create tab in window 1");
- let tab = await browser.tabs.create({windowId, index: 0, url: "about:blank"});
- let oldIndex = tab.index;
- browser.test.assertEq(0, oldIndex, "Tab has the expected index");
-
- [created] = await expectEvents(["onCreated"]);
- browser.test.assertEq(tab.id, created.tab.id, "Got expected tab ID");
- browser.test.assertEq(oldIndex, created.tab.index, "Got expected tab index");
-
-
- browser.test.log("Move tab to window 2");
- await browser.tabs.move([tab.id], {windowId: otherWindowId, index: 0});
-
- let [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
- browser.test.assertEq(oldIndex, detached.oldPosition, "Expected old index");
- browser.test.assertEq(windowId, detached.oldWindowId, "Expected old window ID");
-
- browser.test.assertEq(0, attached.newPosition, "Expected new index");
- browser.test.assertEq(otherWindowId, attached.newWindowId, "Expected new window ID");
-
-
- browser.test.log("Move tab within the same window");
- let [moved] = await browser.tabs.move([tab.id], {index: 1});
- browser.test.assertEq(1, moved.index, "Expected new index");
-
- [moved] = await expectEvents(["onMoved"]);
- browser.test.assertEq(tab.id, moved.tabId, "Expected tab ID");
- browser.test.assertEq(0, moved.fromIndex, "Expected old index");
- browser.test.assertEq(1, moved.toIndex, "Expected new index");
- browser.test.assertEq(otherWindowId, moved.windowId, "Expected window ID");
-
-
- browser.test.log("Remove tab");
- await browser.tabs.remove(tab.id);
- let [removed] = await expectEvents(["onRemoved"]);
-
- browser.test.assertEq(tab.id, removed.tabId, "Expected removed tab ID");
- browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
- // Note: We want to test for the actual boolean value false here.
- browser.test.assertEq(false, removed.isWindowClosing, "Expected isWindowClosing value");
-
-
- browser.test.log("Close second window");
- await browser.windows.remove(otherWindowId);
- [removed] = await expectEvents(["onRemoved"]);
- browser.test.assertEq(initialTab.id, removed.tabId, "Expected removed tab ID");
- browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
- browser.test.assertEq(true, removed.isWindowClosing, "Expected isWindowClosing value");
-
-
- browser.test.log("Create additional tab in window 1");
- tab = await browser.tabs.create({windowId, url: "about:blank"});
- await expectEvents(["onCreated"]);
-
-
- browser.test.log("Create a new window, adopting the new tab");
- // We have to explicitly wait for the event here, since its timing is
- // not predictable.
- let promiseAttached = new Promise(resolve => {
- browser.tabs.onAttached.addListener(function listener(tabId) {
- browser.tabs.onAttached.removeListener(listener);
- resolve();
- });
- });
-
- let [window] = await Promise.all([
- browser.windows.create({tabId: tab.id}),
- promiseAttached,
- ]);
-
- [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
-
- browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
-
- browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
- browser.test.assertEq(0, attached.newPosition, "Expected onAttached new index");
- browser.test.assertEq(window.id, attached.newWindowId,
- "Expected onAttached new window id");
-
- browser.test.log("Close the new window");
- await browser.windows.remove(window.id);
-
- browser.test.notifyPass("tabs-events");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("tabs-events");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs-events");
- yield extension.unload();
-});
-
-add_task(function* testTabEventsSize() {
- function background() {
- function sendSizeMessages(tab, type) {
- browser.test.sendMessage(`${type}-dims`, {width: tab.width, height: tab.height});
- }
-
- browser.tabs.onCreated.addListener(tab => {
- sendSizeMessages(tab, "on-created");
- });
-
- browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
- if (changeInfo.status == "complete") {
- sendSizeMessages(tab, "on-updated");
- }
- });
-
- browser.test.onMessage.addListener(async (msg, arg) => {
- if (msg === "create-tab") {
- let tab = await browser.tabs.create({url: "http://example.com/"});
- sendSizeMessages(tab, "create");
- browser.test.sendMessage("created-tab-id", tab.id);
- } else if (msg === "update-tab") {
- let tab = await browser.tabs.update(arg, {url: "http://example.org/"});
- sendSizeMessages(tab, "update");
- } else if (msg === "remove-tab") {
- browser.tabs.remove(arg);
- browser.test.sendMessage("tab-removed");
- }
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
- background,
- });
-
- const RESOLUTION_PREF = "layout.css.devPixelsPerPx";
- registerCleanupFunction(() => {
- SpecialPowers.clearUserPref(RESOLUTION_PREF);
- });
-
- function checkDimensions(dims, type) {
- is(dims.width, gBrowser.selectedBrowser.clientWidth, `tab from ${type} reports expected width`);
- is(dims.height, gBrowser.selectedBrowser.clientHeight, `tab from ${type} reports expected height`);
- }
-
- yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
-
- for (let resolution of [2, 1]) {
- SpecialPowers.setCharPref(RESOLUTION_PREF, String(resolution));
- is(window.devicePixelRatio, resolution, "window has the required resolution");
-
- extension.sendMessage("create-tab");
- let tabId = yield extension.awaitMessage("created-tab-id");
-
- checkDimensions(yield extension.awaitMessage("create-dims"), "create");
- checkDimensions(yield extension.awaitMessage("on-created-dims"), "onCreated");
- checkDimensions(yield extension.awaitMessage("on-updated-dims"), "onUpdated");
-
- extension.sendMessage("update-tab", tabId);
-
- checkDimensions(yield extension.awaitMessage("update-dims"), "update");
- checkDimensions(yield extension.awaitMessage("on-updated-dims"), "onUpdated");
-
- extension.sendMessage("remove-tab", tabId);
- yield extension.awaitMessage("tab-removed");
- }
-
- yield extension.unload();
- SpecialPowers.clearUserPref(RESOLUTION_PREF);
-});
-
-add_task(function* testTabRemovalEvent() {
- async function background() {
- function awaitLoad(tabId) {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) {
- if (tabId == tabId_ && changed.status == "complete") {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- }
-
- chrome.tabs.onRemoved.addListener((tabId, info) => {
- browser.test.log("Make sure the removed tab is not available in the tabs.query callback.");
- chrome.tabs.query({}, tabs => {
- for (let tab of tabs) {
- browser.test.assertTrue(tab.id != tabId, "Tab query should not include removed tabId");
- }
- browser.test.notifyPass("tabs-events");
- });
- });
-
- try {
- let url = "http://example.com/browser/browser/components/extensions/test/browser/context.html";
- let tab = await browser.tabs.create({url: url});
- await awaitLoad(tab.id);
-
- await browser.tabs.remove(tab.id);
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("tabs-events");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs-events");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js
deleted file mode 100644
index 5a15f2e39..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js
+++ /dev/null
@@ -1,234 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testExecuteScript() {
- let {MessageChannel} = Cu.import("resource://gre/modules/MessageChannel.jsm", {});
-
- function countMM(messageManagerMap) {
- let count = 0;
- // List of permanent message managers in the main process. We should not
- // count them in the test because MessageChannel unsubscribes when the
- // message manager closes, which never happens to these, of course.
- let globalMMs = [
- Services.mm,
- Services.ppmm,
- Services.ppmm.getChildAt(0),
- ];
- for (let mm of messageManagerMap.keys()) {
- // Sanity check: mm is a message manager.
- try {
- mm.QueryInterface(Ci.nsIMessageSender);
- } catch (e) {
- mm.QueryInterface(Ci.nsIMessageBroadcaster);
- }
- if (!globalMMs.includes(mm)) {
- ++count;
- }
- }
- return count;
- }
-
- let messageManagersSize = countMM(MessageChannel.messageManagers);
- let responseManagersSize = countMM(MessageChannel.responseManagers);
-
- const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
- const URL = BASE + "file_iframe_document.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL, true);
-
- async function background() {
- try {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- let frames = await browser.webNavigation.getAllFrames({tabId: tab.id});
-
- browser.test.log(`FRAMES: ${frames[1].frameId} ${JSON.stringify(frames)}\n`);
- await Promise.all([
- browser.tabs.executeScript({
- code: "42",
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected one callback result");
- browser.test.assertEq(42, result[0], "Expected callback result");
- }),
-
- browser.tabs.executeScript({
- file: "script.js",
- code: "42",
- }).then(result => {
- browser.test.fail("Expected not to be able to execute a script with both file and code");
- }, error => {
- browser.test.assertTrue(/a 'code' or a 'file' property, but not both/.test(error.message),
- "Got expected error");
- }),
-
- browser.tabs.executeScript({
- file: "script.js",
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected one callback result");
- browser.test.assertEq(undefined, result[0], "Expected callback result");
- }),
-
- browser.tabs.executeScript({
- file: "script2.js",
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected one callback result");
- browser.test.assertEq(27, result[0], "Expected callback result");
- }),
-
- browser.tabs.executeScript({
- code: "location.href;",
- allFrames: true,
- }).then(result => {
- browser.test.assertTrue(Array.isArray(result), "Result is an array");
-
- browser.test.assertEq(2, result.length, "Result has correct length");
-
- browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "First result is correct");
- browser.test.assertEq("http://mochi.test:8888/", result[1], "Second result is correct");
- }),
-
- browser.tabs.executeScript({
- code: "location.href;",
- runAt: "document_end",
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected callback result");
- browser.test.assertEq("string", typeof result[0], "Result is a string");
-
- browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "Result is correct");
- }),
-
- browser.tabs.executeScript({
- code: "window",
- }).then(result => {
- browser.test.fail("Expected error when returning non-structured-clonable object");
- }, error => {
- browser.test.assertEq("Script returned non-structured-clonable data",
- error.message, "Got expected error");
- }),
-
- browser.tabs.executeScript({
- code: "Promise.resolve(window)",
- }).then(result => {
- browser.test.fail("Expected error when returning non-structured-clonable object");
- }, error => {
- browser.test.assertEq("Script returned non-structured-clonable data",
- error.message, "Got expected error");
- }),
-
- browser.tabs.executeScript({
- frameId: Number.MAX_SAFE_INTEGER,
- code: "42",
- }).then(result => {
- browser.test.fail("Expected error when specifying invalid frame ID");
- }, error => {
- let details = {
- frame_id: Number.MAX_SAFE_INTEGER,
- matchesHost: ["http://mochi.test/", "http://example.com/"],
- };
- browser.test.assertEq(`No window matching ${JSON.stringify(details)}`,
- error.message, "Got expected error");
- }),
-
- browser.tabs.create({url: "http://example.net/", active: false}).then(async tab => {
- await browser.tabs.executeScript(tab.id, {
- code: "42",
- }).then(result => {
- browser.test.fail("Expected error when trying to execute on invalid domain");
- }, error => {
- let details = {
- matchesHost: ["http://mochi.test/", "http://example.com/"],
- };
- browser.test.assertEq(`No window matching ${JSON.stringify(details)}`,
- error.message, "Got expected error");
- });
-
- await browser.tabs.remove(tab.id);
- }),
-
- browser.tabs.executeScript({
- code: "Promise.resolve(42)",
- }).then(result => {
- browser.test.assertEq(42, result[0], "Got expected promise resolution value as result");
- }),
-
- browser.tabs.executeScript({
- code: "location.href;",
- runAt: "document_end",
- allFrames: true,
- }).then(result => {
- browser.test.assertTrue(Array.isArray(result), "Result is an array");
-
- browser.test.assertEq(2, result.length, "Result has correct length");
-
- browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "First result is correct");
- browser.test.assertEq("http://mochi.test:8888/", result[1], "Second result is correct");
- }),
-
- browser.tabs.executeScript({
- code: "location.href;",
- frameId: frames[0].frameId,
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected one result");
- browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), `Result for frameId[0] is correct: ${result[0]}`);
- }),
-
- browser.tabs.executeScript({
- code: "location.href;",
- frameId: frames[1].frameId,
- }).then(result => {
- browser.test.assertEq(1, result.length, "Expected one result");
- browser.test.assertEq("http://mochi.test:8888/", result[0], "Result for frameId[1] is correct");
- }),
-
- browser.tabs.create({url: "http://example.com/"}).then(async tab => {
- let result = await browser.tabs.executeScript(tab.id, {code: "location.href"});
-
- browser.test.assertEq("http://example.com/", result[0], "Script executed correctly in new tab");
-
- await browser.tabs.remove(tab.id);
- }),
-
- new Promise(resolve => {
- browser.runtime.onMessage.addListener(message => {
- browser.test.assertEq("script ran", message, "Expected runtime message");
- resolve();
- });
- }),
- ]);
-
- browser.test.notifyPass("executeScript");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("executeScript");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/", "http://example.com/", "webNavigation"],
- },
-
- background,
-
- files: {
- "script.js": function() {
- browser.runtime.sendMessage("script ran");
- },
-
- "script2.js": "27",
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("executeScript");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-
- // Make sure that we're not holding on to references to closed message
- // managers.
- is(countMM(MessageChannel.messageManagers), messageManagersSize, "Message manager count");
- is(countMM(MessageChannel.responseManagers), responseManagersSize, "Response manager count");
- is(MessageChannel.pendingResponses.size, 0, "Pending response count");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js
deleted file mode 100644
index d11354ead..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js
+++ /dev/null
@@ -1,217 +0,0 @@
-"use strict";
-
-// This is a pretty terrible hack, but it's the best we can do until we
-// support |executeScript| callbacks and |lastError|.
-function* testHasNoPermission(params) {
- let contentSetup = params.contentSetup || (() => Promise.resolve());
-
- async function background(contentSetup) {
- browser.runtime.onMessage.addListener((msg, sender) => {
- browser.test.assertEq(msg, "second script ran", "second script ran");
- browser.test.notifyPass("executeScript");
- });
-
- browser.test.onMessage.addListener(msg => {
- browser.test.assertEq(msg, "execute-script");
-
- browser.tabs.query({currentWindow: true}, tabs => {
- browser.tabs.executeScript({
- file: "script.js",
- });
-
- // Execute a script we know we have permissions for in the
- // second tab, in the hopes that it will execute after the
- // first one. This has intermittent failure written all over
- // it, but it's just about the best we can do until we
- // support callbacks for executeScript.
- browser.tabs.executeScript(tabs[1].id, {
- file: "second-script.js",
- });
- });
- });
-
- await contentSetup();
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: params.manifest,
-
- background: `(${background})(${contentSetup})`,
-
- files: {
- "script.js": function() {
- browser.runtime.sendMessage("first script ran");
- },
-
- "second-script.js": function() {
- browser.runtime.sendMessage("second script ran");
- },
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- if (params.setup) {
- yield params.setup(extension);
- }
-
- extension.sendMessage("execute-script");
-
- yield extension.awaitFinish("executeScript");
- yield extension.unload();
-}
-
-add_task(function* testBadPermissions() {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/");
-
- info("Test no special permissions");
- yield testHasNoPermission({
- manifest: {"permissions": ["http://example.com/"]},
- });
-
- info("Test tabs permissions");
- yield testHasNoPermission({
- manifest: {"permissions": ["http://example.com/", "tabs"]},
- });
-
- info("Test no special permissions, commands, key press");
- yield testHasNoPermission({
- manifest: {
- "permissions": ["http://example.com/"],
- "commands": {
- "test-tabs-executeScript": {
- "suggested_key": {
- "default": "Alt+Shift+K",
- },
- },
- },
- },
- contentSetup() {
- browser.commands.onCommand.addListener(function(command) {
- if (command == "test-tabs-executeScript") {
- browser.test.sendMessage("tabs-command-key-pressed");
- }
- });
- return Promise.resolve();
- },
- setup: function* (extension) {
- yield EventUtils.synthesizeKey("k", {altKey: true, shiftKey: true});
- yield extension.awaitMessage("tabs-command-key-pressed");
- },
- });
-
- info("Test active tab, commands, no key press");
- yield testHasNoPermission({
- manifest: {
- "permissions": ["http://example.com/", "activeTab"],
- "commands": {
- "test-tabs-executeScript": {
- "suggested_key": {
- "default": "Alt+Shift+K",
- },
- },
- },
- },
- });
-
- info("Test active tab, browser action, no click");
- yield testHasNoPermission({
- manifest: {
- "permissions": ["http://example.com/", "activeTab"],
- "browser_action": {},
- },
- });
-
- info("Test active tab, page action, no click");
- yield testHasNoPermission({
- manifest: {
- "permissions": ["http://example.com/", "activeTab"],
- "page_action": {},
- },
- async contentSetup() {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- await browser.pageAction.show(tab.id);
- },
- });
-
- yield BrowserTestUtils.removeTab(tab2);
- yield BrowserTestUtils.removeTab(tab1);
-});
-
-add_task(function* testBadURL() {
- async function background() {
- let promises = [
- new Promise(resolve => {
- browser.tabs.executeScript({
- file: "http://example.com/script.js",
- }, result => {
- browser.test.assertEq(undefined, result, "Result value");
-
- browser.test.assertTrue(browser.extension.lastError instanceof Error,
- "runtime.lastError is Error");
-
- browser.test.assertTrue(browser.runtime.lastError instanceof Error,
- "runtime.lastError is Error");
-
- browser.test.assertEq(
- "Files to be injected must be within the extension",
- browser.extension.lastError && browser.extension.lastError.message,
- "extension.lastError value");
-
- browser.test.assertEq(
- "Files to be injected must be within the extension",
- browser.runtime.lastError && browser.runtime.lastError.message,
- "runtime.lastError value");
-
- resolve();
- });
- }),
-
- browser.tabs.executeScript({
- file: "http://example.com/script.js",
- }).catch(error => {
- browser.test.assertTrue(error instanceof Error, "Error is Error");
-
- browser.test.assertEq(null, browser.extension.lastError,
- "extension.lastError value");
-
- browser.test.assertEq(null, browser.runtime.lastError,
- "runtime.lastError value");
-
- browser.test.assertEq(
- "Files to be injected must be within the extension",
- error && error.message,
- "error value");
- }),
- ];
-
- await Promise.all(promises);
-
- browser.test.notifyPass("executeScript-lastError");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["<all_urls>"],
- },
-
- background,
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("executeScript-lastError");
-
- yield extension.unload();
-});
-
-// TODO: Test that |executeScript| fails if the tab has navigated to a
-// new page, and no longer matches our expected state. This involves
-// intentionally trying to trigger a race condition, and is probably not
-// even worth attempting until we have proper |executeScript| callbacks.
-
-add_task(forceGC);
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js
deleted file mode 100644
index cf4721310..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js
+++ /dev/null
@@ -1,189 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-requestLongerTimeout(2);
-
-function* testHasPermission(params) {
- let contentSetup = params.contentSetup || (() => Promise.resolve());
-
- async function background(contentSetup) {
- browser.runtime.onMessage.addListener((msg, sender) => {
- browser.test.assertEq(msg, "script ran", "script ran");
- browser.test.notifyPass("executeScript");
- });
-
- browser.test.onMessage.addListener(msg => {
- browser.test.assertEq(msg, "execute-script");
-
- browser.tabs.executeScript({
- file: "script.js",
- });
- });
-
- await contentSetup();
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: params.manifest,
-
- background: `(${background})(${contentSetup})`,
-
- files: {
- "script.js": function() {
- browser.runtime.sendMessage("script ran");
- },
- },
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- if (params.setup) {
- yield params.setup(extension);
- }
-
- extension.sendMessage("execute-script");
-
- yield extension.awaitFinish("executeScript");
-
- if (params.tearDown) {
- yield params.tearDown(extension);
- }
-
- yield extension.unload();
-}
-
-add_task(function* testGoodPermissions() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true);
-
- info("Test explicit host permission");
- yield testHasPermission({
- manifest: {"permissions": ["http://mochi.test/"]},
- });
-
- info("Test explicit host subdomain permission");
- yield testHasPermission({
- manifest: {"permissions": ["http://*.mochi.test/"]},
- });
-
- info("Test explicit <all_urls> permission");
- yield testHasPermission({
- manifest: {"permissions": ["<all_urls>"]},
- });
-
- info("Test activeTab permission with a command key press");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab"],
- "commands": {
- "test-tabs-executeScript": {
- "suggested_key": {
- "default": "Alt+Shift+K",
- },
- },
- },
- },
- contentSetup() {
- browser.commands.onCommand.addListener(function(command) {
- if (command == "test-tabs-executeScript") {
- browser.test.sendMessage("tabs-command-key-pressed");
- }
- });
- return Promise.resolve();
- },
- setup: function* (extension) {
- yield EventUtils.synthesizeKey("k", {altKey: true, shiftKey: true});
- yield extension.awaitMessage("tabs-command-key-pressed");
- },
- });
-
- info("Test activeTab permission with a browser action click");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab"],
- "browser_action": {},
- },
- contentSetup() {
- browser.browserAction.onClicked.addListener(() => {
- browser.test.log("Clicked.");
- });
- return Promise.resolve();
- },
- setup: clickBrowserAction,
- tearDown: closeBrowserAction,
- });
-
- info("Test activeTab permission with a page action click");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab"],
- "page_action": {},
- },
- contentSetup: async () => {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- await browser.pageAction.show(tab.id);
- },
- setup: clickPageAction,
- tearDown: closePageAction,
- });
-
- info("Test activeTab permission with a browser action w/popup click");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab"],
- "browser_action": {"default_popup": "_blank.html"},
- },
- setup: async extension => {
- await clickBrowserAction(extension);
- return awaitExtensionPanel(extension, window, "_blank.html");
- },
- tearDown: closeBrowserAction,
- });
-
- info("Test activeTab permission with a page action w/popup click");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab"],
- "page_action": {"default_popup": "_blank.html"},
- },
- contentSetup: async () => {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- await browser.pageAction.show(tab.id);
- },
- setup: clickPageAction,
- tearDown: closePageAction,
- });
-
- info("Test activeTab permission with a context menu click");
- yield testHasPermission({
- manifest: {
- "permissions": ["activeTab", "contextMenus"],
- },
- contentSetup() {
- browser.contextMenus.create({title: "activeTab", contexts: ["all"]});
- return Promise.resolve();
- },
- setup: function* (extension) {
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("a[href]", {type: "contextmenu", button: 2},
- gBrowser.selectedBrowser);
- yield awaitPopupShown;
-
- let item = contextMenu.querySelector("[label=activeTab]");
-
- yield EventUtils.synthesizeMouseAtCenter(item, {}, window);
-
- yield awaitPopupHidden;
- },
- });
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(forceGC);
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js
deleted file mode 100644
index 7b2ffe175..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testExecuteScriptAtOnUpdated() {
- const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
- const URL = BASE + "file_iframe_document.html";
- // This is a regression test for bug 1325830.
- // The bug (executeScript not completing any more) occurred when executeScript
- // was called early at the onUpdated event, unless the tabs.create method is
- // called. So this test does not use tabs.create to open new tabs.
- // Note that if this test is run together with other tests that do call
- // tabs.create, then this test case does not properly test the conditions of
- // the regression any more. To verify that the regression has been resolved,
- // this test must be run in isolation.
-
- function background() {
- // Using variables to prevent listeners from running more than once, instead
- // of removing the listener. This is to minimize any IPC, since the bug that
- // is being tested is sensitive to timing.
- let ignore = false;
- let url;
- browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
- if (changeInfo.status === "loading" && tab.url === url && !ignore) {
- ignore = true;
- browser.tabs.executeScript(tabId, {
- code: "document.URL",
- }).then(results => {
- browser.test.assertEq(url, results[0], "Content script should run");
- browser.test.notifyPass("executeScript-at-onUpdated");
- }, error => {
- browser.test.fail(`Unexpected error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("executeScript-at-onUpdated");
- });
- // (running this log call after executeScript to minimize IPC between
- // onUpdated and executeScript.)
- browser.test.log(`Found expected navigation to ${url}`);
- } else {
- // The bug occurs when executeScript is called before a tab is
- // initialized.
- browser.tabs.executeScript(tabId, {code: ""});
- }
- });
- browser.test.onMessage.addListener(testUrl => {
- url = testUrl;
- browser.test.sendMessage("open-test-tab");
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/", "tabs"],
- },
- background,
- });
-
- yield extension.startup();
- extension.sendMessage(URL);
- yield extension.awaitMessage("open-test-tab");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL, true);
-
- yield extension.awaitFinish("executeScript-at-onUpdated");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js
deleted file mode 100644
index a4c0ed6f1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/**
- * These tests ensure that the runAt argument to tabs.executeScript delays
- * script execution until the document has reached the correct state.
- *
- * Since tests of this nature are especially race-prone, it relies on a
- * server-JS script to delay the completion of our test page's load cycle long
- * enough for us to attempt to load our scripts in the earlies phase we support.
- *
- * And since we can't actually rely on that timing, it retries any attempts that
- * fail to load as early as expected, but don't load at any illegal time.
- */
-
-add_task(function* testExecuteScript() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", true);
-
- async function background() {
- let tab;
-
- const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
- const URL = BASE + "file_iframe_document.sjs";
-
- const MAX_TRIES = 10;
-
- try {
- [tab] = await browser.tabs.query({active: true, currentWindow: true});
-
- let success = false;
- for (let tries = 0; !success && tries < MAX_TRIES; tries++) {
- let url = `${URL}?r=${Math.random()}`;
-
- let loadingPromise = new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab_) {
- if (tabId == tab.id && changed.status == "loading" && tab_.url == url) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
-
- // TODO: Test allFrames and frameId.
-
- await browser.tabs.update({url});
- await loadingPromise;
-
- let states = await Promise.all([
- // Send the executeScript requests in the reverse order that we expect
- // them to execute in, to avoid them passing only because of timing
- // races.
- browser.tabs.executeScript({
- code: "document.readyState",
- runAt: "document_idle",
- }),
- browser.tabs.executeScript({
- code: "document.readyState",
- runAt: "document_end",
- }),
- browser.tabs.executeScript({
- code: "document.readyState",
- runAt: "document_start",
- }),
- ].reverse());
-
- browser.test.log(`Got states: ${states}`);
-
- // Make sure that none of our scripts executed earlier than expected,
- // regardless of retries.
- browser.test.assertTrue(states[1] == "interactive" || states[1] == "complete",
- `document_end state is valid: ${states[1]}`);
- browser.test.assertTrue(states[2] == "complete",
- `document_idle state is valid: ${states[2]}`);
-
- // If we have the earliest valid states for each script, we're done.
- // Otherwise, try again.
- success = (states[0] == "loading" &&
- states[1] == "interactive" &&
- states[2] == "complete");
- }
-
- browser.test.assertTrue(success, "Got the earliest expected states at least once");
-
- browser.test.notifyPass("executeScript-runAt");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("executeScript-runAt");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/", "tabs"],
- },
-
- background,
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("executeScript-runAt");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js b/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js
deleted file mode 100644
index b67d935cb..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "browser_action": {"default_popup": "popup.html"},
- },
-
- files: {
- "tab.js": function() {
- let url = document.location.href;
-
- browser.tabs.getCurrent(currentTab => {
- browser.test.assertEq(currentTab.url, url, "getCurrent in non-active background tab");
-
- // Activate the tab.
- browser.tabs.onActivated.addListener(function listener({tabId}) {
- if (tabId == currentTab.id) {
- browser.tabs.onActivated.removeListener(listener);
-
- browser.tabs.getCurrent(currentTab => {
- browser.test.assertEq(currentTab.id, tabId, "in active background tab");
- browser.test.assertEq(currentTab.url, url, "getCurrent in non-active background tab");
-
- browser.test.sendMessage("tab-finished");
- });
- }
- });
- browser.tabs.update(currentTab.id, {active: true});
- });
- },
-
- "popup.js": function() {
- browser.tabs.getCurrent(tab => {
- browser.test.assertEq(tab, undefined, "getCurrent in popup script");
- browser.test.sendMessage("popup-finished");
- });
- },
-
- "tab.html": `<head><meta charset="utf-8"><script src="tab.js"></script></head>`,
- "popup.html": `<head><meta charset="utf-8"><script src="popup.js"></script></head>`,
- },
-
- background: function() {
- browser.tabs.getCurrent(tab => {
- browser.test.assertEq(tab, undefined, "getCurrent in background script");
- browser.test.sendMessage("background-finished");
- });
-
- browser.tabs.create({url: "tab.html", active: false});
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("background-finished");
- yield extension.awaitMessage("tab-finished");
-
- clickBrowserAction(extension);
- yield awaitExtensionPanel(extension);
- yield extension.awaitMessage("popup-finished");
- yield closeBrowserAction(extension);
-
- // The extension tab is automatically closed when the extension unloads.
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js b/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js
deleted file mode 100644
index a8e172d94..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testExecuteScript() {
- let {MessageChannel} = Cu.import("resource://gre/modules/MessageChannel.jsm", {});
-
- let messageManagersSize = MessageChannel.messageManagers.size;
- let responseManagersSize = MessageChannel.responseManagers.size;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true);
-
- async function background() {
- let tasks = [
- {
- background: "transparent",
- foreground: "rgb(0, 113, 4)",
- promise: () => {
- return browser.tabs.insertCSS({
- file: "file2.css",
- });
- },
- },
- {
- background: "rgb(42, 42, 42)",
- foreground: "rgb(0, 113, 4)",
- promise: () => {
- return browser.tabs.insertCSS({
- code: "* { background: rgb(42, 42, 42) }",
- });
- },
- },
- ];
-
- function checkCSS() {
- let computedStyle = window.getComputedStyle(document.body);
- return [computedStyle.backgroundColor, computedStyle.color];
- }
-
- try {
- for (let {promise, background, foreground} of tasks) {
- let result = await promise();
-
- browser.test.assertEq(undefined, result, "Expected callback result");
-
- [result] = await browser.tabs.executeScript({
- code: `(${checkCSS})()`,
- });
-
- browser.test.assertEq(background, result[0], "Expected background color");
- browser.test.assertEq(foreground, result[1], "Expected foreground color");
- }
-
- browser.test.notifyPass("insertCSS");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFailure("insertCSS");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/"],
- },
-
- background,
-
- files: {
- "file2.css": "* { color: rgb(0, 113, 4) }",
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("insertCSS");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-
- // Make sure that we're not holding on to references to closed message
- // managers.
- is(MessageChannel.messageManagers.size, messageManagersSize, "Message manager count");
- is(MessageChannel.responseManagers.size, responseManagersSize, "Response manager count");
- is(MessageChannel.pendingResponses.size, 0, "Pending response count");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move.js b/browser/components/extensions/test/browser/browser_ext_tabs_move.js
deleted file mode 100644
index 917cdc146..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_move.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: async function() {
- let [tab] = await browser.tabs.query({lastFocusedWindow: true});
-
- browser.tabs.move(tab.id, {index: 0});
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
-
- browser.test.assertEq(tabs[0].url, tab.url, "should be first tab");
- browser.test.notifyPass("tabs.move.single");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.single");
- yield extension.unload();
-
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: async function() {
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
-
- tabs.sort(function(a, b) { return a.url > b.url; });
-
- browser.tabs.move(tabs.map(tab => tab.id), {index: 0});
-
- tabs = await browser.tabs.query({lastFocusedWindow: true});
-
- browser.test.assertEq(tabs[0].url, "about:blank", "should be first tab");
- browser.test.assertEq(tabs[1].url, "about:config", "should be second tab");
- browser.test.assertEq(tabs[2].url, "about:robots", "should be third tab");
-
- browser.test.notifyPass("tabs.move.multiple");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.multiple");
- yield extension.unload();
-
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- async background() {
- let [, tab] = await browser.tabs.query({lastFocusedWindow: true});
-
- // Assuming that tab.id of 12345 does not exist.
- await browser.test.assertRejects(
- browser.tabs.move([tab.id, 12345], {index: 0}),
- /Invalid tab/,
- "Should receive invalid tab error");
-
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
- browser.test.assertEq(tabs[1].url, tab.url, "should be second tab");
- browser.test.notifyPass("tabs.move.invalid");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.invalid");
- yield extension.unload();
-
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: async function() {
- let [tab] = await browser.tabs.query({lastFocusedWindow: true});
- browser.tabs.move(tab.id, {index: -1});
-
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
-
- browser.test.assertEq(tabs[2].url, tab.url, "should be last tab");
- browser.test.notifyPass("tabs.move.last");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.last");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js
deleted file mode 100644
index f3bce364a..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
- let window1 = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- async background() {
- let tabs = await browser.tabs.query({url: "<all_urls>"});
- let destination = tabs[0];
- let source = tabs[1]; // skip over about:blank in window1
-
- // Assuming that this windowId does not exist.
- await browser.test.assertRejects(
- browser.tabs.move(source.id, {windowId: 123144576, index: 0}),
- /Invalid window/,
- "Should receive invalid window error");
-
- browser.tabs.move(source.id, {windowId: destination.windowId, index: 0});
-
- tabs = await browser.tabs.query({url: "<all_urls>"});
- browser.test.assertEq(tabs[0].url, "http://example.com/");
- browser.test.assertEq(tabs[0].windowId, destination.windowId);
- browser.test.notifyPass("tabs.move.window");
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.window");
- yield extension.unload();
-
- for (let tab of window.gBrowser.tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(window1);
-});
-
-add_task(function* test_currentWindowAfterTabMoved() {
- const files = {
- "current.html": "<meta charset=utf-8><script src=current.js></script>",
- "current.js": function() {
- browser.test.onMessage.addListener(msg => {
- if (msg === "current") {
- browser.windows.getCurrent(win => {
- browser.test.sendMessage("id", win.id);
- });
- }
- });
- browser.test.sendMessage("ready");
- },
- };
-
- async function background() {
- let tabId;
-
- const url = browser.extension.getURL("current.html");
-
- browser.test.onMessage.addListener(async msg => {
- if (msg === "move") {
- await browser.windows.create({tabId});
- browser.test.sendMessage("moved");
- } else if (msg === "close") {
- await browser.tabs.remove(tabId);
- browser.test.sendMessage("done");
- }
- });
-
- let tab = await browser.tabs.create({url});
- tabId = tab.id;
- }
-
- const extension = ExtensionTestUtils.loadExtension({files, background});
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- extension.sendMessage("current");
- const first = yield extension.awaitMessage("id");
-
- extension.sendMessage("move");
- yield extension.awaitMessage("moved");
-
- extension.sendMessage("current");
- const second = yield extension.awaitMessage("id");
-
- isnot(first, second, "current window id is different after moving the tab");
-
- extension.sendMessage("close");
- yield extension.awaitMessage("done");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js
deleted file mode 100644
index dacd547f2..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let window1 = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, "http://example.net/");
- yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, "http://example.com/");
- yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.net/");
- yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/");
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query(
- {url: "<all_urls>"},
- tabs => {
- let move1 = tabs[1];
- let move3 = tabs[3];
- browser.tabs.move([move1.id, move3.id], {index: 0});
- browser.tabs.query(
- {url: "<all_urls>"},
- tabs => {
- browser.test.assertEq(tabs[0].url, move1.url);
- browser.test.assertEq(tabs[2].url, move3.url);
- browser.test.notifyPass("tabs.move.multiple");
- });
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.multiple");
- yield extension.unload();
-
- for (let tab of window.gBrowser.tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(window1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js
deleted file mode 100644
index c592dc56d..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
- let window1 = yield BrowserTestUtils.openNewBrowserWindow();
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/");
- window1.gBrowser.pinTab(tab1);
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query(
- {url: "<all_urls>"},
- tabs => {
- let destination = tabs[0];
- let source = tabs[1]; // remember, pinning moves it to the left.
- browser.tabs.move(source.id, {windowId: destination.windowId, index: 0});
-
- browser.tabs.query(
- {url: "<all_urls>"},
- tabs => {
- browser.test.assertEq(true, tabs[0].pinned);
- browser.test.notifyPass("tabs.move.pin");
- });
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.move.pin");
- yield extension.unload();
-
- for (let tab of window.gBrowser.tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(window1);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js b/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js
deleted file mode 100644
index 9cc2554d6..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js
+++ /dev/null
@@ -1,126 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testTabEvents() {
- async function background() {
- /** The list of active tab ID's */
- let tabIds = [];
-
- /**
- * Stores the events that fire for each tab.
- *
- * events {
- * tabId1: [event1, event2, ...],
- * tabId2: [event1, event2, ...],
- * }
- */
- let events = {};
-
- browser.tabs.onActivated.addListener((info) => {
- if (info.tabId in events) {
- events[info.tabId].push("onActivated");
- } else {
- events[info.tabId] = ["onActivated"];
- }
- });
-
- browser.tabs.onHighlighted.addListener((info) => {
- if (info.tabIds[0] in events) {
- events[info.tabIds[0]].push("onHighlighted");
- } else {
- events[info.tabIds[0]] = ["onHighlighted"];
- }
- });
-
- /**
- * Asserts that the expected events are fired for the tab with id = tabId.
- * The events associated to the specified tab are removed after this check is made.
- *
- * @param {number} tabId
- * @param {Array<string>} expectedEvents
- */
- async function expectEvents(tabId, expectedEvents) {
- browser.test.log(`Expecting events: ${expectedEvents.join(", ")}`);
-
- await new Promise(resolve => setTimeout(resolve, 0));
-
- browser.test.assertEq(expectedEvents.length, events[tabId].length,
- `Got expected number of events for ${tabId}`);
-
- for (let [i, name] of expectedEvents.entries()) {
- browser.test.assertEq(name, i in events[tabId] && events[tabId][i],
- `Got expected ${name} event`);
- }
- delete events[tabId];
- }
-
- /**
- * Opens a new tab and asserts that the correct events are fired.
- *
- * @param {number} windowId
- */
- async function openTab(windowId) {
- let tab = await browser.tabs.create({windowId});
-
- tabIds.push(tab.id);
- browser.test.log(`Opened tab ${tab.id}`);
-
- await expectEvents(tab.id, [
- "onActivated",
- "onHighlighted",
- ]);
- }
-
- /**
- * Highlights an existing tab and asserts that the correct events are fired.
- *
- * @param {number} tabId
- */
- async function highlightTab(tabId) {
- browser.test.log(`Highlighting tab ${tabId}`);
- let tab = await browser.tabs.update(tabId, {active: true});
-
- browser.test.assertEq(tab.id, tabId, `Tab ${tab.id} highlighted`);
-
- await expectEvents(tab.id, [
- "onActivated",
- "onHighlighted",
- ]);
- }
-
- /**
- * The main entry point to the tests.
- */
- let tabs = await browser.tabs.query({active: true, currentWindow: true});
-
- let activeWindow = tabs[0].windowId;
- await Promise.all([
- openTab(activeWindow),
- openTab(activeWindow),
- openTab(activeWindow),
- ]);
-
- await Promise.all([
- highlightTab(tabIds[0]),
- highlightTab(tabIds[1]),
- highlightTab(tabIds[2]),
- ]);
-
- await Promise.all(tabIds.map(id => browser.tabs.remove(id)));
-
- browser.test.notifyPass("tabs.highlight");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.highlight");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js b/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js
deleted file mode 100644
index 2c26bbd16..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js
+++ /dev/null
@@ -1,198 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-requestLongerTimeout(2);
-
-add_task(function* () {
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
-
- yield focusWindow(win1);
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- "content_scripts": [{
- "matches": ["http://mochi.test/*/context_tabs_onUpdated_page.html"],
- "js": ["content-script.js"],
- "run_at": "document_start",
- }],
- },
-
- background: function() {
- let pageURL = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";
-
- let expectedSequence = [
- {status: "loading"},
- {status: "loading", url: pageURL},
- {status: "complete"},
- ];
- let collectedSequence = [];
-
- browser.tabs.onUpdated.addListener(function(tabId, updatedInfo) {
- // onUpdated also fires with updatedInfo.faviconUrl, so explicitly
- // check for updatedInfo.status before recording the event.
- if ("status" in updatedInfo) {
- collectedSequence.push(updatedInfo);
- }
- });
-
- browser.runtime.onMessage.addListener(function() {
- if (collectedSequence.length !== expectedSequence.length) {
- browser.test.assertEq(
- JSON.stringify(expectedSequence),
- JSON.stringify(collectedSequence),
- "got unexpected number of updateInfo data"
- );
- } else {
- for (let i = 0; i < expectedSequence.length; i++) {
- browser.test.assertEq(
- expectedSequence[i].status,
- collectedSequence[i].status,
- "check updatedInfo status"
- );
- if (expectedSequence[i].url || collectedSequence[i].url) {
- browser.test.assertEq(
- expectedSequence[i].url,
- collectedSequence[i].url,
- "check updatedInfo url"
- );
- }
- }
- }
-
- browser.test.notifyPass("tabs.onUpdated");
- });
-
- browser.tabs.create({url: pageURL});
- },
- files: {
- "content-script.js": `
- window.addEventListener("message", function(evt) {
- if (evt.data == "frame-updated") {
- browser.runtime.sendMessage("load-completed");
- }
- }, true);
- `,
- },
- });
-
- yield Promise.all([
- extension.startup(),
- extension.awaitFinish("tabs.onUpdated"),
- ]);
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(win1);
-});
-
-function* do_test_update(background, withPermissions = true) {
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
-
- yield focusWindow(win1);
-
- let manifest = {};
- if (withPermissions) {
- manifest.permissions = ["tabs"];
- }
- let extension = ExtensionTestUtils.loadExtension({manifest, background});
-
- yield Promise.all([
- yield extension.startup(),
- yield extension.awaitFinish("finish"),
- ]);
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(win1);
-}
-
-add_task(function* test_pinned() {
- yield do_test_update(function background() {
- // Create a new tab for testing update.
- browser.tabs.create({}, function(tab) {
- browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {
- // Check callback
- browser.test.assertEq(tabId, tab.id, "Check tab id");
- browser.test.log("onUpdate: " + JSON.stringify(changeInfo));
- if ("pinned" in changeInfo) {
- browser.test.assertTrue(changeInfo.pinned, "Check changeInfo.pinned");
- browser.tabs.onUpdated.removeListener(onUpdated);
- // Remove created tab.
- browser.tabs.remove(tabId);
- browser.test.notifyPass("finish");
- return;
- }
- });
- browser.tabs.update(tab.id, {pinned: true});
- });
- });
-});
-
-add_task(function* test_unpinned() {
- yield do_test_update(function background() {
- // Create a new tab for testing update.
- browser.tabs.create({pinned: true}, function(tab) {
- browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {
- // Check callback
- browser.test.assertEq(tabId, tab.id, "Check tab id");
- browser.test.log("onUpdate: " + JSON.stringify(changeInfo));
- if ("pinned" in changeInfo) {
- browser.test.assertFalse(changeInfo.pinned, "Check changeInfo.pinned");
- browser.tabs.onUpdated.removeListener(onUpdated);
- // Remove created tab.
- browser.tabs.remove(tabId);
- browser.test.notifyPass("finish");
- return;
- }
- });
- browser.tabs.update(tab.id, {pinned: false});
- });
- });
-});
-
-add_task(function* test_url() {
- yield do_test_update(function background() {
- // Create a new tab for testing update.
- browser.tabs.create({}, function(tab) {
- browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {
- // Check callback
- browser.test.assertEq(tabId, tab.id, "Check tab id");
- browser.test.log("onUpdate: " + JSON.stringify(changeInfo));
- if ("url" in changeInfo) {
- browser.test.assertEq("about:blank", changeInfo.url,
- "Check changeInfo.url");
- browser.tabs.onUpdated.removeListener(onUpdated);
- // Remove created tab.
- browser.tabs.remove(tabId);
- browser.test.notifyPass("finish");
- return;
- }
- });
- browser.tabs.update(tab.id, {url: "about:blank"});
- });
- });
-});
-
-add_task(function* test_without_tabs_permission() {
- yield do_test_update(function background() {
- browser.tabs.create({url: "about:blank"}, function(tab) {
- browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {
- if (tabId == tab.id) {
- browser.test.assertFalse("url" in changeInfo, "url should not be included without tabs permission");
- browser.test.assertFalse("favIconUrl" in changeInfo, "favIconUrl should not be included without tabs permission");
-
- if (changeInfo.status == "complete") {
- browser.tabs.onUpdated.removeListener(onUpdated);
- browser.tabs.remove(tabId);
- browser.test.notifyPass("finish");
- }
- }
- });
- browser.tabs.reload(tab.id);
- });
- }, false /* withPermissions */);
-});
-
-add_task(forceGC);
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_query.js b/browser/components/extensions/test/browser/browser_ext_tabs_query.js
deleted file mode 100644
index 7804d1454..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_query.js
+++ /dev/null
@@ -1,224 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-requestLongerTimeout(2);
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- lastFocusedWindow: true,
- }, function(tabs) {
- browser.test.assertEq(tabs.length, 3, "should have three tabs");
-
- tabs.sort((tab1, tab2) => tab1.index - tab2.index);
-
- browser.test.assertEq(tabs[0].url, "about:blank", "first tab blank");
- tabs.shift();
-
- browser.test.assertTrue(tabs[0].active, "tab 0 active");
- browser.test.assertFalse(tabs[1].active, "tab 1 inactive");
-
- browser.test.assertFalse(tabs[0].pinned, "tab 0 unpinned");
- browser.test.assertFalse(tabs[1].pinned, "tab 1 unpinned");
-
- browser.test.assertEq(tabs[0].url, "about:robots", "tab 0 url correct");
- browser.test.assertEq(tabs[1].url, "about:config", "tab 1 url correct");
-
- browser.test.assertEq(tabs[0].status, "complete", "tab 0 status correct");
- browser.test.assertEq(tabs[1].status, "complete", "tab 1 status correct");
-
- browser.test.assertEq(tabs[0].title, "Gort! Klaatu barada nikto!", "tab 0 title correct");
-
- browser.test.notifyPass("tabs.query");
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.query");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-
- tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
- tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
- let tab3 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://test1.example.org/MochiKit/");
-
- // test simple queries
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- url: "<all_urls>",
- }, function(tabs) {
- browser.test.assertEq(tabs.length, 3, "should have three tabs");
-
- tabs.sort((tab1, tab2) => tab1.index - tab2.index);
-
- browser.test.assertEq(tabs[0].url, "http://example.com/", "tab 0 url correct");
- browser.test.assertEq(tabs[1].url, "http://example.net/", "tab 1 url correct");
- browser.test.assertEq(tabs[2].url, "http://test1.example.org/MochiKit/", "tab 2 url correct");
-
- browser.test.notifyPass("tabs.query");
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.query");
- yield extension.unload();
-
- // match pattern
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- url: "http://*/MochiKit*",
- }, function(tabs) {
- browser.test.assertEq(tabs.length, 1, "should have one tab");
-
- browser.test.assertEq(tabs[0].url, "http://test1.example.org/MochiKit/", "tab 0 url correct");
-
- browser.test.notifyPass("tabs.query");
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.query");
- yield extension.unload();
-
- // match array of patterns
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- url: ["http://*/MochiKit*", "http://*.com/*"],
- }, function(tabs) {
- browser.test.assertEq(tabs.length, 2, "should have two tabs");
-
- tabs.sort((tab1, tab2) => tab1.index - tab2.index);
-
- browser.test.assertEq(tabs[0].url, "http://example.com/", "tab 0 url correct");
- browser.test.assertEq(tabs[1].url, "http://test1.example.org/MochiKit/", "tab 1 url correct");
-
- browser.test.notifyPass("tabs.query");
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.query");
- yield extension.unload();
-
- // test width and height
- extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.test.onMessage.addListener(async msg => {
- let tabs = await browser.tabs.query({active: true});
-
- browser.test.assertEq(tabs.length, 1, "should have one tab");
- browser.test.sendMessage("dims", {width: tabs[0].width, height: tabs[0].height});
- });
- browser.test.sendMessage("ready");
- },
- });
-
- const RESOLUTION_PREF = "layout.css.devPixelsPerPx";
- registerCleanupFunction(() => {
- SpecialPowers.clearUserPref(RESOLUTION_PREF);
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
-
- for (let resolution of [2, 1]) {
- SpecialPowers.setCharPref(RESOLUTION_PREF, String(resolution));
- is(window.devicePixelRatio, resolution, "window has the required resolution");
-
- let {clientHeight, clientWidth} = gBrowser.selectedBrowser;
-
- extension.sendMessage("check-size");
- let dims = yield extension.awaitMessage("dims");
- is(dims.width, clientWidth, "tab reports expected width");
- is(dims.height, clientHeight, "tab reports expected height");
- }
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
- yield BrowserTestUtils.removeTab(tab3);
- SpecialPowers.clearUserPref(RESOLUTION_PREF);
-});
-
-add_task(function* testQueryPermissions() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": [],
- },
-
- async background() {
- try {
- let tabs = await browser.tabs.query({currentWindow: true, active: true});
- browser.test.assertEq(tabs.length, 1, "Expect query to return tabs");
- browser.test.notifyPass("queryPermissions");
- } catch (e) {
- browser.test.notifyFail("queryPermissions");
- }
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("queryPermissions");
-
- yield extension.unload();
-});
-
-add_task(function* testQueryWithURLPermissions() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": [],
- },
-
- async background() {
- await browser.test.assertRejects(
- browser.tabs.query({"url": "http://www.bbc.com/"}),
- 'The "tabs" permission is required to use the query API with the "url" parameter',
- "Expected tabs.query with 'url' to fail with permissions error message");
-
- browser.test.notifyPass("queryWithURLPermissions");
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("queryWithURLPermissions");
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_reload.js b/browser/components/extensions/test/browser/browser_ext_tabs_reload.js
deleted file mode 100644
index 99b2d426b..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_reload.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- files: {
- "tab.js": function() {
- browser.runtime.sendMessage("tab-loaded");
- },
- "tab.html":
- `<head>
- <meta charset="utf-8">
- <script src="tab.js"></script>
- </head>`,
- },
-
- async background() {
- let tabLoadedCount = 0;
-
- let tab = await browser.tabs.create({url: "tab.html", active: true});
-
- browser.runtime.onMessage.addListener(msg => {
- if (msg == "tab-loaded") {
- tabLoadedCount++;
-
- if (tabLoadedCount == 1) {
- // Reload the tab once passing no arguments.
- return browser.tabs.reload();
- }
-
- if (tabLoadedCount == 2) {
- // Reload the tab again with explicit arguments.
- return browser.tabs.reload(tab.id, {
- bypassCache: false,
- });
- }
-
- if (tabLoadedCount == 3) {
- browser.test.notifyPass("tabs.reload");
- }
- }
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.reload");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js b/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js
deleted file mode 100644
index 648361724..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs", "<all_urls>"],
- },
-
- async background() {
- const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
- const URL = BASE + "file_bypass_cache.sjs";
-
- function awaitLoad(tabId) {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) {
- if (tabId == tabId_ && changed.status == "complete" && tab.url == URL) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- }
-
- try {
- let tab = await browser.tabs.create({url: URL});
- await awaitLoad(tab.id);
-
- await browser.tabs.reload(tab.id, {bypassCache: false});
- await awaitLoad(tab.id);
-
- let [textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"});
- browser.test.assertEq("", textContent, "`textContent` should be empty when bypassCache=false");
-
- await browser.tabs.reload(tab.id, {bypassCache: true});
- await awaitLoad(tab.id);
-
- [textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"});
-
- let [pragma, cacheControl] = textContent.split(":");
- browser.test.assertEq("no-cache", pragma, "`pragma` should be set to `no-cache` when bypassCache is true");
- browser.test.assertEq("no-cache", cacheControl, "`cacheControl` should be set to `no-cache` when bypassCache is true");
-
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("tabs.reload_bypass_cache");
- } catch (error) {
- browser.test.fail(`${error} :: ${error.stack}`);
- browser.test.notifyFail("tabs.reload_bypass_cache");
- }
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("tabs.reload_bypass_cache");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js b/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js
deleted file mode 100644
index e0eadab64..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testExecuteScript() {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true);
-
- async function background() {
- let tasks = [
- // Insert CSS file.
- {
- background: "transparent",
- foreground: "rgb(0, 113, 4)",
- promise: () => {
- return browser.tabs.insertCSS({
- file: "file2.css",
- });
- },
- },
- // Insert CSS code.
- {
- background: "rgb(42, 42, 42)",
- foreground: "rgb(0, 113, 4)",
- promise: () => {
- return browser.tabs.insertCSS({
- code: "* { background: rgb(42, 42, 42) }",
- });
- },
- },
- // Remove CSS code again.
- {
- background: "transparent",
- foreground: "rgb(0, 113, 4)",
- promise: () => {
- return browser.tabs.removeCSS({
- code: "* { background: rgb(42, 42, 42) }",
- });
- },
- },
- // Remove CSS file again.
- {
- background: "transparent",
- foreground: "rgb(0, 0, 0)",
- promise: () => {
- return browser.tabs.removeCSS({
- file: "file2.css",
- });
- },
- },
- ];
-
- function checkCSS() {
- let computedStyle = window.getComputedStyle(document.body);
- return [computedStyle.backgroundColor, computedStyle.color];
- }
-
- try {
- for (let {promise, background, foreground} of tasks) {
- let result = await promise();
- browser.test.assertEq(undefined, result, "Expected callback result");
-
- [result] = await browser.tabs.executeScript({
- code: `(${checkCSS})()`,
- });
- browser.test.assertEq(background, result[0], "Expected background color");
- browser.test.assertEq(foreground, result[1], "Expected foreground color");
- }
-
- browser.test.notifyPass("removeCSS");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFailure("removeCSS");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["http://mochi.test/"],
- },
-
- background,
-
- files: {
- "file2.css": "* { color: rgb(0, 113, 4) }",
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("removeCSS");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js b/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js
deleted file mode 100644
index 64e97afb1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js
+++ /dev/null
@@ -1,227 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* tabsSendMessageReply() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "content_scripts": [{
- "matches": ["http://example.com/"],
- "js": ["content-script.js"],
- "run_at": "document_start",
- }],
- },
-
- background: async function() {
- let firstTab;
- let promiseResponse = new Promise(resolve => {
- browser.runtime.onMessage.addListener((msg, sender, respond) => {
- if (msg == "content-script-ready") {
- let tabId = sender.tab.id;
-
- Promise.all([
- promiseResponse,
-
- browser.tabs.sendMessage(tabId, "respond-now"),
- browser.tabs.sendMessage(tabId, "respond-now-2"),
- new Promise(resolve => browser.tabs.sendMessage(tabId, "respond-soon", resolve)),
- browser.tabs.sendMessage(tabId, "respond-promise"),
- browser.tabs.sendMessage(tabId, "respond-never"),
- new Promise(resolve => {
- browser.runtime.sendMessage("respond-never", response => { resolve(response); });
- }),
-
- browser.tabs.sendMessage(tabId, "respond-error").catch(error => Promise.resolve({error})),
- browser.tabs.sendMessage(tabId, "throw-error").catch(error => Promise.resolve({error})),
-
- browser.tabs.sendMessage(firstTab, "no-listener").catch(error => Promise.resolve({error})),
- ]).then(([response, respondNow, respondNow2, respondSoon, respondPromise, respondNever, respondNever2, respondError, throwError, noListener]) => {
- browser.test.assertEq("expected-response", response, "Content script got the expected response");
-
- browser.test.assertEq("respond-now", respondNow, "Got the expected immediate response");
- browser.test.assertEq("respond-now-2", respondNow2, "Got the expected immediate response from the second listener");
- browser.test.assertEq("respond-soon", respondSoon, "Got the expected delayed response");
- browser.test.assertEq("respond-promise", respondPromise, "Got the expected promise response");
- browser.test.assertEq(undefined, respondNever, "Got the expected no-response resolution");
- browser.test.assertEq(undefined, respondNever2, "Got the expected no-response resolution");
-
- browser.test.assertEq("respond-error", respondError.error.message, "Got the expected error response");
- browser.test.assertEq("throw-error", throwError.error.message, "Got the expected thrown error response");
-
- browser.test.assertEq("Could not establish connection. Receiving end does not exist.",
- noListener.error.message,
- "Got the expected no listener response");
-
- return browser.tabs.remove(tabId);
- }).then(() => {
- browser.test.notifyPass("sendMessage");
- });
-
- return Promise.resolve("expected-response");
- } else if (msg[0] == "got-response") {
- resolve(msg[1]);
- }
- });
- });
-
- let tabs = await browser.tabs.query({currentWindow: true, active: true});
- firstTab = tabs[0].id;
- browser.tabs.create({url: "http://example.com/"});
- },
-
- files: {
- "content-script.js": async function() {
- browser.runtime.onMessage.addListener((msg, sender, respond) => {
- if (msg == "respond-now") {
- respond(msg);
- } else if (msg == "respond-soon") {
- setTimeout(() => { respond(msg); }, 0);
- return true;
- } else if (msg == "respond-promise") {
- return Promise.resolve(msg);
- } else if (msg == "respond-never") {
- return;
- } else if (msg == "respond-error") {
- return Promise.reject(new Error(msg));
- } else if (msg == "throw-error") {
- throw new Error(msg);
- }
- });
-
- browser.runtime.onMessage.addListener((msg, sender, respond) => {
- if (msg == "respond-now") {
- respond("hello");
- } else if (msg == "respond-now-2") {
- respond(msg);
- }
- });
-
- let response = await browser.runtime.sendMessage("content-script-ready");
- browser.runtime.sendMessage(["got-response", response]);
- },
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("sendMessage");
-
- yield extension.unload();
-});
-
-
-add_task(function* tabsSendHidden() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
-
- "content_scripts": [{
- "matches": ["http://example.com/content*"],
- "js": ["content-script.js"],
- "run_at": "document_start",
- }],
- },
-
- background: async function() {
- let resolveContent;
- browser.runtime.onMessage.addListener((msg, sender) => {
- if (msg[0] == "content-ready") {
- resolveContent(msg[1]);
- }
- });
-
- let awaitContent = url => {
- return new Promise(resolve => {
- resolveContent = resolve;
- }).then(result => {
- browser.test.assertEq(url, result, "Expected content script URL");
- });
- };
-
- try {
- const URL1 = "http://example.com/content1.html";
- const URL2 = "http://example.com/content2.html";
-
- let tab = await browser.tabs.create({url: URL1});
- await awaitContent(URL1);
-
- let url = await browser.tabs.sendMessage(tab.id, URL1);
- browser.test.assertEq(URL1, url, "Should get response from expected content window");
-
- await browser.tabs.update(tab.id, {url: URL2});
- await awaitContent(URL2);
-
- url = await browser.tabs.sendMessage(tab.id, URL2);
- browser.test.assertEq(URL2, url, "Should get response from expected content window");
-
- // Repeat once just to be sure the first message was processed by all
- // listeners before we exit the test.
- url = await browser.tabs.sendMessage(tab.id, URL2);
- browser.test.assertEq(URL2, url, "Should get response from expected content window");
-
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("contentscript-bfcache-window");
- } catch (error) {
- browser.test.fail(`Error: ${error} :: ${error.stack}`);
- browser.test.notifyFail("contentscript-bfcache-window");
- }
- },
-
- files: {
- "content-script.js": function() {
- // Store this in a local variable to make sure we don't touch any
- // properties of the possibly-hidden content window.
- let href = window.location.href;
-
- browser.runtime.onMessage.addListener((msg, sender) => {
- browser.test.assertEq(href, msg, "Should be in the expected content window");
-
- return Promise.resolve(href);
- });
-
- browser.runtime.sendMessage(["content-ready", href]);
- },
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("contentscript-bfcache-window");
-
- yield extension.unload();
-});
-
-
-add_task(function* tabsSendMessageNoExceptionOnNonExistentTab() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- async background() {
- let url = "http://example.com/mochitest/browser/browser/components/extensions/test/browser/file_dummy.html";
- let tab = await browser.tabs.create({url});
-
- try {
- browser.tabs.sendMessage(tab.id, "message");
- browser.tabs.sendMessage(tab.id + 100, "message");
- } catch (e) {
- browser.test.fail("no exception should be raised on tabs.sendMessage to nonexistent tabs");
- }
-
- await browser.tabs.remove(tab.id);
-
- browser.test.notifyPass("tabs.sendMessage");
- },
- });
-
- yield Promise.all([
- extension.startup(),
- extension.awaitFinish("tabs.sendMessage"),
- ]);
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_update.js b/browser/components/extensions/test/browser/browser_ext_tabs_update.js
deleted file mode 100644
index 8e56a746c..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_update.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config");
-
- gBrowser.selectedTab = tab1;
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background: function() {
- browser.tabs.query({
- lastFocusedWindow: true,
- }, function(tabs) {
- browser.test.assertEq(tabs.length, 3, "should have three tabs");
-
- tabs.sort((tab1, tab2) => tab1.index - tab2.index);
-
- browser.test.assertEq(tabs[0].url, "about:blank", "first tab blank");
- tabs.shift();
-
- browser.test.assertTrue(tabs[0].active, "tab 0 active");
- browser.test.assertFalse(tabs[1].active, "tab 1 inactive");
-
- browser.tabs.update(tabs[1].id, {active: true}, function() {
- browser.test.sendMessage("check");
- });
- });
- },
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("check")]);
-
- ok(gBrowser.selectedTab == tab2, "correct tab selected");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js b/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js
deleted file mode 100644
index b43855fb1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* testTabsUpdateURL(existentTabURL, tabsUpdateURL, isErrorExpected) {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- files: {
- "tab.html": `
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <h1>tab page</h1>
- </body>
- </html>
- `.trim(),
- },
- background: function() {
- browser.test.sendMessage("ready", browser.runtime.getURL("tab.html"));
-
- browser.test.onMessage.addListener(async (msg, tabsUpdateURL, isErrorExpected) => {
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
-
- try {
- let tab = await browser.tabs.update(tabs[1].id, {url: tabsUpdateURL});
-
- browser.test.assertFalse(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should be rejected`);
- browser.test.assertTrue(tab, "on success the tab should be defined");
- } catch (error) {
- browser.test.assertTrue(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should not be rejected`);
- browser.test.assertTrue(/^Illegal URL/.test(error.message),
- "tabs.update should be rejected with the expected error message");
- }
-
- browser.test.sendMessage("done");
- });
- },
- });
-
- yield extension.startup();
-
- let mozExtTabURL = yield extension.awaitMessage("ready");
-
- if (tabsUpdateURL == "self") {
- tabsUpdateURL = mozExtTabURL;
- }
-
- info(`tab.update URL "${tabsUpdateURL}" on tab with URL "${existentTabURL}"`);
-
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, existentTabURL);
-
- extension.sendMessage("start", tabsUpdateURL, isErrorExpected);
- yield extension.awaitMessage("done");
-
- yield BrowserTestUtils.removeTab(tab1);
- yield extension.unload();
-}
-
-add_task(function* () {
- info("Start testing tabs.update on javascript URLs");
-
- let dataURLPage = `data:text/html,
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <h1>data url page</h1>
- </body>
- </html>`;
-
- let checkList = [
- {
- tabsUpdateURL: "http://example.net",
- isErrorExpected: false,
- },
- {
- tabsUpdateURL: "self",
- isErrorExpected: false,
- },
- {
- tabsUpdateURL: "about:addons",
- isErrorExpected: true,
- },
- {
- tabsUpdateURL: "javascript:console.log('tabs.update execute javascript')",
- isErrorExpected: true,
- },
- {
- tabsUpdateURL: dataURLPage,
- isErrorExpected: true,
- },
- ];
-
- let testCases = checkList
- .map((check) => Object.assign({}, check, {existentTabURL: "about:blank"}));
-
- for (let {existentTabURL, tabsUpdateURL, isErrorExpected} of testCases) {
- yield* testTabsUpdateURL(existentTabURL, tabsUpdateURL, isErrorExpected);
- }
-
- info("done");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js b/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js
deleted file mode 100644
index c2e54d3ea..000000000
--- a/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-const SITE_SPECIFIC_PREF = "browser.zoom.siteSpecific";
-
-add_task(function* () {
- let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
- let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/");
-
- gBrowser.selectedTab = tab1;
-
- async function background() {
- function promiseUpdated(tabId, attr) {
- return new Promise(resolve => {
- let onUpdated = (tabId_, changeInfo, tab) => {
- if (tabId == tabId_ && attr in changeInfo) {
- browser.tabs.onUpdated.removeListener(onUpdated);
-
- resolve({changeInfo, tab});
- }
- };
- browser.tabs.onUpdated.addListener(onUpdated);
- });
- }
-
- let deferred = {};
- browser.test.onMessage.addListener((message, msg, result) => {
- if (message == "msg-done" && deferred[msg]) {
- deferred[msg].resolve(result);
- }
- });
-
- let _id = 0;
- function msg(...args) {
- return new Promise((resolve, reject) => {
- let id = ++_id;
- deferred[id] = {resolve, reject};
- browser.test.sendMessage("msg", id, ...args);
- });
- }
-
-
- let zoomEvents = [];
- let eventPromises = [];
- browser.tabs.onZoomChange.addListener(info => {
- zoomEvents.push(info);
- if (eventPromises.length) {
- eventPromises.shift().resolve();
- }
- });
-
- let awaitZoom = async (tabId, newValue) => {
- let listener;
-
- await new Promise(async resolve => {
- listener = info => {
- if (info.tabId == tabId && info.newZoomFactor == newValue) {
- resolve();
- }
- };
- browser.tabs.onZoomChange.addListener(listener);
-
- let zoomFactor = await browser.tabs.getZoom(tabId);
- if (zoomFactor == newValue) {
- resolve();
- }
- });
-
- browser.tabs.onZoomChange.removeListener(listener);
- };
-
- let checkZoom = async (tabId, newValue, oldValue = null) => {
- let awaitEvent;
- if (oldValue != null && !zoomEvents.length) {
- awaitEvent = new Promise(resolve => {
- eventPromises.push({resolve});
- });
- }
-
- let [apiZoom, realZoom] = await Promise.all([
- browser.tabs.getZoom(tabId),
- msg("get-zoom", tabId),
- awaitEvent,
- ]);
-
- browser.test.assertEq(newValue, apiZoom, `Got expected zoom value from API`);
- browser.test.assertEq(newValue, realZoom, `Got expected zoom value from parent`);
-
- if (oldValue != null) {
- let event = zoomEvents.shift();
- browser.test.assertEq(tabId, event.tabId, `Got expected zoom event tab ID`);
- browser.test.assertEq(newValue, event.newZoomFactor, `Got expected zoom event zoom factor`);
- browser.test.assertEq(oldValue, event.oldZoomFactor, `Got expected zoom event old zoom factor`);
-
- browser.test.assertEq(3, Object.keys(event.zoomSettings).length, `Zoom settings should have 3 keys`);
- browser.test.assertEq("automatic", event.zoomSettings.mode, `Mode should be "automatic"`);
- browser.test.assertEq("per-origin", event.zoomSettings.scope, `Scope should be "per-origin"`);
- browser.test.assertEq(1, event.zoomSettings.defaultZoomFactor, `Default zoom should be 1`);
- }
- };
-
- try {
- let tabs = await browser.tabs.query({lastFocusedWindow: true});
- browser.test.assertEq(tabs.length, 3, "We have three tabs");
-
- let tabIds = [tabs[1].id, tabs[2].id];
- await checkZoom(tabIds[0], 1);
-
- await browser.tabs.setZoom(tabIds[0], 2);
- await checkZoom(tabIds[0], 2, 1);
-
- let zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]);
- browser.test.assertEq(3, Object.keys(zoomSettings).length, `Zoom settings should have 3 keys`);
- browser.test.assertEq("automatic", zoomSettings.mode, `Mode should be "automatic"`);
- browser.test.assertEq("per-origin", zoomSettings.scope, `Scope should be "per-origin"`);
- browser.test.assertEq(1, zoomSettings.defaultZoomFactor, `Default zoom should be 1`);
-
-
- browser.test.log(`Switch to tab 2`);
- await browser.tabs.update(tabIds[1], {active: true});
- await checkZoom(tabIds[1], 1);
-
-
- browser.test.log(`Navigate tab 2 to origin of tab 1`);
- browser.tabs.update(tabIds[1], {url: "http://example.com"});
- await promiseUpdated(tabIds[1], "url");
- await checkZoom(tabIds[1], 2, 1);
-
-
- browser.test.log(`Update zoom in tab 2, expect changes in both tabs`);
- await browser.tabs.setZoom(tabIds[1], 1.5);
- await checkZoom(tabIds[1], 1.5, 2);
-
-
- browser.test.log(`Switch to tab 1, expect asynchronous zoom change just after the switch`);
- await Promise.all([
- awaitZoom(tabIds[0], 1.5),
- browser.tabs.update(tabIds[0], {active: true}),
- ]);
- await checkZoom(tabIds[0], 1.5, 2);
-
-
- browser.test.log("Set zoom to 0, expect it set to 1");
- await browser.tabs.setZoom(tabIds[0], 0);
- await checkZoom(tabIds[0], 1, 1.5);
-
-
- browser.test.log("Change zoom externally, expect changes reflected");
- await msg("enlarge");
- await checkZoom(tabIds[0], 1.1, 1);
-
- await Promise.all([
- browser.tabs.setZoom(tabIds[0], 0),
- browser.tabs.setZoom(tabIds[1], 0),
- ]);
- await Promise.all([
- checkZoom(tabIds[0], 1, 1.1),
- checkZoom(tabIds[1], 1, 1.5),
- ]);
-
-
- browser.test.log("Check that invalid zoom values throw an error");
- await browser.test.assertRejects(
- browser.tabs.setZoom(tabIds[0], 42),
- /Zoom value 42 out of range/,
- "Expected an out of range error");
-
- browser.test.log("Disable site-specific zoom, expect correct scope");
- await msg("site-specific", false);
- zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]);
-
- browser.test.assertEq("per-tab", zoomSettings.scope, `Scope should be "per-tab"`);
- await msg("site-specific", null);
-
- browser.test.notifyPass("tab-zoom");
- } catch (e) {
- browser.test.fail(`Error: ${e} :: ${e.stack}`);
- browser.test.notifyFail("tab-zoom");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- extension.onMessage("msg", (id, msg, ...args) => {
- let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let resp;
- if (msg == "get-zoom") {
- let tab = TabManager.getTab(args[0]);
- resp = ZoomManager.getZoomForBrowser(tab.linkedBrowser);
- } else if (msg == "set-zoom") {
- let tab = TabManager.getTab(args[0]);
- ZoomManager.setZoomForBrowser(tab.linkedBrowser);
- } else if (msg == "enlarge") {
- FullZoom.enlarge();
- } else if (msg == "site-specific") {
- if (args[0] == null) {
- SpecialPowers.clearUserPref(SITE_SPECIFIC_PREF);
- } else {
- SpecialPowers.setBoolPref(SITE_SPECIFIC_PREF, args[0]);
- }
- }
-
- extension.sendMessage("msg-done", id, resp);
- });
-
- yield extension.startup();
-
- yield extension.awaitFinish("tab-zoom");
-
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_topwindowid.js b/browser/components/extensions/test/browser/browser_ext_topwindowid.js
deleted file mode 100644
index 9176ac946..000000000
--- a/browser/components/extensions/test/browser/browser_ext_topwindowid.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* test_topwindowid_cleanup() {
- let {Frames} = Cu.import("resource://gre/modules/ExtensionManagement.jsm", {});
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/");
-
- let {outerWindowID, messageManager} = tab.linkedBrowser;
-
- ok(Frames.topWindowIds.has(outerWindowID), "Outer window ID is registered");
-
- let awaitDisconnect = TestUtils.topicObserved("message-manager-disconnect",
- subject => subject === messageManager);
-
- yield BrowserTestUtils.removeTab(tab);
-
- yield awaitDisconnect;
-
- ok(!Frames.topWindowIds.has(outerWindowID), "Outer window ID is no longer registered");
-});
-
diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js
deleted file mode 100644
index 0058ca065..000000000
--- a/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* webNavigation_getFrameId_of_existing_main_frame() {
- // Whether the frame ID in the extension API is 0 is determined by a map that
- // is maintained by |Frames| in ExtensionManagement.jsm. This map is filled
- // using data from content processes. But if ExtensionManagement.jsm is not
- // imported, then the "Extension:TopWindowID" message gets lost.
- // As a result, if the state is not synchronized again, the webNavigation API
- // will mistakenly report a non-zero frame ID for top-level frames.
- //
- // If you want to be absolutely sure that the frame ID is correct, don't open
- // tabs before starting an extension, or explicitly load the module in the
- // main process:
- // Cu.import("resource://gre/modules/ExtensionManagement.jsm", {});
- //
- // Or simply run the test again.
- const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
- const DUMMY_URL = BASE + "file_dummy.html";
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, DUMMY_URL, true);
-
- async function background(DUMMY_URL) {
- let tabs = await browser.tabs.query({active: true, currentWindow: true});
- let frames = await browser.webNavigation.getAllFrames({tabId: tabs[0].id});
- browser.test.assertEq(1, frames.length, "The dummy page has one frame");
- browser.test.assertEq(0, frames[0].frameId, "Main frame's ID must be 0");
- browser.test.assertEq(DUMMY_URL, frames[0].url, "Main frame URL must match");
- browser.test.notifyPass("frameId checked");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["webNavigation"],
- },
-
- background: `(${background})(${JSON.stringify(DUMMY_URL)});`,
- });
-
- yield extension.startup();
- yield extension.awaitFinish("frameId checked");
- yield extension.unload();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js
deleted file mode 100644
index 6b4a597ad..000000000
--- a/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js
+++ /dev/null
@@ -1,168 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testWebNavigationGetNonExistentTab() {
- let extension = ExtensionTestUtils.loadExtension({
- background: async function() {
- // There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js)
- // starts from 1.
- await browser.test.assertRejects(
- browser.webNavigation.getAllFrames({tabId: 0}),
- "Invalid tab ID: 0",
- "getAllFrames rejected Promise should pass the expected error");
-
- // There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js)
- // starts from 1, processId is currently marked as optional and it is ignored.
- await browser.test.assertRejects(
- browser.webNavigation.getFrame({tabId: 0, frameId: 15, processId: 20}),
- "Invalid tab ID: 0",
- "getFrame rejected Promise should pass the expected error");
-
- browser.test.sendMessage("getNonExistentTab.done");
- },
- manifest: {
- permissions: ["webNavigation"],
- },
- });
- info("load complete");
-
- yield extension.startup();
- info("startup complete");
-
- yield extension.awaitMessage("getNonExistentTab.done");
-
- yield extension.unload();
- info("extension unloaded");
-});
-
-add_task(function* testWebNavigationFrames() {
- let extension = ExtensionTestUtils.loadExtension({
- background: async function() {
- let tabId;
- let collectedDetails = [];
-
- browser.webNavigation.onCompleted.addListener(async details => {
- collectedDetails.push(details);
-
- if (details.frameId !== 0) {
- // wait for the top level iframe to be complete
- return;
- }
-
- let getAllFramesDetails = await browser.webNavigation.getAllFrames({tabId});
-
- let getFramePromises = getAllFramesDetails.map(({frameId}) => {
- // processId is currently marked as optional and it is ignored.
- return browser.webNavigation.getFrame({tabId, frameId, processId: 0});
- });
-
- let getFrameResults = await Promise.all(getFramePromises);
- browser.test.sendMessage("webNavigationFrames.done", {
- collectedDetails, getAllFramesDetails, getFrameResults,
- });
-
- // Pick a random frameId.
- let nonExistentFrameId = Math.floor(Math.random() * 10000);
-
- // Increment the picked random nonExistentFrameId until it doesn't exists.
- while (getAllFramesDetails.filter((details) => details.frameId == nonExistentFrameId).length > 0) {
- nonExistentFrameId += 1;
- }
-
- // Check that getFrame Promise is rejected with the expected error message on nonexistent frameId.
- await browser.test.assertRejects(
- browser.webNavigation.getFrame({tabId, frameId: nonExistentFrameId, processId: 20}),
- `No frame found with frameId: ${nonExistentFrameId}`,
- "getFrame promise should be rejected with the expected error message on unexistent frameId");
-
- await browser.tabs.remove(tabId);
- browser.test.sendMessage("webNavigationFrames.done");
- });
-
- let tab = await browser.tabs.create({url: "tab.html"});
- tabId = tab.id;
- },
- manifest: {
- permissions: ["webNavigation", "tabs"],
- },
- files: {
- "tab.html": `
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <iframe src="subframe.html"></iframe>
- <iframe src="subframe.html"></iframe>
- </body>
- </html>
- `,
- "subframe.html": `
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- </html>
- `,
- },
- });
- info("load complete");
-
- yield extension.startup();
- info("startup complete");
-
- let {
- collectedDetails,
- getAllFramesDetails,
- getFrameResults,
- } = yield extension.awaitMessage("webNavigationFrames.done");
-
- is(getAllFramesDetails.length, 3, "expected number of frames found");
- is(getAllFramesDetails.length, collectedDetails.length,
- "number of frames found should equal the number onCompleted events collected");
-
- is(getAllFramesDetails[0].frameId, 0, "the root frame has the expected frameId");
- is(getAllFramesDetails[0].parentFrameId, -1, "the root frame has the expected parentFrameId");
-
- // ordered by frameId
- let sortByFrameId = (el1, el2) => {
- let val1 = el1 ? el1.frameId : -1;
- let val2 = el2 ? el2.frameId : -1;
- return val1 - val2;
- };
-
- collectedDetails = collectedDetails.sort(sortByFrameId);
- getAllFramesDetails = getAllFramesDetails.sort(sortByFrameId);
- getFrameResults = getFrameResults.sort(sortByFrameId);
-
- info("check frame details content");
-
- is(getFrameResults.length, getAllFramesDetails.length,
- "getFrame and getAllFrames should return the same number of results");
-
- Assert.deepEqual(getFrameResults, getAllFramesDetails,
- "getFrame and getAllFrames should return the same results");
-
- info(`check frame details collected and retrieved with getAllFrames`);
-
- for (let [i, collected] of collectedDetails.entries()) {
- let getAllFramesDetail = getAllFramesDetails[i];
-
- is(getAllFramesDetail.frameId, collected.frameId, "frameId");
- is(getAllFramesDetail.parentFrameId, collected.parentFrameId, "parentFrameId");
- is(getAllFramesDetail.tabId, collected.tabId, "tabId");
-
- // This can be uncommented once Bug 1246125 has been fixed
- // is(getAllFramesDetail.url, collected.url, "url");
- }
-
- info("frame details content checked");
-
- yield extension.awaitMessage("webNavigationFrames.done");
-
- yield extension.unload();
- info("extension unloaded");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js
deleted file mode 100644
index f2ea0d901..000000000
--- a/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js
+++ /dev/null
@@ -1,251 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml";
-
-function* promiseAutocompleteResultPopup(inputText) {
- gURLBar.focus();
- gURLBar.value = inputText;
- gURLBar.controller.startSearch(inputText);
- yield promisePopupShown(gURLBar.popup);
- yield BrowserTestUtils.waitForCondition(() => {
- return gURLBar.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH;
- });
-}
-
-function* addBookmark(bookmark) {
- if (bookmark.keyword) {
- yield PlacesUtils.keywords.insert({
- keyword: bookmark.keyword,
- url: bookmark.url,
- });
- }
-
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: bookmark.url,
- title: bookmark.title,
- });
-
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.eraseEverything();
- });
-}
-
-function addSearchEngine(basename) {
- return new Promise((resolve, reject) => {
- info("Waiting for engine to be added: " + basename);
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: (engine) => {
- info(`Search engine added: ${basename}`);
- registerCleanupFunction(() => Services.search.removeEngine(engine));
- resolve(engine);
- },
- onError: (errCode) => {
- ok(false, `addEngine failed with error code ${errCode}`);
- reject();
- },
- });
- });
-}
-
-function* prepareSearchEngine() {
- let oldCurrentEngine = Services.search.currentEngine;
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
- let engine = yield addSearchEngine(TEST_ENGINE_BASENAME);
- Services.search.currentEngine = engine;
-
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF);
- Services.search.currentEngine = oldCurrentEngine;
-
- // Make sure the popup is closed for the next test.
- gURLBar.blur();
- gURLBar.popup.selectedIndex = -1;
- gURLBar.popup.hidePopup();
- ok(!gURLBar.popup.popupOpen, "popup should be closed");
-
- // Clicking suggestions causes visits to search results pages, so clear that
- // history now.
- yield PlacesTestUtils.clearHistory();
- });
-}
-
-add_task(function* test_webnavigation_urlbar_typed_transitions() {
- function backgroundScript() {
- browser.webNavigation.onCommitted.addListener((msg) => {
- browser.test.assertEq("http://example.com/?q=typed", msg.url,
- "Got the expected url");
- // assert from_address_bar transition qualifier
- browser.test.assertTrue(msg.transitionQualifiers &&
- msg.transitionQualifiers.includes("from_address_bar"),
- "Got the expected from_address_bar transitionQualifier");
- browser.test.assertEq("typed", msg.transitionType,
- "Got the expected transitionType");
- browser.test.notifyPass("webNavigation.from_address_bar.typed");
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: backgroundScript,
- manifest: {
- permissions: ["webNavigation"],
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("ready");
-
- gURLBar.focus();
- gURLBar.textValue = "http://example.com/?q=typed";
-
- EventUtils.synthesizeKey("VK_RETURN", {altKey: true});
-
- yield extension.awaitFinish("webNavigation.from_address_bar.typed");
-
- yield extension.unload();
- info("extension unloaded");
-});
-
-add_task(function* test_webnavigation_urlbar_bookmark_transitions() {
- function backgroundScript() {
- browser.webNavigation.onCommitted.addListener((msg) => {
- browser.test.assertEq("http://example.com/?q=bookmark", msg.url,
- "Got the expected url");
-
- // assert from_address_bar transition qualifier
- browser.test.assertTrue(msg.transitionQualifiers &&
- msg.transitionQualifiers.includes("from_address_bar"),
- "Got the expected from_address_bar transitionQualifier");
- browser.test.assertEq("auto_bookmark", msg.transitionType,
- "Got the expected transitionType");
- browser.test.notifyPass("webNavigation.from_address_bar.auto_bookmark");
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: backgroundScript,
- manifest: {
- permissions: ["webNavigation"],
- },
- });
-
- yield addBookmark({
- title: "Bookmark To Click",
- url: "http://example.com/?q=bookmark",
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("ready");
-
- yield promiseAutocompleteResultPopup("Bookmark To Click");
-
- let item = gURLBar.popup.richlistbox.getItemAtIndex(1);
- item.click();
- yield extension.awaitFinish("webNavigation.from_address_bar.auto_bookmark");
-
- yield extension.unload();
- info("extension unloaded");
-});
-
-add_task(function* test_webnavigation_urlbar_keyword_transition() {
- function backgroundScript() {
- browser.webNavigation.onCommitted.addListener((msg) => {
- browser.test.assertEq(`http://example.com/?q=search`, msg.url,
- "Got the expected url");
-
- // assert from_address_bar transition qualifier
- browser.test.assertTrue(msg.transitionQualifiers &&
- msg.transitionQualifiers.includes("from_address_bar"),
- "Got the expected from_address_bar transitionQualifier");
- browser.test.assertEq("keyword", msg.transitionType,
- "Got the expected transitionType");
- browser.test.notifyPass("webNavigation.from_address_bar.keyword");
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: backgroundScript,
- manifest: {
- permissions: ["webNavigation"],
- },
- });
-
- yield addBookmark({
- title: "Test Keyword",
- url: "http://example.com/?q=%s",
- keyword: "testkw",
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("ready");
-
- yield promiseAutocompleteResultPopup("testkw search");
-
- let item = gURLBar.popup.richlistbox.getItemAtIndex(0);
- item.click();
-
- yield extension.awaitFinish("webNavigation.from_address_bar.keyword");
-
- yield extension.unload();
- info("extension unloaded");
-});
-
-add_task(function* test_webnavigation_urlbar_search_transitions() {
- function backgroundScript() {
- browser.webNavigation.onCommitted.addListener((msg) => {
- browser.test.assertEq("http://mochi.test:8888/", msg.url,
- "Got the expected url");
-
- // assert from_address_bar transition qualifier
- browser.test.assertTrue(msg.transitionQualifiers &&
- msg.transitionQualifiers.includes("from_address_bar"),
- "Got the expected from_address_bar transitionQualifier");
- browser.test.assertEq("generated", msg.transitionType,
- "Got the expected 'generated' transitionType");
- browser.test.notifyPass("webNavigation.from_address_bar.generated");
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: backgroundScript,
- manifest: {
- permissions: ["webNavigation"],
- },
- });
-
- yield extension.startup();
-
- yield extension.awaitMessage("ready");
-
- yield prepareSearchEngine();
- yield promiseAutocompleteResultPopup("foo");
-
- let item = gURLBar.popup.richlistbox.getItemAtIndex(0);
- item.click();
-
- yield extension.awaitFinish("webNavigation.from_address_bar.generated");
-
- yield extension.unload();
- info("extension unloaded");
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_webRequest.js b/browser/components/extensions/test/browser/browser_ext_webRequest.js
deleted file mode 100644
index ab9f58480..000000000
--- a/browser/components/extensions/test/browser/browser_ext_webRequest.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-/* globals makeExtension */
-"use strict";
-
-Services.scriptloader.loadSubScript(new URL("head_webrequest.js", gTestPath).href,
- this);
-
-Cu.import("resource:///modules/HiddenFrame.jsm", this);
-const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
-
-function createHiddenBrowser(url) {
- let frame = new HiddenFrame();
- return new Promise(resolve =>
- frame.get().then(subframe => {
- let doc = subframe.document;
- let browser = doc.createElementNS(XUL_NS, "browser");
- browser.setAttribute("type", "content");
- browser.setAttribute("disableglobalhistory", "true");
- browser.setAttribute("src", url);
-
- doc.documentElement.appendChild(browser);
- resolve({frame: frame, browser: browser});
- }));
-}
-
-let extension;
-let dummy = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/file_dummy.html";
-
-add_task(function* setup() {
- // SelfSupport has a tendency to fire when running this test alone, without
- // a good way to turn it off we just set the url to ""
- yield SpecialPowers.pushPrefEnv({
- set: [["browser.selfsupport.url", ""]],
- });
- extension = makeExtension();
- yield extension.startup();
-});
-
-add_task(function* test_newWindow() {
- let expect = {
- "file_dummy.html": {
- type: "main_frame",
- },
- };
- // NOTE: When running solo, favicon will be loaded at some point during
- // the tests in this file, so all tests ignore it. When running with
- // other tests in this directory, favicon gets loaded at some point before
- // we run, and we never see the request, thus it cannot be handled as part
- // of expect above.
- extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]});
- yield extension.awaitMessage("continue");
-
- let openedWindow = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.openNewForegroundTab(openedWindow.gBrowser, dummy + "?newWindow");
-
- yield extension.awaitMessage("done");
- yield BrowserTestUtils.closeWindow(openedWindow);
-});
-
-add_task(function* test_newTab() {
- // again, in this window
- let expect = {
- "file_dummy.html": {
- type: "main_frame",
- },
- };
- extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]});
- yield extension.awaitMessage("continue");
- let tab = yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, dummy + "?newTab");
-
- yield extension.awaitMessage("done");
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_subframe() {
- let expect = {
- "file_dummy.html": {
- type: "main_frame",
- },
- };
- // test a content subframe attached to hidden window
- extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]});
- yield extension.awaitMessage("continue");
- let frameInfo = yield createHiddenBrowser(dummy + "?subframe");
- yield extension.awaitMessage("done");
- // cleanup
- frameInfo.browser.remove();
- frameInfo.frame.destroy();
-});
-
-add_task(function* teardown() {
- yield extension.unload();
-});
-
diff --git a/browser/components/extensions/test/browser/browser_ext_windows.js b/browser/components/extensions/test/browser/browser_ext_windows.js
deleted file mode 100644
index d3dd6ecdb..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- let raisedWin = Services.ww.openWindow(
- null, Services.prefs.getCharPref("browser.chromeURL"), "_blank",
- "chrome,dialog=no,all,alwaysRaised", null);
-
- yield TestUtils.topicObserved("browser-delayed-startup-finished",
- subject => subject == raisedWin);
-
- let extension = ExtensionTestUtils.loadExtension({
- background: function() {
- browser.windows.getAll((wins) => {
- browser.test.assertEq(wins.length, 2, "Expect two windows");
-
- browser.test.assertEq(false, wins[0].alwaysOnTop,
- "Expect first window not to be always on top");
- browser.test.assertEq(true, wins[1].alwaysOnTop,
- "Expect first window to be always on top");
-
- browser.test.notifyPass("alwaysOnTop");
- });
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("alwaysOnTop");
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(raisedWin);
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js b/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js
deleted file mode 100644
index 13f8b2eee..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-// Tests allowScriptsToClose option
-add_task(function* test_allowScriptsToClose() {
- const files = {
- "dummy.html": "<meta charset=utf-8><script src=close.js></script>",
- "close.js": function() {
- window.close();
- if (!window.closed) {
- browser.test.sendMessage("close-failed");
- }
- },
- };
-
- function background() {
- browser.test.onMessage.addListener((msg, options) => {
- function listener(_, {status}, {url}) {
- if (status == "complete" && url == options.url) {
- browser.tabs.onUpdated.removeListener(listener);
- browser.tabs.executeScript({file: "close.js"});
- }
- }
- options.url = browser.runtime.getURL(options.url);
- browser.windows.create(options);
- if (msg === "create+execute") {
- browser.tabs.onUpdated.addListener(listener);
- }
- });
- browser.test.notifyPass();
- }
-
- const example = "http://example.com/";
- const manifest = {permissions: ["tabs", example]};
-
- const extension = ExtensionTestUtils.loadExtension({files, background, manifest});
- yield SpecialPowers.pushPrefEnv({set: [["dom.allow_scripts_to_close_windows", false]]});
-
- yield extension.startup();
- yield extension.awaitFinish();
-
- extension.sendMessage("create", {url: "dummy.html"});
- let win = yield BrowserTestUtils.waitForNewWindow();
- yield BrowserTestUtils.windowClosed(win);
- info("script allowed to close the window");
-
- extension.sendMessage("create+execute", {url: example});
- win = yield BrowserTestUtils.waitForNewWindow();
- yield extension.awaitMessage("close-failed");
- info("script prevented from closing the window");
- win.close();
-
- extension.sendMessage("create+execute", {url: example, allowScriptsToClose: true});
- win = yield BrowserTestUtils.waitForNewWindow();
- yield BrowserTestUtils.windowClosed(win);
- info("script allowed to close the window");
-
- yield SpecialPowers.popPrefEnv();
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create.js b/browser/components/extensions/test/browser/browser_ext_windows_create.js
deleted file mode 100644
index f209c9836..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_create.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-requestLongerTimeout(2);
-
-add_task(function* testWindowCreate() {
- let extension = ExtensionTestUtils.loadExtension({
- async background() {
- let _checkWindowPromise;
- browser.test.onMessage.addListener(msg => {
- if (msg == "checked-window") {
- _checkWindowPromise.resolve();
- _checkWindowPromise = null;
- }
- });
-
- let os;
-
- function checkWindow(expected) {
- return new Promise(resolve => {
- _checkWindowPromise = {resolve};
- browser.test.sendMessage("check-window", expected);
- });
- }
-
- async function createWindow(params, expected, keep = false) {
- let window = await browser.windows.create(...params);
- // params is null when testing create without createData
- params = params[0] || {};
-
- for (let key of Object.keys(params)) {
- if (key == "state" && os == "mac" && params.state == "normal") {
- // OS-X doesn't have a hard distinction between "normal" and
- // "maximized" states.
- browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
- `Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
- } else {
- browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
- }
- }
-
- browser.test.assertEq(1, window.tabs.length, "tabs property got populated");
-
- await checkWindow(expected);
- if (keep) {
- return window;
- }
-
- if (params.state == "fullscreen" && os == "win") {
- // FIXME: Closing a fullscreen window causes a window leak in
- // Windows tests.
- await browser.windows.update(window.id, {state: "normal"});
- }
- await browser.windows.remove(window.id);
- }
-
- try {
- ({os} = await browser.runtime.getPlatformInfo());
-
- // Set the current window to state: "normal" because the test is failing on Windows
- // where the current window is maximized.
- let currentWindow = await browser.windows.getCurrent();
- await browser.windows.update(currentWindow.id, {state: "normal"});
-
- await createWindow([], {state: "STATE_NORMAL"});
- await createWindow([{state: "maximized"}], {state: "STATE_MAXIMIZED"});
- await createWindow([{state: "minimized"}], {state: "STATE_MINIMIZED"});
- await createWindow([{state: "normal"}], {state: "STATE_NORMAL", hiddenChrome: []});
- await createWindow([{state: "fullscreen"}], {state: "STATE_FULLSCREEN"});
-
- let window = await createWindow(
- [{type: "popup"}],
- {hiddenChrome: ["menubar", "toolbar", "location", "directories", "status", "extrachrome"],
- chromeFlags: ["CHROME_OPENAS_DIALOG"]},
- true);
-
- let tabs = await browser.tabs.query({windowType: "popup", active: true});
-
- browser.test.assertEq(1, tabs.length, "Expected only one popup");
- browser.test.assertEq(window.id, tabs[0].windowId, "Expected new window to be returned in query");
-
- await browser.windows.remove(window.id);
-
- browser.test.notifyPass("window-create");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-create");
- }
- },
- });
-
- let latestWindow;
- let windowListener = (window, topic) => {
- if (topic == "domwindowopened") {
- latestWindow = window;
- }
- };
- Services.ww.registerNotification(windowListener);
-
- extension.onMessage("check-window", expected => {
- if (expected.state != null) {
- let {windowState} = latestWindow;
- if (latestWindow.fullScreen) {
- windowState = latestWindow.STATE_FULLSCREEN;
- }
-
- if (expected.state == "STATE_NORMAL" && AppConstants.platform == "macosx") {
- ok(windowState == window.STATE_NORMAL || windowState == window.STATE_MAXIMIZED,
- `Expected windowState (currently ${windowState}) to be STATE_NORMAL but will accept STATE_MAXIMIZED`);
- } else {
- is(windowState, window[expected.state],
- `Expected window state to be ${expected.state}`);
- }
- }
- if (expected.hiddenChrome) {
- let chromeHidden = latestWindow.document.documentElement.getAttribute("chromehidden");
- is(chromeHidden.trim().split(/\s+/).sort().join(" "),
- expected.hiddenChrome.sort().join(" "),
- "Got expected hidden chrome");
- }
- if (expected.chromeFlags) {
- let {chromeFlags} = latestWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDocShell)
- .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIXULWindow);
- for (let flag of expected.chromeFlags) {
- ok(chromeFlags & Ci.nsIWebBrowserChrome[flag],
- `Expected window to have the ${flag} flag`);
- }
- }
-
- extension.sendMessage("checked-window");
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-create");
- yield extension.unload();
-
- Services.ww.unregisterNotification(windowListener);
- latestWindow = null;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_params.js b/browser/components/extensions/test/browser/browser_ext_windows_create_params.js
deleted file mode 100644
index c54d94e05..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_create_params.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-
-// Tests that incompatible parameters can't be used together.
-add_task(function* testWindowCreateParams() {
- let extension = ExtensionTestUtils.loadExtension({
- async background() {
- try {
- for (let state of ["minimized", "maximized", "fullscreen"]) {
- for (let param of ["left", "top", "width", "height"]) {
- let expected = `"state": "${state}" may not be combined with "left", "top", "width", or "height"`;
-
- await browser.test.assertRejects(
- browser.windows.create({state, [param]: 100}),
- RegExp(expected),
- `Got expected error from create(${param}=100)`);
- }
- }
-
- browser.test.notifyPass("window-create-params");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-create-params");
- }
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-create-params");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js b/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js
deleted file mode 100644
index 52ffaea8b..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testWindowCreate() {
- async function background() {
- let promiseTabAttached = () => {
- return new Promise(resolve => {
- browser.tabs.onAttached.addListener(function listener() {
- browser.tabs.onAttached.removeListener(listener);
- resolve();
- });
- });
- };
-
- let promiseTabUpdated = (expected) => {
- return new Promise(resolve => {
- browser.tabs.onUpdated.addListener(function listener(tabId, changeInfo, tab) {
- if (changeInfo.url === expected) {
- browser.tabs.onUpdated.removeListener(listener);
- resolve();
- }
- });
- });
- };
-
- try {
- let window = await browser.windows.getCurrent();
- let windowId = window.id;
-
- browser.test.log("Create additional tab in window 1");
- let tab = await browser.tabs.create({windowId, url: "about:blank"});
- let tabId = tab.id;
-
- browser.test.log("Create a new window, adopting the new tab");
-
- // Note that we want to check against actual boolean values for
- // all of the `incognito` property tests.
- browser.test.assertEq(false, tab.incognito, "Tab is not private");
-
- {
- let [, window] = await Promise.all([
- promiseTabAttached(),
- browser.windows.create({tabId: tabId}),
- ]);
- browser.test.assertEq(false, window.incognito, "New window is not private");
- browser.test.assertEq(tabId, window.tabs[0].id, "tabs property populated correctly");
-
- browser.test.log("Close the new window");
- await browser.windows.remove(window.id);
- }
-
- {
- browser.test.log("Create a new private window");
- let privateWindow = await browser.windows.create({incognito: true});
- browser.test.assertEq(true, privateWindow.incognito, "Private window is private");
-
- browser.test.log("Create additional tab in private window");
- let privateTab = await browser.tabs.create({windowId: privateWindow.id});
- browser.test.assertEq(true, privateTab.incognito, "Private tab is private");
-
- browser.test.log("Create a new window, adopting the new private tab");
- let [, newWindow] = await Promise.all([
- promiseTabAttached(),
- browser.windows.create({tabId: privateTab.id}),
- ]);
- browser.test.assertEq(true, newWindow.incognito, "New private window is private");
-
- browser.test.log("Close the new private window");
- await browser.windows.remove(newWindow.id);
-
- browser.test.log("Close the private window");
- await browser.windows.remove(privateWindow.id);
- }
-
-
- browser.test.log("Try to create a window with both a tab and a URL");
- [tab] = await browser.tabs.query({windowId, active: true});
- await browser.test.assertRejects(
- browser.windows.create({tabId: tab.id, url: "http://example.com/"}),
- /`tabId` may not be used in conjunction with `url`/,
- "Create call failed as expected");
-
- browser.test.log("Try to create a window with both a tab and an invalid incognito setting");
- await browser.test.assertRejects(
- browser.windows.create({tabId: tab.id, incognito: true}),
- /`incognito` property must match the incognito state of tab/,
- "Create call failed as expected");
-
-
- browser.test.log("Try to create a window with an invalid tabId");
- await browser.test.assertRejects(
- browser.windows.create({tabId: 0}),
- /Invalid tab ID: 0/,
- "Create call failed as expected");
-
-
- browser.test.log("Try to create a window with two URLs");
- let readyPromise = Promise.all([
- // tabs.onUpdated can be invoked between the call of windows.create and
- // the invocation of its callback/promise, so set up the listeners
- // before creating the window.
- promiseTabUpdated("http://example.com/"),
- promiseTabUpdated("http://example.org/"),
- ]);
-
- window = await browser.windows.create({url: ["http://example.com/", "http://example.org/"]});
- await readyPromise;
-
- browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window");
- browser.test.assertEq("about:blank", window.tabs[0].url, "about:blank, page not loaded yet");
- browser.test.assertEq("about:blank", window.tabs[1].url, "about:blank, page not loaded yet");
-
- window = await browser.windows.get(window.id, {populate: true});
-
- browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window");
- browser.test.assertEq("http://example.com/", window.tabs[0].url, "Correct URL was loaded in tab 1");
- browser.test.assertEq("http://example.org/", window.tabs[1].url, "Correct URL was loaded in tab 2");
-
- await browser.windows.remove(window.id);
-
- browser.test.notifyPass("window-create");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-create");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- "permissions": ["tabs"],
- },
-
- background,
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-create");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_url.js b/browser/components/extensions/test/browser/browser_ext_windows_create_url.js
deleted file mode 100644
index c5c7aaf20..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_create_url.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testWindowCreate() {
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["tabs"],
- },
-
- background: async function() {
- const EXTENSION_URL = browser.runtime.getURL("test.html");
- const REMOTE_URL = browser.runtime.getURL("test.html");
-
- let windows = new class extends Map { // eslint-disable-line new-parens
- get(id) {
- if (!this.has(id)) {
- let window = {
- tabs: new Map(),
- };
- window.promise = new Promise(resolve => {
- window.resolvePromise = resolve;
- });
-
- this.set(id, window);
- }
-
- return super.get(id);
- }
- };
-
- browser.tabs.onUpdated.addListener((tabId, changed, tab) => {
- if (changed.status == "complete" && tab.url !== "about:blank") {
- let window = windows.get(tab.windowId);
- window.tabs.set(tab.index, tab);
-
- if (window.tabs.size === window.expectedTabs) {
- window.resolvePromise(window);
- }
- }
- });
-
- async function create(options) {
- let window = await browser.windows.create(options);
- let win = windows.get(window.id);
-
- win.expectedTabs = Array.isArray(options.url) ? options.url.length : 1;
-
- return win.promise;
- }
-
- try {
- let windows = await Promise.all([
- create({url: REMOTE_URL}),
- create({url: "test.html"}),
- create({url: EXTENSION_URL}),
- create({url: [REMOTE_URL, "test.html", EXTENSION_URL]}),
- ]);
- browser.test.assertEq(REMOTE_URL, windows[0].tabs.get(0).url, "Single, absolute, remote URL");
-
- browser.test.assertEq(REMOTE_URL, windows[1].tabs.get(0).url, "Single, relative URL");
-
- browser.test.assertEq(REMOTE_URL, windows[2].tabs.get(0).url, "Single, absolute, extension URL");
-
- browser.test.assertEq(REMOTE_URL, windows[3].tabs.get(0).url, "url[0]: Absolute, remote URL");
- browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(1).url, "url[1]: Relative URL");
- browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(2).url, "url[2]: Absolute, extension URL");
-
- browser.test.notifyPass("window-create-url");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-create-url");
- }
- },
-
- files: {
- "test.html": `<DOCTYPE html><html><head><meta charset="utf-8"></head></html>`,
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-create-url");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_events.js b/browser/components/extensions/test/browser/browser_ext_windows_events.js
deleted file mode 100644
index dc3485b98..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_events.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-SimpleTest.requestCompleteLog();
-
-add_task(function* testWindowsEvents() {
- function background() {
- browser.windows.onCreated.addListener(window => {
- browser.test.log(`onCreated: windowId=${window.id}`);
-
- browser.test.assertTrue(Number.isInteger(window.id),
- "Window object's id is an integer");
- browser.test.assertEq("normal", window.type,
- "Window object returned with the correct type");
- browser.test.sendMessage("window-created", window.id);
- });
-
- let lastWindowId, os;
- browser.windows.onFocusChanged.addListener(async windowId => {
- browser.test.log(`onFocusChange: windowId=${windowId} lastWindowId=${lastWindowId}`);
-
- if (windowId === browser.windows.WINDOW_ID_NONE && os === "linux") {
- browser.test.log("Ignoring a superfluous WINDOW_ID_NONE (blur) event on Linux");
- return;
- }
-
- browser.test.assertTrue(lastWindowId !== windowId,
- "onFocusChanged fired once for the given window");
- lastWindowId = windowId;
-
- browser.test.assertTrue(Number.isInteger(windowId),
- "windowId is an integer");
-
- let window = await browser.windows.getLastFocused();
-
- browser.test.assertEq(windowId, window.id,
- "Last focused window has the correct id");
- browser.test.sendMessage(`window-focus-changed`, window.id);
- });
-
- browser.windows.onRemoved.addListener(windowId => {
- browser.test.log(`onRemoved: windowId=${windowId}`);
-
- browser.test.assertTrue(Number.isInteger(windowId),
- "windowId is an integer");
- browser.test.sendMessage(`window-removed`, windowId);
- browser.test.notifyPass("windows.events");
- });
-
- browser.runtime.getPlatformInfo(info => {
- os = info.os;
- browser.test.sendMessage("ready");
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- background: `(${background})()`,
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
-
- let currentWindow = window;
- let currentWindowId = WindowManager.getId(currentWindow);
- info(`Current window ID: ${currentWindowId}`);
-
- info(`Create browser window 1`);
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- let win1Id = yield extension.awaitMessage("window-created");
- info(`Window 1 ID: ${win1Id}`);
-
- // This shouldn't be necessary, but tests intermittently fail, so let's give
- // it a try.
- win1.focus();
-
- let winId = yield extension.awaitMessage(`window-focus-changed`);
- is(winId, win1Id, "Got focus change event for the correct window ID.");
-
- info(`Create browser window 2`);
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
- let win2Id = yield extension.awaitMessage("window-created");
- info(`Window 2 ID: ${win2Id}`);
-
- win2.focus();
-
- winId = yield extension.awaitMessage(`window-focus-changed`);
- is(winId, win2Id, "Got focus change event for the correct window ID.");
-
- info(`Focus browser window 1`);
- yield focusWindow(win1);
-
- winId = yield extension.awaitMessage(`window-focus-changed`);
- is(winId, win1Id, "Got focus change event for the correct window ID.");
-
- info(`Close browser window 2`);
- yield BrowserTestUtils.closeWindow(win2);
-
- winId = yield extension.awaitMessage(`window-removed`);
- is(winId, win2Id, "Got removed event for the correct window ID.");
-
- info(`Close browser window 1`);
- yield BrowserTestUtils.closeWindow(win1);
-
- winId = yield extension.awaitMessage(`window-removed`);
- is(winId, win1Id, "Got removed event for the correct window ID.");
-
- winId = yield extension.awaitMessage(`window-focus-changed`);
- is(winId, currentWindowId, "Got focus change event for the correct window ID.");
-
- yield extension.awaitFinish("windows.events");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_size.js b/browser/components/extensions/test/browser/browser_ext_windows_size.js
deleted file mode 100644
index be822fea1..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_size.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* testWindowCreate() {
- let extension = ExtensionTestUtils.loadExtension({
- async background() {
- let _checkWindowPromise;
- browser.test.onMessage.addListener((msg, arg) => {
- if (msg == "checked-window") {
- _checkWindowPromise.resolve(arg);
- _checkWindowPromise = null;
- }
- });
-
- let getWindowSize = () => {
- return new Promise(resolve => {
- _checkWindowPromise = {resolve};
- browser.test.sendMessage("check-window");
- });
- };
-
- const KEYS = ["left", "top", "width", "height"];
- function checkGeom(expected, actual) {
- for (let key of KEYS) {
- browser.test.assertEq(expected[key], actual[key], `Expected '${key}' value`);
- }
- }
-
- let windowId;
- async function checkWindow(expected, retries = 5) {
- let geom = await getWindowSize();
-
- if (retries && KEYS.some(key => expected[key] != geom[key])) {
- browser.test.log(`Got mismatched size (${JSON.stringify(expected)} != ${JSON.stringify(geom)}). ` +
- `Retrying after a short delay.`);
-
- await new Promise(resolve => setTimeout(resolve, 200));
-
- return checkWindow(expected, retries - 1);
- }
-
- browser.test.log(`Check actual window size`);
- checkGeom(expected, geom);
-
- browser.test.log("Check API-reported window size");
-
- geom = await browser.windows.get(windowId);
-
- checkGeom(expected, geom);
- }
-
- try {
- let geom = {left: 100, top: 100, width: 500, height: 300};
-
- let window = await browser.windows.create(geom);
- windowId = window.id;
-
- await checkWindow(geom);
-
- let update = {left: 150, width: 600};
- Object.assign(geom, update);
- await browser.windows.update(windowId, update);
- await checkWindow(geom);
-
- update = {top: 150, height: 400};
- Object.assign(geom, update);
- await browser.windows.update(windowId, update);
- await checkWindow(geom);
-
- geom = {left: 200, top: 200, width: 800, height: 600};
- await browser.windows.update(windowId, geom);
- await checkWindow(geom);
-
- let platformInfo = await browser.runtime.getPlatformInfo();
- if (platformInfo.os != "linux") {
- geom = {left: -50, top: -50, width: 800, height: 600};
- await browser.windows.update(windowId, geom);
- await checkWindow(geom);
- }
-
- await browser.windows.remove(windowId);
- browser.test.notifyPass("window-size");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-size");
- }
- },
- });
-
- let latestWindow;
- let windowListener = (window, topic) => {
- if (topic == "domwindowopened") {
- latestWindow = window;
- }
- };
- Services.ww.registerNotification(windowListener);
-
- extension.onMessage("check-window", () => {
- extension.sendMessage("checked-window", {
- top: latestWindow.screenY,
- left: latestWindow.screenX,
- width: latestWindow.outerWidth,
- height: latestWindow.outerHeight,
- });
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-size");
- yield extension.unload();
-
- Services.ww.unregisterNotification(windowListener);
- latestWindow = null;
-});
diff --git a/browser/components/extensions/test/browser/browser_ext_windows_update.js b/browser/components/extensions/test/browser/browser_ext_windows_update.js
deleted file mode 100644
index b9475547a..000000000
--- a/browser/components/extensions/test/browser/browser_ext_windows_update.js
+++ /dev/null
@@ -1,189 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-add_task(function* () {
- function promiseWaitForFocus(window) {
- return new Promise(resolve => {
- waitForFocus(function() {
- ok(Services.focus.activeWindow === window, "correct window focused");
- resolve();
- }, window);
- });
- }
-
- let window1 = window;
- let window2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- Services.focus.activeWindow = window2;
- yield promiseWaitForFocus(window2);
-
- let extension = ExtensionTestUtils.loadExtension({
- background: function() {
- browser.windows.getAll(undefined, function(wins) {
- browser.test.assertEq(wins.length, 2, "should have two windows");
-
- // Sort the unfocused window to the lower index.
- wins.sort(function(win1, win2) {
- if (win1.focused === win2.focused) {
- return 0;
- }
-
- return win1.focused ? 1 : -1;
- });
-
- browser.windows.update(wins[0].id, {focused: true}, function() {
- browser.test.sendMessage("check");
- });
- });
- },
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("check")]);
-
- yield promiseWaitForFocus(window1);
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(window2);
-});
-
-
-add_task(function* testWindowUpdate() {
- let extension = ExtensionTestUtils.loadExtension({
- async background() {
- let _checkWindowPromise;
- browser.test.onMessage.addListener(msg => {
- if (msg == "checked-window") {
- _checkWindowPromise.resolve();
- _checkWindowPromise = null;
- }
- });
-
- let os;
- function checkWindow(expected) {
- return new Promise(resolve => {
- _checkWindowPromise = {resolve};
- browser.test.sendMessage("check-window", expected);
- });
- }
-
- let currentWindowId;
- async function updateWindow(windowId, params, expected) {
- let window = await browser.windows.update(windowId, params);
-
- browser.test.assertEq(currentWindowId, window.id, "Expected WINDOW_ID_CURRENT to refer to the same window");
- for (let key of Object.keys(params)) {
- if (key == "state" && os == "mac" && params.state == "normal") {
- // OS-X doesn't have a hard distinction between "normal" and
- // "maximized" states.
- browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
- `Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
- } else {
- browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
- }
- }
-
- return checkWindow(expected);
- }
-
- try {
- let windowId = browser.windows.WINDOW_ID_CURRENT;
-
- ({os} = await browser.runtime.getPlatformInfo());
-
- let window = await browser.windows.getCurrent();
- currentWindowId = window.id;
-
- await updateWindow(windowId, {state: "maximized"}, {state: "STATE_MAXIMIZED"});
- await updateWindow(windowId, {state: "minimized"}, {state: "STATE_MINIMIZED"});
- await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"});
- await updateWindow(windowId, {state: "fullscreen"}, {state: "STATE_FULLSCREEN"});
- await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"});
-
- browser.test.notifyPass("window-update");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-update");
- }
- },
- });
-
- extension.onMessage("check-window", expected => {
- if (expected.state != null) {
- let {windowState} = window;
- if (window.fullScreen) {
- windowState = window.STATE_FULLSCREEN;
- }
-
- // Temporarily accepting STATE_MAXIMIZED on Linux because of bug 1307759.
- if (expected.state == "STATE_NORMAL" && (AppConstants.platform == "macosx" || AppConstants.platform == "linux")) {
- ok(windowState == window.STATE_NORMAL || windowState == window.STATE_MAXIMIZED,
- `Expected windowState (currently ${windowState}) to be STATE_NORMAL but will accept STATE_MAXIMIZED`);
- } else {
- is(windowState, window[expected.state],
- `Expected window state to be ${expected.state}`);
- }
- }
-
- extension.sendMessage("checked-window");
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-update");
- yield extension.unload();
-});
-
-add_task(function* () {
- let window2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- let extension = ExtensionTestUtils.loadExtension({
- background: function() {
- browser.windows.getAll(undefined, function(wins) {
- browser.test.assertEq(wins.length, 2, "should have two windows");
-
- let unfocused = wins.find(win => !win.focused);
- browser.windows.update(unfocused.id, {drawAttention: true}, function() {
- browser.test.sendMessage("check");
- });
- });
- },
- });
-
- yield Promise.all([extension.startup(), extension.awaitMessage("check")]);
-
- yield extension.unload();
-
- yield BrowserTestUtils.closeWindow(window2);
-});
-
-
-// Tests that incompatible parameters can't be used together.
-add_task(function* testWindowUpdateParams() {
- let extension = ExtensionTestUtils.loadExtension({
- async background() {
- try {
- for (let state of ["minimized", "maximized", "fullscreen"]) {
- for (let param of ["left", "top", "width", "height"]) {
- let expected = `"state": "${state}" may not be combined with "left", "top", "width", or "height"`;
-
- let windowId = browser.windows.WINDOW_ID_CURRENT;
- await browser.test.assertRejects(
- browser.windows.update(windowId, {state, [param]: 100}),
- RegExp(expected),
- `Got expected error for create(${param}=100`);
- }
- }
-
- browser.test.notifyPass("window-update-params");
- } catch (e) {
- browser.test.fail(`${e} :: ${e.stack}`);
- browser.test.notifyFail("window-update-params");
- }
- },
- });
-
- yield extension.startup();
- yield extension.awaitFinish("window-update-params");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/browser/context.html b/browser/components/extensions/test/browser/context.html
deleted file mode 100644
index 954feea52..000000000
--- a/browser/components/extensions/test/browser/context.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- just some text 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
- <img src="ctxmenu-image.png" id="img1">
-
- <p>
- <a href="some-link" id="link1">Some link</a>
- </p>
-
- <p>
- <a href="image-around-some-link">
- <img src="ctxmenu-image.png" id="img-wrapped-in-link">
- </a>
- </p>
-
- <p>
- <input type="text" id="edit-me">
- </p>
- </body>
-</html>
diff --git a/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html b/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html
deleted file mode 100644
index 0e9b54b52..000000000
--- a/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<html>
- <body>
- <h3>test iframe</h3>
- <script>
- "use strict";
-
- window.onload = function() {
- window.onhashchange = function() {
- window.parent.postMessage("updated-iframe-url", "*");
- };
- // NOTE: without the this setTimeout the location change is not fired
- // even without the "fire only for top level windows" fix
- setTimeout(function() {
- window.location.hash = "updated-iframe-url";
- }, 0);
- };
- </script>
- </body>
-</html>
diff --git a/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html b/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html
deleted file mode 100644
index 0f2ce1e8f..000000000
--- a/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
- <body>
- <h3>test page</h3>
- <iframe src="about:blank"></iframe>
- <script>
- "use strict";
-
- window.onmessage = function(evt) {
- if (evt.data === "updated-iframe-url") {
- window.postMessage("frame-updated", "*");
- }
- };
- window.onload = function() {
- document.querySelector("iframe").setAttribute("src", "context_tabs_onUpdated_iframe.html");
- };
- </script>
- </body>
-</html>
diff --git a/browser/components/extensions/test/browser/ctxmenu-image.png b/browser/components/extensions/test/browser/ctxmenu-image.png
deleted file mode 100644
index 4c3be5084..000000000
--- a/browser/components/extensions/test/browser/ctxmenu-image.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/extensions/test/browser/file_bypass_cache.sjs b/browser/components/extensions/test/browser/file_bypass_cache.sjs
deleted file mode 100644
index c91c76b88..000000000
--- a/browser/components/extensions/test/browser/file_bypass_cache.sjs
+++ /dev/null
@@ -1,11 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80 ft=javascript: */
-"use strict";
-
-function handleRequest(request, response) {
- response.setHeader("Content-Type", "text/plain; charset=UTF-8", false);
-
- if (request.hasHeader("pragma") && request.hasHeader("cache-control")) {
- response.write(`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`);
- }
-} \ No newline at end of file
diff --git a/browser/components/extensions/test/browser/file_dummy.html b/browser/components/extensions/test/browser/file_dummy.html
deleted file mode 100644
index 1a87e2840..000000000
--- a/browser/components/extensions/test/browser/file_dummy.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Dummy test page</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Dummy test page</p>
-</body>
-</html>
diff --git a/browser/components/extensions/test/browser/file_iframe_document.html b/browser/components/extensions/test/browser/file_iframe_document.html
deleted file mode 100644
index fcadccf02..000000000
--- a/browser/components/extensions/test/browser/file_iframe_document.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <title></title>
-</head>
-<body>
- <iframe src="/"></iframe>
-</body>
-</html>
diff --git a/browser/components/extensions/test/browser/file_iframe_document.sjs b/browser/components/extensions/test/browser/file_iframe_document.sjs
deleted file mode 100644
index 661a768af..000000000
--- a/browser/components/extensions/test/browser/file_iframe_document.sjs
+++ /dev/null
@@ -1,41 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80 ft=javascript: */
-"use strict";
-
-// This script slows the load of an HTML document so that we can reliably test
-// all phases of the load cycle supported by the extension API.
-
-/* eslint-disable no-unused-vars */
-
-const DELAY = 1 * 1000; // Delay one second before completing the request.
-
-const Ci = Components.interfaces;
-
-let nsTimer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");
-
-let timer;
-
-function handleRequest(request, response) {
- response.processAsync();
-
- response.setHeader("Content-Type", "text/html", false);
- response.setHeader("Cache-Control", "no-cache", false);
- response.write(`<!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title></title>
- </head>
- <body>
- `);
-
- // Note: We need to store a reference to the timer to prevent it from being
- // canceled when it's GCed.
- timer = new nsTimer(() => {
- response.write(`
- <iframe src="/"></iframe>
- </body>
- </html>`);
- response.finish();
- }, DELAY, Ci.nsITimer.TYPE_ONE_SHOT);
-}
diff --git a/browser/components/extensions/test/browser/file_language_fr_en.html b/browser/components/extensions/test/browser/file_language_fr_en.html
deleted file mode 100644
index 5e3c7b3b0..000000000
--- a/browser/components/extensions/test/browser/file_language_fr_en.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE html>
-<html lang="fr">
-<head>
- <meta charset="UTF-8">
- <title></title>
-</head>
-<body>
- France is the largest country in Western Europe and the third-largest in Europe as a whole.
- A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter
- Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France,
- Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus.
- Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumps over the lazy dog.
-</body>
-</html>
diff --git a/browser/components/extensions/test/browser/file_language_ja.html b/browser/components/extensions/test/browser/file_language_ja.html
deleted file mode 100644
index ed07ba70e..000000000
--- a/browser/components/extensions/test/browser/file_language_ja.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html lang="ja">
-<head>
- <meta charset="UTF-8">
- <title></title>
-</head>
-<body>
- ã“ã®ãƒš ジã§ã¯ アカウントã«æŒ‡å®šã•ã‚ŒãŸäºˆç®—ã®å±¥æ­´ã‚’一覧ã«ã—ã¦ã„ã¾ã™ ãã‚Œãžã‚Œã®é …ç›®ã«ã¯ 予算é¡ã¨ç‰¹å®šæœŸé–“ã®ã‚¹ãƒ† タスãŒè¡¨ç¤ºã•ã‚Œã¾ã™ ç¾åœ¨ã¾ãŸã¯ä»Šå¾Œã®äºˆç®—を設定ã™ã‚‹ã«ã¯
-</body>
-</html>
diff --git a/browser/components/extensions/test/browser/file_language_tlh.html b/browser/components/extensions/test/browser/file_language_tlh.html
deleted file mode 100644
index dd7da7bdb..000000000
--- a/browser/components/extensions/test/browser/file_language_tlh.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html lang="tlh">
-<head>
- <meta charset="UTF-8">
- <title></title>
-</head>
-<body>
- tlhIngan maH!
- Hab SoSlI' Quch!
- Heghlu'meH QaQ jajvam
-</body>
-</html>
diff --git a/browser/components/extensions/test/browser/file_popup_api_injection_a.html b/browser/components/extensions/test/browser/file_popup_api_injection_a.html
deleted file mode 100644
index 750ff1db3..000000000
--- a/browser/components/extensions/test/browser/file_popup_api_injection_a.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <script type="application/javascript">
- "use strict";
- throw new Error(`WebExt Privilege Escalation: BrowserAction: typeof(browser) = ${typeof(browser)}`);
- </script>
-</head>
-</html>
diff --git a/browser/components/extensions/test/browser/file_popup_api_injection_b.html b/browser/components/extensions/test/browser/file_popup_api_injection_b.html
deleted file mode 100644
index b8c287e55..000000000
--- a/browser/components/extensions/test/browser/file_popup_api_injection_b.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <script type="application/javascript">
- "use strict";
- throw new Error(`WebExt Privilege Escalation: PageAction: typeof(browser) = ${typeof(browser)}`);
- </script>
-</head>
-</html>
diff --git a/browser/components/extensions/test/browser/head.js b/browser/components/extensions/test/browser/head.js
deleted file mode 100644
index f8d59c944..000000000
--- a/browser/components/extensions/test/browser/head.js
+++ /dev/null
@@ -1,263 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* exported CustomizableUI makeWidgetId focusWindow forceGC
- * getBrowserActionWidget
- * clickBrowserAction clickPageAction
- * getBrowserActionPopup getPageActionPopup
- * closeBrowserAction closePageAction
- * promisePopupShown promisePopupHidden
- * openContextMenu closeContextMenu
- * openExtensionContextMenu closeExtensionContextMenu
- * imageBuffer getListStyleImage getPanelForNode
- * awaitExtensionPanel awaitPopupResize
- * promiseContentDimensions alterContent
- */
-
-var {AppConstants} = Cu.import("resource://gre/modules/AppConstants.jsm");
-var {CustomizableUI} = Cu.import("resource:///modules/CustomizableUI.jsm");
-
-// Bug 1239884: Our tests occasionally hit a long GC pause at unpredictable
-// times in debug builds, which results in intermittent timeouts. Until we have
-// a better solution, we force a GC after certain strategic tests, which tend to
-// accumulate a high number of unreaped windows.
-function forceGC() {
- if (AppConstants.DEBUG) {
- Cu.forceGC();
- }
-}
-
-function makeWidgetId(id) {
- id = id.toLowerCase();
- return id.replace(/[^a-z0-9_-]/g, "_");
-}
-
-var focusWindow = Task.async(function* focusWindow(win) {
- let fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
- if (fm.activeWindow == win) {
- return;
- }
-
- let promise = new Promise(resolve => {
- win.addEventListener("focus", function listener() {
- win.removeEventListener("focus", listener, true);
- resolve();
- }, true);
- });
-
- win.focus();
- yield promise;
-});
-
-let img = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==";
-var imageBuffer = Uint8Array.from(atob(img), byte => byte.charCodeAt(0)).buffer;
-
-function getListStyleImage(button) {
- let style = button.ownerDocument.defaultView.getComputedStyle(button);
-
- let match = /^url\("(.*)"\)$/.exec(style.listStyleImage);
-
- return match && match[1];
-}
-
-function promisePopupShown(popup) {
- return new Promise(resolve => {
- if (popup.state == "open") {
- resolve();
- } else {
- let onPopupShown = event => {
- popup.removeEventListener("popupshown", onPopupShown);
- resolve();
- };
- popup.addEventListener("popupshown", onPopupShown);
- }
- });
-}
-
-function promisePopupHidden(popup) {
- return new Promise(resolve => {
- let onPopupHidden = event => {
- popup.removeEventListener("popuphidden", onPopupHidden);
- resolve();
- };
- popup.addEventListener("popuphidden", onPopupHidden);
- });
-}
-
-function promiseContentDimensions(browser) {
- return ContentTask.spawn(browser, null, function* () {
- function copyProps(obj, props) {
- let res = {};
- for (let prop of props) {
- res[prop] = obj[prop];
- }
- return res;
- }
-
- return {
- window: copyProps(content,
- ["innerWidth", "innerHeight", "outerWidth", "outerHeight",
- "scrollX", "scrollY", "scrollMaxX", "scrollMaxY"]),
- body: copyProps(content.document.body,
- ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight"]),
- root: copyProps(content.document.documentElement,
- ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight"]),
-
- isStandards: content.document.compatMode !== "BackCompat",
- };
- });
-}
-
-function* awaitPopupResize(browser) {
- return BrowserTestUtils.waitForEvent(browser, "WebExtPopupResized",
- event => event.detail === "delayed");
-}
-
-function alterContent(browser, task, arg = null) {
- return Promise.all([
- ContentTask.spawn(browser, arg, task),
- awaitPopupResize(browser),
- ]).then(() => {
- return promiseContentDimensions(browser);
- });
-}
-
-function getPanelForNode(node) {
- while (node.localName != "panel") {
- node = node.parentNode;
- }
- return node;
-}
-
-var awaitBrowserLoaded = browser => ContentTask.spawn(browser, null, () => {
- if (content.document.readyState !== "complete") {
- return ContentTaskUtils.waitForEvent(content, "load").then(() => {});
- }
-});
-
-var awaitExtensionPanel = Task.async(function* (extension, win = window, awaitLoad = true) {
- let {originalTarget: browser} = yield BrowserTestUtils.waitForEvent(
- win.document, "WebExtPopupLoaded", true,
- event => event.detail.extension.id === extension.id);
-
- yield Promise.all([
- promisePopupShown(getPanelForNode(browser)),
-
- awaitLoad && awaitBrowserLoaded(browser),
- ]);
-
- return browser;
-});
-
-function getBrowserActionWidget(extension) {
- return CustomizableUI.getWidget(makeWidgetId(extension.id) + "-browser-action");
-}
-
-function getBrowserActionPopup(extension, win = window) {
- let group = getBrowserActionWidget(extension);
-
- if (group.areaType == CustomizableUI.TYPE_TOOLBAR) {
- return win.document.getElementById("customizationui-widget-panel");
- }
- return win.PanelUI.panel;
-}
-
-var showBrowserAction = Task.async(function* (extension, win = window) {
- let group = getBrowserActionWidget(extension);
- let widget = group.forWindow(win);
-
- if (group.areaType == CustomizableUI.TYPE_TOOLBAR) {
- ok(!widget.overflowed, "Expect widget not to be overflowed");
- } else if (group.areaType == CustomizableUI.TYPE_MENU_PANEL) {
- yield win.PanelUI.show();
- }
-});
-
-var clickBrowserAction = Task.async(function* (extension, win = window) {
- yield showBrowserAction(extension, win);
-
- let widget = getBrowserActionWidget(extension).forWindow(win);
-
- EventUtils.synthesizeMouseAtCenter(widget.node, {}, win);
-});
-
-function closeBrowserAction(extension, win = window) {
- let group = getBrowserActionWidget(extension);
-
- let node = win.document.getElementById(group.viewId);
- CustomizableUI.hidePanelForNode(node);
-
- return Promise.resolve();
-}
-
-function* openContextMenu(selector = "#img1") {
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter(selector, {type: "contextmenu"}, gBrowser.selectedBrowser);
- yield popupShownPromise;
- return contentAreaContextMenu;
-}
-
-function* closeContextMenu() {
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- contentAreaContextMenu.hidePopup();
- yield popupHiddenPromise;
-}
-
-function* openExtensionContextMenu(selector = "#img1") {
- let contextMenu = yield openContextMenu(selector);
- let topLevelMenu = contextMenu.getElementsByAttribute("ext-type", "top-level-menu");
-
- // Return null if the extension only has one item and therefore no extension menu.
- if (topLevelMenu.length == 0) {
- return null;
- }
-
- let extensionMenu = topLevelMenu[0].childNodes[0];
- let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(extensionMenu, {});
- yield popupShownPromise;
- return extensionMenu;
-}
-
-function* closeExtensionContextMenu(itemToSelect) {
- let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
- EventUtils.synthesizeMouseAtCenter(itemToSelect, {});
- yield popupHiddenPromise;
-}
-
-function getPageActionPopup(extension, win = window) {
- let panelId = makeWidgetId(extension.id) + "-panel";
- return win.document.getElementById(panelId);
-}
-
-function clickPageAction(extension, win = window) {
- // This would normally be set automatically on navigation, and cleared
- // when the user types a value into the URL bar, to show and hide page
- // identity info and icons such as page action buttons.
- //
- // Unfortunately, that doesn't happen automatically in browser chrome
- // tests.
- /* globals SetPageProxyState */
- SetPageProxyState("valid");
-
- let pageActionId = makeWidgetId(extension.id) + "-page-action";
- let elem = win.document.getElementById(pageActionId);
-
- EventUtils.synthesizeMouseAtCenter(elem, {}, win);
- return new Promise(SimpleTest.executeSoon);
-}
-
-function closePageAction(extension, win = window) {
- let node = getPageActionPopup(extension, win);
- if (node) {
- return promisePopupShown(node).then(() => {
- node.hidePopup();
- });
- }
-
- return Promise.resolve();
-}
diff --git a/browser/components/extensions/test/browser/head_pageAction.js b/browser/components/extensions/test/browser/head_pageAction.js
deleted file mode 100644
index f2d81e512..000000000
--- a/browser/components/extensions/test/browser/head_pageAction.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* exported runTests */
-/* globals getListStyleImage */
-
-function* runTests(options) {
- function background(getTests) {
- let tabs;
- let tests;
-
- // Gets the current details of the page action, and returns a
- // promise that resolves to an object containing them.
- async function getDetails() {
- let [tab] = await browser.tabs.query({active: true, currentWindow: true});
- let tabId = tab.id;
-
- browser.test.log(`Get details: tab={id: ${tabId}, url: ${JSON.stringify(tab.url)}}`);
-
- return {
- title: await browser.pageAction.getTitle({tabId}),
- popup: await browser.pageAction.getPopup({tabId}),
- };
- }
-
-
- // Runs the next test in the `tests` array, checks the results,
- // and passes control back to the outer test scope.
- function nextTest() {
- let test = tests.shift();
-
- test(async expecting => {
- function finish() {
- // Check that the actual icon has the expected values, then
- // run the next test.
- browser.test.sendMessage("nextTest", expecting, tests.length);
- }
-
- if (expecting) {
- // Check that the API returns the expected values, and then
- // run the next test.
- let details = await getDetails();
-
- browser.test.assertEq(expecting.title, details.title,
- "expected value from getTitle");
-
- browser.test.assertEq(expecting.popup, details.popup,
- "expected value from getPopup");
- }
-
- finish();
- });
- }
-
- async function runTests() {
- tabs = [];
- tests = getTests(tabs);
-
- let resultTabs = await browser.tabs.query({active: true, currentWindow: true});
-
- tabs[0] = resultTabs[0].id;
-
- nextTest();
- }
-
- browser.test.onMessage.addListener((msg) => {
- if (msg == "runTests") {
- runTests();
- } else if (msg == "runNextTest") {
- nextTest();
- } else {
- browser.test.fail(`Unexpected message: ${msg}`);
- }
- });
-
- runTests();
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: options.manifest,
-
- files: options.files || {},
-
- background: `(${background})(${options.getTests})`,
- });
-
- let pageActionId;
- let currentWindow = window;
- let windows = [];
-
- function checkDetails(details) {
- let image = currentWindow.document.getElementById(pageActionId);
- if (details == null) {
- ok(image == null || image.hidden, "image is hidden");
- } else {
- ok(image, "image exists");
-
- is(getListStyleImage(image), details.icon, "icon URL is correct");
-
- let title = details.title || options.manifest.name;
- is(image.getAttribute("tooltiptext"), title, "image title is correct");
- is(image.getAttribute("aria-label"), title, "image aria-label is correct");
- // TODO: Popup URL.
- }
- }
-
- let testNewWindows = 1;
-
- let awaitFinish = new Promise(resolve => {
- extension.onMessage("nextTest", (expecting, testsRemaining) => {
- if (!pageActionId) {
- pageActionId = `${makeWidgetId(extension.id)}-page-action`;
- }
-
- checkDetails(expecting);
-
- if (testsRemaining) {
- extension.sendMessage("runNextTest");
- } else if (testNewWindows) {
- testNewWindows--;
-
- BrowserTestUtils.openNewBrowserWindow().then(window => {
- windows.push(window);
- currentWindow = window;
- return focusWindow(window);
- }).then(() => {
- extension.sendMessage("runTests");
- });
- } else {
- resolve();
- }
- });
- });
-
- yield SpecialPowers.pushPrefEnv({set: [["general.useragent.locale", "es-ES"]]});
-
- yield extension.startup();
-
- yield awaitFinish;
-
- yield extension.unload();
-
- yield SpecialPowers.popPrefEnv();
-
- let node = document.getElementById(pageActionId);
- is(node, null, "pageAction image removed from document");
-
- currentWindow = null;
- for (let win of windows.splice(0)) {
- node = win.document.getElementById(pageActionId);
- is(node, null, "pageAction image removed from second document");
-
- yield BrowserTestUtils.closeWindow(win);
- }
-}
-
diff --git a/browser/components/extensions/test/browser/head_sessions.js b/browser/components/extensions/test/browser/head_sessions.js
deleted file mode 100644
index ca3a86c24..000000000
--- a/browser/components/extensions/test/browser/head_sessions.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* exported recordInitialTimestamps onlyNewItemsFilter checkRecentlyClosed */
-
-let initialTimestamps = [];
-
-function recordInitialTimestamps(timestamps) {
- initialTimestamps = timestamps;
-}
-
-function onlyNewItemsFilter(item) {
- return !initialTimestamps.includes(item.lastModified);
-}
-
-function checkWindow(window) {
- for (let prop of ["focused", "incognito", "alwaysOnTop"]) {
- is(window[prop], false, `closed window has the expected value for ${prop}`);
- }
- for (let prop of ["state", "type"]) {
- is(window[prop], "normal", `closed window has the expected value for ${prop}`);
- }
-}
-
-function checkTab(tab, windowId, incognito) {
- for (let prop of ["selected", "highlighted", "active", "pinned"]) {
- is(tab[prop], false, `closed tab has the expected value for ${prop}`);
- }
- is(tab.windowId, windowId, "closed tab has the expected value for windowId");
- is(tab.incognito, incognito, "closed tab has the expected value for incognito");
-}
-
-function checkRecentlyClosed(recentlyClosed, expectedCount, windowId, incognito = false) {
- let sessionIds = new Set();
- is(recentlyClosed.length, expectedCount, "the expected number of closed tabs/windows was found");
- for (let item of recentlyClosed) {
- if (item.window) {
- sessionIds.add(item.window.sessionId);
- checkWindow(item.window);
- } else if (item.tab) {
- sessionIds.add(item.tab.sessionId);
- checkTab(item.tab, windowId, incognito);
- }
- }
- is(sessionIds.size, expectedCount, "each item has a unique sessionId");
-}
diff --git a/browser/components/extensions/test/browser/searchSuggestionEngine.sjs b/browser/components/extensions/test/browser/searchSuggestionEngine.sjs
deleted file mode 100644
index 1978b4f66..000000000
--- a/browser/components/extensions/test/browser/searchSuggestionEngine.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(req, resp) {
- let suffixes = ["foo", "bar"];
- let data = [req.queryString, suffixes.map(s => req.queryString + s)];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
-}
diff --git a/browser/components/extensions/test/browser/searchSuggestionEngine.xml b/browser/components/extensions/test/browser/searchSuggestionEngine.xml
deleted file mode 100644
index 703d45925..000000000
--- a/browser/components/extensions/test/browser/searchSuggestionEngine.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_searchSuggestionEngine searchSuggestionEngine.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/components/extensions/test/browser/searchSuggestionEngine.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://mochi.test:8888/" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/components/extensions/test/mochitest/mochitest.ini b/browser/components/extensions/test/mochitest/mochitest.ini
deleted file mode 100644
index 39290db61..000000000
--- a/browser/components/extensions/test/mochitest/mochitest.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-support-files =
- ../../../../../toolkit/components/extensions/test/mochitest/test_ext_all_apis.js
-tags = webextensions
-
-[test_ext_all_apis.html]
diff --git a/browser/components/extensions/test/mochitest/test_ext_all_apis.html b/browser/components/extensions/test/mochitest/test_ext_all_apis.html
deleted file mode 100644
index 176d380c2..000000000
--- a/browser/components/extensions/test/mochitest/test_ext_all_apis.html
+++ /dev/null
@@ -1,75 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>WebExtension test</title>
- <meta charset="utf-8">
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
-</head>
-<body>
-<script>
-"use strict";
-/* exported expectedContentApisTargetSpecific, expectedBackgroundApisTargetSpecific */
-let expectedContentApisTargetSpecific = [
-];
-
-let expectedBackgroundApisTargetSpecific = [
- "tabs.MutedInfoReason",
- "tabs.TAB_ID_NONE",
- "tabs.TabStatus",
- "tabs.WindowType",
- "tabs.ZoomSettingsMode",
- "tabs.ZoomSettingsScope",
- "tabs.connect",
- "tabs.create",
- "tabs.detectLanguage",
- "tabs.duplicate",
- "tabs.executeScript",
- "tabs.get",
- "tabs.getCurrent",
- "tabs.getZoom",
- "tabs.getZoomSettings",
- "tabs.highlight",
- "tabs.insertCSS",
- "tabs.move",
- "tabs.onActivated",
- "tabs.onAttached",
- "tabs.onCreated",
- "tabs.onDetached",
- "tabs.onHighlighted",
- "tabs.onMoved",
- "tabs.onRemoved",
- "tabs.onReplaced",
- "tabs.onUpdated",
- "tabs.onZoomChange",
- "tabs.query",
- "tabs.reload",
- "tabs.remove",
- "tabs.removeCSS",
- "tabs.sendMessage",
- "tabs.setZoom",
- "tabs.setZoomSettings",
- "tabs.update",
- "windows.CreateType",
- "windows.WINDOW_ID_CURRENT",
- "windows.WINDOW_ID_NONE",
- "windows.WindowState",
- "windows.WindowType",
- "windows.create",
- "windows.get",
- "windows.getAll",
- "windows.getCurrent",
- "windows.getLastFocused",
- "windows.onCreated",
- "windows.onFocusChanged",
- "windows.onRemoved",
- "windows.remove",
- "windows.update",
-];
-</script>
-<script src="test_ext_all_apis.js"></script>
-
-</body>
-</html>
diff --git a/browser/components/extensions/test/xpcshell/.eslintrc.js b/browser/components/extensions/test/xpcshell/.eslintrc.js
deleted file mode 100644
index 2bfe540ea..000000000
--- a/browser/components/extensions/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,9 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": "../../../../../testing/xpcshell/xpcshell.eslintrc.js",
-
- "globals": {
- "browser": false,
- },
-};
diff --git a/browser/components/extensions/test/xpcshell/head.js b/browser/components/extensions/test/xpcshell/head.js
deleted file mode 100644
index de4a4a3f6..000000000
--- a/browser/components/extensions/test/xpcshell/head.js
+++ /dev/null
@@ -1,55 +0,0 @@
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-/* exported createHttpServer */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
- "resource://gre/modules/AppConstants.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Extension",
- "resource://gre/modules/Extension.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionData",
- "resource://gre/modules/Extension.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
- "resource://gre/modules/ExtensionManagement.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestUtils",
- "resource://testing-common/ExtensionXPCShellUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
- "resource://testing-common/httpd.js");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
- "resource://gre/modules/Schemas.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-
-ExtensionTestUtils.init(this);
-
-
-/**
- * Creates a new HttpServer for testing, and begins listening on the
- * specified port. Automatically shuts down the server when the test
- * unit ends.
- *
- * @param {integer} [port]
- * The port to listen on. If omitted, listen on a random
- * port. The latter is the preferred behavior.
- *
- * @returns {HttpServer}
- */
-function createHttpServer(port = -1) {
- let server = new HttpServer();
- server.start(port);
-
- do_register_cleanup(() => {
- return new Promise(resolve => {
- server.stop(resolve);
- });
- });
-
- return server;
-}
diff --git a/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js b/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js
deleted file mode 100644
index 142c0a37c..000000000
--- a/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js
+++ /dev/null
@@ -1,601 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function backgroundScript() {
- let unsortedId, ourId;
- let initialBookmarkCount = 0;
- let createdBookmarks = new Set();
- let createdFolderId;
- let collectedEvents = [];
- const nonExistentId = "000000000000";
- const bookmarkGuids = {
- menuGuid: "menu________",
- toolbarGuid: "toolbar_____",
- unfiledGuid: "unfiled_____",
- };
-
- function checkOurBookmark(bookmark) {
- browser.test.assertEq(ourId, bookmark.id, "Bookmark has the expected Id");
- browser.test.assertTrue("parentId" in bookmark, "Bookmark has a parentId");
- browser.test.assertEq(0, bookmark.index, "Bookmark has the expected index"); // We assume there are no other bookmarks.
- browser.test.assertEq("http://example.org/", bookmark.url, "Bookmark has the expected url");
- browser.test.assertEq("test bookmark", bookmark.title, "Bookmark has the expected title");
- browser.test.assertTrue("dateAdded" in bookmark, "Bookmark has a dateAdded");
- browser.test.assertFalse("dateGroupModified" in bookmark, "Bookmark does not have a dateGroupModified");
- browser.test.assertFalse("unmodifiable" in bookmark, "Bookmark is not unmodifiable");
- }
-
- function checkBookmark(expected, bookmark) {
- browser.test.assertEq(expected.url, bookmark.url, "Bookmark has the expected url");
- browser.test.assertEq(expected.title, bookmark.title, "Bookmark has the expected title");
- browser.test.assertEq(expected.index, bookmark.index, "Bookmark has expected index");
- if ("parentId" in expected) {
- browser.test.assertEq(expected.parentId, bookmark.parentId, "Bookmark has the expected parentId");
- }
- }
-
- function expectedError() {
- browser.test.fail("Did not get expected error");
- }
-
- function checkOnCreated(id, parentId, index, title, url, dateAdded) {
- let createdData = collectedEvents.pop();
- browser.test.assertEq("onCreated", createdData.event, "onCreated was the last event received");
- browser.test.assertEq(id, createdData.id, "onCreated event received the expected id");
- let bookmark = createdData.bookmark;
- browser.test.assertEq(id, bookmark.id, "onCreated event received the expected bookmark id");
- browser.test.assertEq(parentId, bookmark.parentId, "onCreated event received the expected bookmark parentId");
- browser.test.assertEq(index, bookmark.index, "onCreated event received the expected bookmark index");
- browser.test.assertEq(title, bookmark.title, "onCreated event received the expected bookmark title");
- browser.test.assertEq(url, bookmark.url, "onCreated event received the expected bookmark url");
- browser.test.assertEq(dateAdded, bookmark.dateAdded, "onCreated event received the expected bookmark dateAdded");
- }
-
- function checkOnChanged(id, url, title) {
- // If both url and title are changed, then url is fired last.
- let changedData = collectedEvents.pop();
- browser.test.assertEq("onChanged", changedData.event, "onChanged was the last event received");
- browser.test.assertEq(id, changedData.id, "onChanged event received the expected id");
- browser.test.assertEq(url, changedData.info.url, "onChanged event received the expected url");
- // title is fired first.
- changedData = collectedEvents.pop();
- browser.test.assertEq("onChanged", changedData.event, "onChanged was the last event received");
- browser.test.assertEq(id, changedData.id, "onChanged event received the expected id");
- browser.test.assertEq(title, changedData.info.title, "onChanged event received the expected title");
- }
-
- function checkOnMoved(id, parentId, oldParentId, index, oldIndex) {
- let movedData = collectedEvents.pop();
- browser.test.assertEq("onMoved", movedData.event, "onMoved was the last event received");
- browser.test.assertEq(id, movedData.id, "onMoved event received the expected id");
- let info = movedData.info;
- browser.test.assertEq(parentId, info.parentId, "onMoved event received the expected parentId");
- browser.test.assertEq(oldParentId, info.oldParentId, "onMoved event received the expected oldParentId");
- browser.test.assertEq(index, info.index, "onMoved event received the expected index");
- browser.test.assertEq(oldIndex, info.oldIndex, "onMoved event received the expected oldIndex");
- }
-
- function checkOnRemoved(id, parentId, index, url) {
- let removedData = collectedEvents.pop();
- browser.test.assertEq("onRemoved", removedData.event, "onRemoved was the last event received");
- browser.test.assertEq(id, removedData.id, "onRemoved event received the expected id");
- let info = removedData.info;
- browser.test.assertEq(parentId, removedData.info.parentId, "onRemoved event received the expected parentId");
- browser.test.assertEq(index, removedData.info.index, "onRemoved event received the expected index");
- let node = info.node;
- browser.test.assertEq(id, node.id, "onRemoved event received the expected node id");
- browser.test.assertEq(parentId, node.parentId, "onRemoved event received the expected node parentId");
- browser.test.assertEq(index, node.index, "onRemoved event received the expected node index");
- browser.test.assertEq(url, node.url, "onRemoved event received the expected node url");
- }
-
- browser.bookmarks.onChanged.addListener((id, info) => {
- collectedEvents.push({event: "onChanged", id, info});
- });
-
- browser.bookmarks.onCreated.addListener((id, bookmark) => {
- collectedEvents.push({event: "onCreated", id, bookmark});
- });
-
- browser.bookmarks.onMoved.addListener((id, info) => {
- collectedEvents.push({event: "onMoved", id, info});
- });
-
- browser.bookmarks.onRemoved.addListener((id, info) => {
- collectedEvents.push({event: "onRemoved", id, info});
- });
-
- browser.bookmarks.get(["not-a-bookmark-guid"]).then(expectedError, invalidGuidError => {
- browser.test.assertTrue(
- invalidGuidError.message.includes("Invalid value for property 'guid': not-a-bookmark-guid"),
- "Expected error thrown when trying to get a bookmark using an invalid guid"
- );
-
- return browser.bookmarks.get([nonExistentId]).then(expectedError, nonExistentIdError => {
- browser.test.assertTrue(
- nonExistentIdError.message.includes("Bookmark not found"),
- "Expected error thrown when trying to get a bookmark using a non-existent Id"
- );
- });
- }).then(() => {
- return browser.bookmarks.search({});
- }).then(results => {
- initialBookmarkCount = results.length;
- return browser.bookmarks.create({title: "test bookmark", url: "http://example.org"});
- }).then(result => {
- ourId = result.id;
- checkOurBookmark(result);
- browser.test.assertEq(1, collectedEvents.length, "1 expected event received");
- checkOnCreated(ourId, bookmarkGuids.unfiledGuid, 0, "test bookmark", "http://example.org/", result.dateAdded);
-
- return browser.bookmarks.get(ourId);
- }).then(results => {
- browser.test.assertEq(results.length, 1);
- checkOurBookmark(results[0]);
-
- unsortedId = results[0].parentId;
- return browser.bookmarks.get(unsortedId);
- }).then(results => {
- let folder = results[0];
- browser.test.assertEq(1, results.length, "1 bookmark was returned");
-
- browser.test.assertEq(unsortedId, folder.id, "Folder has the expected id");
- browser.test.assertTrue("parentId" in folder, "Folder has a parentId");
- browser.test.assertTrue("index" in folder, "Folder has an index");
- browser.test.assertFalse("url" in folder, "Folder does not have a url");
- browser.test.assertEq("Other Bookmarks", folder.title, "Folder has the expected title");
- browser.test.assertTrue("dateAdded" in folder, "Folder has a dateAdded");
- browser.test.assertTrue("dateGroupModified" in folder, "Folder has a dateGroupModified");
- browser.test.assertFalse("unmodifiable" in folder, "Folder is not unmodifiable"); // TODO: Do we want to enable this?
-
- return browser.bookmarks.getChildren(unsortedId);
- }).then(results => {
- browser.test.assertEq(1, results.length, "The folder has one child");
- checkOurBookmark(results[0]);
-
- return browser.bookmarks.update(nonExistentId, {title: "new test title"}).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("No bookmarks found for the provided GUID"),
- "Expected error thrown when trying to update a non-existent bookmark"
- );
-
- return browser.bookmarks.update(ourId, {title: "new test title", url: "http://example.com/"});
- });
- }).then(result => {
- browser.test.assertEq("new test title", result.title, "Updated bookmark has the expected title");
- browser.test.assertEq("http://example.com/", result.url, "Updated bookmark has the expected URL");
- browser.test.assertEq(ourId, result.id, "Updated bookmark has the expected id");
-
- browser.test.assertEq(2, collectedEvents.length, "2 expected events received");
- checkOnChanged(ourId, "http://example.com/", "new test title");
-
- return Promise.resolve().then(() => {
- return browser.bookmarks.update(ourId, {url: "this is not a valid url"});
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Invalid bookmark:"),
- "Expected error thrown when trying update with an invalid url"
- );
- return browser.bookmarks.getTree();
- });
- }).then(results => {
- browser.test.assertEq(1, results.length, "getTree returns one result");
- let bookmark = results[0].children.find(bookmarkItem => bookmarkItem.id == unsortedId);
- browser.test.assertEq(
- "Other Bookmarks",
- bookmark.title,
- "Folder returned from getTree has the expected title"
- );
-
- return browser.bookmarks.create({parentId: "invalid"}).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Invalid bookmark"),
- "Expected error thrown when trying to create a bookmark with an invalid parentId"
- );
- browser.test.assertTrue(
- error.message.includes(`"parentGuid":"invalid"`),
- "Expected error thrown when trying to create a bookmark with an invalid parentId"
- );
- });
- }).then(() => {
- return browser.bookmarks.remove(ourId);
- }).then(result => {
- browser.test.assertEq(undefined, result, "Removing a bookmark returns undefined");
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnRemoved(ourId, bookmarkGuids.unfiledGuid, 0, "http://example.com/");
-
- return browser.bookmarks.get(ourId).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Bookmark not found"),
- "Expected error thrown when trying to get a removed bookmark"
- );
- });
- }).then(() => {
- return browser.bookmarks.remove(nonExistentId).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("No bookmarks found for the provided GUID"),
- "Expected error thrown when trying removed a non-existent bookmark"
- );
- });
- }).then(() => {
- // test bookmarks.search
- return Promise.all([
- browser.bookmarks.create({title: "MØzillä", url: "http://møzîllä.örg/"}),
- browser.bookmarks.create({title: "Example", url: "http://example.org/"}),
- browser.bookmarks.create({title: "Mozilla Folder"}),
- browser.bookmarks.create({title: "EFF", url: "http://eff.org/"}),
- browser.bookmarks.create({title: "Menu Item", url: "http://menu.org/", parentId: bookmarkGuids.menuGuid}),
- browser.bookmarks.create({title: "Toolbar Item", url: "http://toolbar.org/", parentId: bookmarkGuids.toolbarGuid}),
- ]);
- }).then(results => {
- browser.test.assertEq(6, collectedEvents.length, "6 expected events received");
- checkOnCreated(results[5].id, bookmarkGuids.toolbarGuid, 0, "Toolbar Item", "http://toolbar.org/", results[5].dateAdded);
- checkOnCreated(results[4].id, bookmarkGuids.menuGuid, 0, "Menu Item", "http://menu.org/", results[4].dateAdded);
- checkOnCreated(results[3].id, bookmarkGuids.unfiledGuid, 0, "EFF", "http://eff.org/", results[3].dateAdded);
- checkOnCreated(results[2].id, bookmarkGuids.unfiledGuid, 0, "Mozilla Folder", undefined, results[2].dateAdded);
- checkOnCreated(results[1].id, bookmarkGuids.unfiledGuid, 0, "Example", "http://example.org/", results[1].dateAdded);
- checkOnCreated(results[0].id, bookmarkGuids.unfiledGuid, 0, "MØzillä", "http://møzîllä.örg/", results[0].dateAdded);
-
- for (let result of results) {
- if (result.title !== "Mozilla Folder") {
- createdBookmarks.add(result.id);
- }
- }
- let folderResult = results[2];
- createdFolderId = folderResult.id;
- return Promise.all([
- browser.bookmarks.create({title: "Mozilla", url: "http://allizom.org/", parentId: createdFolderId}),
- browser.bookmarks.create({title: "Mozilla Corporation", url: "http://allizom.com/", parentId: createdFolderId}),
- browser.bookmarks.create({title: "Firefox", url: "http://allizom.org/firefox/", parentId: createdFolderId}),
- ]).then(newBookmarks => {
- browser.test.assertEq(3, collectedEvents.length, "3 expected events received");
- checkOnCreated(newBookmarks[2].id, createdFolderId, 0, "Firefox", "http://allizom.org/firefox/", newBookmarks[2].dateAdded);
- checkOnCreated(newBookmarks[1].id, createdFolderId, 0, "Mozilla Corporation", "http://allizom.com/", newBookmarks[1].dateAdded);
- checkOnCreated(newBookmarks[0].id, createdFolderId, 0, "Mozilla", "http://allizom.org/", newBookmarks[0].dateAdded);
-
- return browser.bookmarks.create({
- title: "About Mozilla",
- url: "http://allizom.org/about/",
- parentId: createdFolderId,
- index: 1,
- });
- }).then(result => {
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnCreated(result.id, createdFolderId, 1, "About Mozilla", "http://allizom.org/about/", result.dateAdded);
-
- // returns all items on empty object
- return browser.bookmarks.search({});
- }).then(bookmarksSearchResults => {
- browser.test.assertTrue(bookmarksSearchResults.length >= 9, "At least as many bookmarks as added were returned by search({})");
-
- return Promise.resolve().then(() => {
- return browser.bookmarks.remove(createdFolderId);
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Cannot remove a non-empty folder"),
- "Expected error thrown when trying to remove a non-empty folder"
- );
- return browser.bookmarks.getSubTree(createdFolderId);
- });
- });
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of nodes returned by getSubTree");
- browser.test.assertEq("Mozilla Folder", results[0].title, "Folder has the expected title");
- let children = results[0].children;
- browser.test.assertEq(4, children.length, "Expected number of bookmarks returned by getSubTree");
- browser.test.assertEq("Firefox", children[0].title, "Bookmark has the expected title");
- browser.test.assertEq("About Mozilla", children[1].title, "Bookmark has the expected title");
- browser.test.assertEq(1, children[1].index, "Bookmark has the expected index");
- browser.test.assertEq("Mozilla Corporation", children[2].title, "Bookmark has the expected title");
- browser.test.assertEq("Mozilla", children[3].title, "Bookmark has the expected title");
-
- // throws an error for invalid query objects
- Promise.resolve().then(() => {
- return browser.bookmarks.search();
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Incorrect argument types for bookmarks.search"),
- "Expected error thrown when trying to search with no arguments"
- );
- });
-
- Promise.resolve().then(() => {
- return browser.bookmarks.search(null);
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Incorrect argument types for bookmarks.search"),
- "Expected error thrown when trying to search with null as an argument"
- );
- });
-
- Promise.resolve().then(() => {
- return browser.bookmarks.search(function() {});
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Incorrect argument types for bookmarks.search"),
- "Expected error thrown when trying to search with a function as an argument"
- );
- });
-
- Promise.resolve().then(() => {
- return browser.bookmarks.search({banana: "banana"});
- }).then(expectedError, error => {
- let substr = `an unexpected "banana" property`;
- browser.test.assertTrue(
- error.message.includes(substr),
- `Expected error ${JSON.stringify(error.message)} to contain ${JSON.stringify(substr)}`);
- });
-
- Promise.resolve().then(() => {
- return browser.bookmarks.search({url: "spider-man vs. batman"});
- }).then(expectedError, error => {
- let substr = 'must match the format "url"';
- browser.test.assertTrue(
- error.message.includes(substr),
- `Expected error ${JSON.stringify(error.message)} to contain ${JSON.stringify(substr)}`);
- });
-
- // queries the full url
- return browser.bookmarks.search("http://example.org/");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for url search");
- checkBookmark({title: "Example", url: "http://example.org/", index: 2}, results[0]);
-
- // queries a partial url
- return browser.bookmarks.search("example.org");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for url search");
- checkBookmark({title: "Example", url: "http://example.org/", index: 2}, results[0]);
-
- // queries the title
- return browser.bookmarks.search("EFF");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for title search");
- checkBookmark({title: "EFF", url: "http://eff.org/", index: 0, parentId: bookmarkGuids.unfiledGuid}, results[0]);
-
- // finds menu items
- return browser.bookmarks.search("Menu Item");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for menu item search");
- checkBookmark({title: "Menu Item", url: "http://menu.org/", index: 0, parentId: bookmarkGuids.menuGuid}, results[0]);
-
- // finds toolbar items
- return browser.bookmarks.search("Toolbar Item");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for toolbar item search");
- checkBookmark({title: "Toolbar Item", url: "http://toolbar.org/", index: 0, parentId: bookmarkGuids.toolbarGuid}, results[0]);
-
- // finds folders
- return browser.bookmarks.search("Mozilla Folder");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of folders returned");
- browser.test.assertEq("Mozilla Folder", results[0].title, "Folder has the expected title");
-
- // is case-insensitive
- return browser.bookmarks.search("corporation");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returnedfor case-insensitive search");
- browser.test.assertEq("Mozilla Corporation", results[0].title, "Bookmark has the expected title");
-
- // is case-insensitive for non-ascii
- return browser.bookmarks.search("MøZILLÄ");
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for non-ascii search");
- browser.test.assertEq("MØzillä", results[0].title, "Bookmark has the expected title");
-
- // returns multiple results
- return browser.bookmarks.search("allizom");
- }).then(results => {
- browser.test.assertEq(4, results.length, "Expected number of multiple results returned");
- browser.test.assertEq("Mozilla", results[0].title, "Bookmark has the expected title");
- browser.test.assertEq("Mozilla Corporation", results[1].title, "Bookmark has the expected title");
- browser.test.assertEq("Firefox", results[2].title, "Bookmark has the expected title");
- browser.test.assertEq("About Mozilla", results[3].title, "Bookmark has the expected title");
-
- // accepts a url field
- return browser.bookmarks.search({url: "http://allizom.com/"});
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for url field");
- checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]);
-
- // normalizes urls
- return browser.bookmarks.search({url: "http://allizom.com"});
- }).then(results => {
- browser.test.assertEq(results.length, 1, "Expected number of results returned for normalized url field");
- checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]);
-
- // normalizes urls even more
- return browser.bookmarks.search({url: "http:allizom.com"});
- }).then(results => {
- browser.test.assertEq(results.length, 1, "Expected number of results returned for normalized url field");
- checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]);
-
- // accepts a title field
- return browser.bookmarks.search({title: "Mozilla"});
- }).then(results => {
- browser.test.assertEq(results.length, 1, "Expected number of results returned for title field");
- checkBookmark({title: "Mozilla", url: "http://allizom.org/", index: 3}, results[0]);
-
- // can combine title and query
- return browser.bookmarks.search({title: "Mozilla", query: "allizom"});
- }).then(results => {
- browser.test.assertEq(1, results.length, "Expected number of results returned for title and query fields");
- checkBookmark({title: "Mozilla", url: "http://allizom.org/", index: 3}, results[0]);
-
- // uses AND conditions
- return browser.bookmarks.search({title: "EFF", query: "allizom"});
- }).then(results => {
- browser.test.assertEq(
- 0,
- results.length,
- "Expected number of results returned for non-matching title and query fields"
- );
-
- // returns an empty array on item not found
- return browser.bookmarks.search("microsoft");
- }).then(results => {
- browser.test.assertEq(0, results.length, "Expected number of results returned for non-matching search");
-
- return Promise.resolve().then(() => {
- return browser.bookmarks.getRecent("");
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Incorrect argument types for bookmarks.getRecent"),
- "Expected error thrown when calling getRecent with an empty string"
- );
- });
- }).then(() => {
- return Promise.resolve().then(() => {
- return browser.bookmarks.getRecent(1.234);
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Incorrect argument types for bookmarks.getRecent"),
- "Expected error thrown when calling getRecent with a decimal number"
- );
- });
- }).then(() => {
- return Promise.all([
- browser.bookmarks.search("corporation"),
- browser.bookmarks.getChildren(bookmarkGuids.menuGuid),
- ]);
- }).then(results => {
- let corporationBookmark = results[0][0];
- let childCount = results[1].length;
-
- browser.test.assertEq(2, corporationBookmark.index, "Bookmark has the expected index");
-
- return browser.bookmarks.move(corporationBookmark.id, {index: 0}).then(result => {
- browser.test.assertEq(0, result.index, "Bookmark has the expected index");
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnMoved(corporationBookmark.id, createdFolderId, createdFolderId, 0, 2);
-
- return browser.bookmarks.move(corporationBookmark.id, {parentId: bookmarkGuids.menuGuid});
- }).then(result => {
- browser.test.assertEq(bookmarkGuids.menuGuid, result.parentId, "Bookmark has the expected parent");
- browser.test.assertEq(childCount, result.index, "Bookmark has the expected index");
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnMoved(corporationBookmark.id, bookmarkGuids.menuGuid, createdFolderId, 1, 0);
-
- return browser.bookmarks.move(corporationBookmark.id, {index: 0});
- }).then(result => {
- browser.test.assertEq(bookmarkGuids.menuGuid, result.parentId, "Bookmark has the expected parent");
- browser.test.assertEq(0, result.index, "Bookmark has the expected index");
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnMoved(corporationBookmark.id, bookmarkGuids.menuGuid, bookmarkGuids.menuGuid, 0, 1);
-
- return browser.bookmarks.move(corporationBookmark.id, {parentId: bookmarkGuids.toolbarGuid, index: 1});
- }).then(result => {
- browser.test.assertEq(bookmarkGuids.toolbarGuid, result.parentId, "Bookmark has the expected parent");
- browser.test.assertEq(1, result.index, "Bookmark has the expected index");
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnMoved(corporationBookmark.id, bookmarkGuids.toolbarGuid, bookmarkGuids.menuGuid, 1, 0);
-
- createdBookmarks.add(corporationBookmark.id);
- });
- }).then(() => {
- return browser.bookmarks.getRecent(4);
- }).then(results => {
- browser.test.assertEq(4, results.length, "Expected number of results returned by getRecent");
- let prevDate = results[0].dateAdded;
- for (let bookmark of results) {
- browser.test.assertTrue(bookmark.dateAdded <= prevDate, "The recent bookmarks are sorted by dateAdded");
- prevDate = bookmark.dateAdded;
- }
- let bookmarksByTitle = results.sort((a, b) => {
- return a.title.localeCompare(b.title);
- });
- browser.test.assertEq("About Mozilla", bookmarksByTitle[0].title, "Bookmark has the expected title");
- browser.test.assertEq("Firefox", bookmarksByTitle[1].title, "Bookmark has the expected title");
- browser.test.assertEq("Mozilla", bookmarksByTitle[2].title, "Bookmark has the expected title");
- browser.test.assertEq("Mozilla Corporation", bookmarksByTitle[3].title, "Bookmark has the expected title");
-
- return browser.bookmarks.search({});
- }).then(results => {
- let startBookmarkCount = results.length;
-
- return browser.bookmarks.search({title: "Mozilla Folder"}).then(result => {
- return browser.bookmarks.removeTree(result[0].id);
- }).then(() => {
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnRemoved(createdFolderId, bookmarkGuids.unfiledGuid, 1);
-
- return browser.bookmarks.search({}).then(searchResults => {
- browser.test.assertEq(
- startBookmarkCount - 4,
- searchResults.length,
- "Expected number of results returned after removeTree");
- });
- });
- }).then(() => {
- return browser.bookmarks.create({title: "Empty Folder"});
- }).then(result => {
- let emptyFolderId = result.id;
-
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnCreated(emptyFolderId, bookmarkGuids.unfiledGuid, 3, "Empty Folder", undefined, result.dateAdded);
-
- browser.test.assertEq("Empty Folder", result.title, "Folder has the expected title");
- return browser.bookmarks.remove(emptyFolderId).then(() => {
- browser.test.assertEq(1, collectedEvents.length, "1 expected events received");
- checkOnRemoved(emptyFolderId, bookmarkGuids.unfiledGuid, 3);
-
- return browser.bookmarks.get(emptyFolderId).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("Bookmark not found"),
- "Expected error thrown when trying to get a removed folder"
- );
- });
- });
- }).then(() => {
- return browser.bookmarks.getChildren(nonExistentId).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("root is null"),
- "Expected error thrown when trying to getChildren for a non-existent folder"
- );
- });
- }).then(() => {
- return Promise.resolve().then(() => {
- return browser.bookmarks.move(nonExistentId, {});
- }).then(expectedError, error => {
- browser.test.assertTrue(
- error.message.includes("No bookmarks found for the provided GUID"),
- "Expected error thrown when calling move with a non-existent bookmark"
- );
- });
- }).then(() => {
- // remove all created bookmarks
- let promises = Array.from(createdBookmarks, guid => browser.bookmarks.remove(guid));
- return Promise.all(promises);
- }).then(() => {
- browser.test.assertEq(createdBookmarks.size, collectedEvents.length, "expected number of events received");
-
- return browser.bookmarks.search({});
- }).then(results => {
- browser.test.assertEq(initialBookmarkCount, results.length, "All created bookmarks have been removed");
-
- return browser.test.notifyPass("bookmarks");
- }).catch(error => {
- browser.test.fail(`Error: ${String(error)} :: ${error.stack}`);
- browser.test.notifyFail("bookmarks");
- });
-}
-
-let extensionData = {
- background: `(${backgroundScript})()`,
- manifest: {
- permissions: ["bookmarks"],
- },
-};
-
-add_task(function* test_contentscript() {
- let extension = ExtensionTestUtils.loadExtension(extensionData);
- yield extension.startup();
- yield extension.awaitFinish("bookmarks");
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/xpcshell/test_ext_history.js b/browser/components/extensions/test/xpcshell/test_ext_history.js
deleted file mode 100644
index 78df33151..000000000
--- a/browser/components/extensions/test/xpcshell/test_ext_history.js
+++ /dev/null
@@ -1,487 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils",
- "resource://gre/modules/ExtensionUtils.jsm");
-
-add_task(function* test_delete() {
- function background() {
- let historyClearedCount = 0;
- let removedUrls = [];
-
- browser.history.onVisitRemoved.addListener(data => {
- if (data.allHistory) {
- historyClearedCount++;
- browser.test.assertEq(0, data.urls.length, "onVisitRemoved received an empty urls array");
- } else {
- browser.test.assertEq(1, data.urls.length, "onVisitRemoved received one URL");
- removedUrls.push(data.urls[0]);
- }
- });
-
- browser.test.onMessage.addListener((msg, arg) => {
- if (msg === "delete-url") {
- browser.history.deleteUrl({url: arg}).then(result => {
- browser.test.assertEq(undefined, result, "browser.history.deleteUrl returns nothing");
- browser.test.sendMessage("url-deleted");
- });
- } else if (msg === "delete-range") {
- browser.history.deleteRange(arg).then(result => {
- browser.test.assertEq(undefined, result, "browser.history.deleteRange returns nothing");
- browser.test.sendMessage("range-deleted", removedUrls);
- });
- } else if (msg === "delete-all") {
- browser.history.deleteAll().then(result => {
- browser.test.assertEq(undefined, result, "browser.history.deleteAll returns nothing");
- browser.test.sendMessage("history-cleared", [historyClearedCount, removedUrls]);
- });
- }
- });
-
- browser.test.sendMessage("ready");
- }
-
- const BASE_URL = "http://mozilla.com/test_history/";
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["history"],
- },
- background: `(${background})()`,
- });
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
- yield PlacesTestUtils.clearHistory();
-
- let historyClearedCount;
- let visits = [];
- let visitDate = new Date(1999, 9, 9, 9, 9).getTime();
-
- function pushVisit(subvisits) {
- visitDate += 1000;
- subvisits.push({date: new Date(visitDate)});
- }
-
- // Add 5 visits for one uri and 3 visits for 3 others
- for (let i = 0; i < 4; ++i) {
- let visit = {
- url: `${BASE_URL}${i}`,
- title: "visit " + i,
- visits: [],
- };
- if (i === 0) {
- for (let j = 0; j < 5; ++j) {
- pushVisit(visit.visits);
- }
- } else {
- pushVisit(visit.visits);
- }
- visits.push(visit);
- }
-
- yield PlacesUtils.history.insertMany(visits);
- equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 5, "5 visits for uri found in history database");
-
- let testUrl = visits[2].url;
- ok((yield PlacesTestUtils.isPageInDB(testUrl)), "expected url found in history database");
-
- extension.sendMessage("delete-url", testUrl);
- yield extension.awaitMessage("url-deleted");
- equal((yield PlacesTestUtils.isPageInDB(testUrl)), false, "expected url not found in history database");
-
- // delete 3 of the 5 visits for url 1
- let filter = {
- startTime: visits[0].visits[0].date,
- endTime: visits[0].visits[2].date,
- };
-
- extension.sendMessage("delete-range", filter);
- let removedUrls = yield extension.awaitMessage("range-deleted");
- ok(!removedUrls.includes(visits[0].url), `${visits[0].url} not received by onVisitRemoved`);
- ok((yield PlacesTestUtils.isPageInDB(visits[0].url)), "expected uri found in history database");
- equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 2, "2 visits for uri found in history database");
- ok((yield PlacesTestUtils.isPageInDB(visits[1].url)), "expected uri found in history database");
- equal((yield PlacesTestUtils.visitsInDB(visits[1].url)), 1, "1 visit for uri found in history database");
-
- // delete the rest of the visits for url 1, and the visit for url 2
- filter.startTime = visits[0].visits[0].date;
- filter.endTime = visits[1].visits[0].date;
-
- extension.sendMessage("delete-range", filter);
- yield extension.awaitMessage("range-deleted");
-
- equal((yield PlacesTestUtils.isPageInDB(visits[0].url)), false, "expected uri not found in history database");
- equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 0, "0 visits for uri found in history database");
- equal((yield PlacesTestUtils.isPageInDB(visits[1].url)), false, "expected uri not found in history database");
- equal((yield PlacesTestUtils.visitsInDB(visits[1].url)), 0, "0 visits for uri found in history database");
-
- ok((yield PlacesTestUtils.isPageInDB(visits[3].url)), "expected uri found in history database");
-
- extension.sendMessage("delete-all");
- [historyClearedCount, removedUrls] = yield extension.awaitMessage("history-cleared");
- equal(PlacesUtils.history.hasHistoryEntries, false, "history is empty");
- equal(historyClearedCount, 2, "onVisitRemoved called for each clearing of history");
- equal(removedUrls.length, 3, "onVisitRemoved called the expected number of times");
- for (let i = 1; i < 3; ++i) {
- let url = visits[i].url;
- ok(removedUrls.includes(url), `${url} received by onVisitRemoved`);
- }
- yield extension.unload();
-});
-
-add_task(function* test_search() {
- const SINGLE_VISIT_URL = "http://example.com/";
- const DOUBLE_VISIT_URL = "http://example.com/2/";
- const MOZILLA_VISIT_URL = "http://mozilla.com/";
- const REFERENCE_DATE = new Date();
- // pages/visits to add via History.insert
- const PAGE_INFOS = [
- {
- url: SINGLE_VISIT_URL,
- title: `test visit for ${SINGLE_VISIT_URL}`,
- visits: [
- {date: new Date(Number(REFERENCE_DATE) - 1000)},
- ],
- },
- {
- url: DOUBLE_VISIT_URL,
- title: `test visit for ${DOUBLE_VISIT_URL}`,
- visits: [
- {date: REFERENCE_DATE},
- {date: new Date(Number(REFERENCE_DATE) - 2000)},
- ],
- },
- {
- url: MOZILLA_VISIT_URL,
- title: `test visit for ${MOZILLA_VISIT_URL}`,
- visits: [
- {date: new Date(Number(REFERENCE_DATE) - 3000)},
- ],
- },
- ];
-
- function background(BGSCRIPT_REFERENCE_DATE) {
- const futureTime = Date.now() + 24 * 60 * 60 * 1000;
-
- browser.test.onMessage.addListener(msg => {
- browser.history.search({text: ""}).then(results => {
- browser.test.sendMessage("empty-search", results);
- return browser.history.search({text: "mozilla.com"});
- }).then(results => {
- browser.test.sendMessage("text-search", results);
- return browser.history.search({text: "example.com", maxResults: 1});
- }).then(results => {
- browser.test.sendMessage("max-results-search", results);
- return browser.history.search({text: "", startTime: BGSCRIPT_REFERENCE_DATE - 2000, endTime: BGSCRIPT_REFERENCE_DATE - 1000});
- }).then(results => {
- browser.test.sendMessage("date-range-search", results);
- return browser.history.search({text: "", startTime: futureTime});
- }).then(results => {
- browser.test.assertEq(0, results.length, "no results returned for late start time");
- return browser.history.search({text: "", endTime: 0});
- }).then(results => {
- browser.test.assertEq(0, results.length, "no results returned for early end time");
- return browser.history.search({text: "", startTime: Date.now(), endTime: 0});
- }).then(results => {
- browser.test.fail("history.search rejects with startTime that is after the endTime");
- }, error => {
- browser.test.assertEq(
- "The startTime cannot be after the endTime",
- error.message,
- "history.search rejects with startTime that is after the endTime");
- }).then(() => {
- browser.test.notifyPass("search");
- });
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["history"],
- },
- background: `(${background})(${Number(REFERENCE_DATE)})`,
- });
-
- function findResult(url, results) {
- return results.find(r => r.url === url);
- }
-
- function checkResult(results, url, expectedCount) {
- let result = findResult(url, results);
- notEqual(result, null, `history.search result was found for ${url}`);
- equal(result.visitCount, expectedCount, `history.search reports ${expectedCount} visit(s)`);
- equal(result.title, `test visit for ${url}`, "title for search result is correct");
- }
-
- yield extension.startup();
- yield extension.awaitMessage("ready");
- yield PlacesTestUtils.clearHistory();
-
- yield PlacesUtils.history.insertMany(PAGE_INFOS);
-
- extension.sendMessage("check-history");
-
- let results = yield extension.awaitMessage("empty-search");
- equal(results.length, 3, "history.search with empty text returned 3 results");
- checkResult(results, SINGLE_VISIT_URL, 1);
- checkResult(results, DOUBLE_VISIT_URL, 2);
- checkResult(results, MOZILLA_VISIT_URL, 1);
-
- results = yield extension.awaitMessage("text-search");
- equal(results.length, 1, "history.search with specific text returned 1 result");
- checkResult(results, MOZILLA_VISIT_URL, 1);
-
- results = yield extension.awaitMessage("max-results-search");
- equal(results.length, 1, "history.search with maxResults returned 1 result");
- checkResult(results, DOUBLE_VISIT_URL, 2);
-
- results = yield extension.awaitMessage("date-range-search");
- equal(results.length, 2, "history.search with a date range returned 2 result");
- checkResult(results, DOUBLE_VISIT_URL, 2);
- checkResult(results, SINGLE_VISIT_URL, 1);
-
- yield extension.awaitFinish("search");
- yield extension.unload();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_add_url() {
- function background() {
- const TEST_DOMAIN = "http://example.com/";
-
- browser.test.onMessage.addListener((msg, testData) => {
- let [details, type] = testData;
- details.url = details.url || `${TEST_DOMAIN}${type}`;
- if (msg === "add-url") {
- details.title = `Title for ${type}`;
- browser.history.addUrl(details).then(() => {
- return browser.history.search({text: details.url});
- }).then(results => {
- browser.test.assertEq(1, results.length, "1 result found when searching for added URL");
- browser.test.sendMessage("url-added", {details, result: results[0]});
- });
- } else if (msg === "expect-failure") {
- let expectedMsg = testData[2];
- browser.history.addUrl(details).then(() => {
- browser.test.fail(`Expected error thrown for ${type}`);
- }, error => {
- browser.test.assertTrue(
- error.message.includes(expectedMsg),
- `"Expected error thrown when trying to add a URL with ${type}`
- );
- browser.test.sendMessage("add-failed");
- });
- }
- });
-
- browser.test.sendMessage("ready");
- }
-
- let addTestData = [
- [{}, "default"],
- [{visitTime: new Date()}, "with_date"],
- [{visitTime: Date.now()}, "with_ms_number"],
- [{visitTime: new Date().toISOString()}, "with_iso_string"],
- [{transition: "typed"}, "valid_transition"],
- ];
-
- let failTestData = [
- [{transition: "generated"}, "an invalid transition", "|generated| is not a supported transition for history"],
- [{visitTime: Date.now() + 1000000}, "a future date", "cannot be a future date"],
- [{url: "about.config"}, "an invalid url", "about.config is not a valid URL"],
- ];
-
- function* checkUrl(results) {
- ok((yield PlacesTestUtils.isPageInDB(results.details.url)), `${results.details.url} found in history database`);
- ok(PlacesUtils.isValidGuid(results.result.id), "URL was added with a valid id");
- equal(results.result.title, results.details.title, "URL was added with the correct title");
- if (results.details.visitTime) {
- equal(results.result.lastVisitTime,
- Number(ExtensionUtils.normalizeTime(results.details.visitTime)),
- "URL was added with the correct date");
- }
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["history"],
- },
- background: `(${background})()`,
- });
-
- yield PlacesTestUtils.clearHistory();
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- for (let data of addTestData) {
- extension.sendMessage("add-url", data);
- let results = yield extension.awaitMessage("url-added");
- yield checkUrl(results);
- }
-
- for (let data of failTestData) {
- extension.sendMessage("expect-failure", data);
- yield extension.awaitMessage("add-failed");
- }
-
- yield extension.unload();
-});
-
-add_task(function* test_get_visits() {
- function background() {
- const TEST_DOMAIN = "http://example.com/";
- const FIRST_DATE = Date.now();
- const INITIAL_DETAILS = {
- url: TEST_DOMAIN,
- visitTime: FIRST_DATE,
- transition: "link",
- };
-
- let visitIds = new Set();
-
- function checkVisit(visit, expected) {
- visitIds.add(visit.visitId);
- browser.test.assertEq(expected.visitTime, visit.visitTime, "visit has the correct visitTime");
- browser.test.assertEq(expected.transition, visit.transition, "visit has the correct transition");
- browser.history.search({text: expected.url}).then(results => {
- // all results will have the same id, so we only need to use the first one
- browser.test.assertEq(results[0].id, visit.id, "visit has the correct id");
- });
- }
-
- let details = Object.assign({}, INITIAL_DETAILS);
-
- browser.history.addUrl(details).then(() => {
- return browser.history.getVisits({url: details.url});
- }).then(results => {
- browser.test.assertEq(1, results.length, "the expected number of visits were returned");
- checkVisit(results[0], details);
- details.url = `${TEST_DOMAIN}/1/`;
- return browser.history.addUrl(details);
- }).then(() => {
- return browser.history.getVisits({url: details.url});
- }).then(results => {
- browser.test.assertEq(1, results.length, "the expected number of visits were returned");
- checkVisit(results[0], details);
- details.visitTime = FIRST_DATE - 1000;
- details.transition = "typed";
- return browser.history.addUrl(details);
- }).then(() => {
- return browser.history.getVisits({url: details.url});
- }).then(results => {
- browser.test.assertEq(2, results.length, "the expected number of visits were returned");
- checkVisit(results[0], INITIAL_DETAILS);
- checkVisit(results[1], details);
- }).then(() => {
- browser.test.assertEq(3, visitIds.size, "each visit has a unique visitId");
- browser.test.notifyPass("get-visits");
- });
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["history"],
- },
- background: `(${background})()`,
- });
-
- yield PlacesTestUtils.clearHistory();
- yield extension.startup();
-
- yield extension.awaitFinish("get-visits");
- yield extension.unload();
-});
-
-add_task(function* test_on_visited() {
- const SINGLE_VISIT_URL = "http://example.com/1/";
- const DOUBLE_VISIT_URL = "http://example.com/2/";
- let visitDate = new Date(1999, 9, 9, 9, 9).getTime();
-
- // pages/visits to add via History.insertMany
- const PAGE_INFOS = [
- {
- url: SINGLE_VISIT_URL,
- title: `visit to ${SINGLE_VISIT_URL}`,
- visits: [
- {date: new Date(visitDate)},
- ],
- },
- {
- url: DOUBLE_VISIT_URL,
- title: `visit to ${DOUBLE_VISIT_URL}`,
- visits: [
- {date: new Date(visitDate += 1000)},
- {date: new Date(visitDate += 1000)},
- ],
- },
- ];
-
- function background() {
- let onVisitedData = [];
-
- browser.history.onVisited.addListener(data => {
- if (data.url.includes("moz-extension")) {
- return;
- }
- onVisitedData.push(data);
- if (onVisitedData.length == 3) {
- browser.test.sendMessage("on-visited-data", onVisitedData);
- }
- });
-
- browser.test.sendMessage("ready");
- }
-
- let extension = ExtensionTestUtils.loadExtension({
- manifest: {
- permissions: ["history"],
- },
- background: `(${background})()`,
- });
-
- yield PlacesTestUtils.clearHistory();
- yield extension.startup();
- yield extension.awaitMessage("ready");
-
- yield PlacesUtils.history.insertMany(PAGE_INFOS);
-
- let onVisitedData = yield extension.awaitMessage("on-visited-data");
-
- function checkOnVisitedData(index, expected) {
- let onVisited = onVisitedData[index];
- ok(PlacesUtils.isValidGuid(onVisited.id), "onVisited received a valid id");
- equal(onVisited.url, expected.url, "onVisited received the expected url");
- // Title will be blank until bug 1287928 lands
- // https://bugzilla.mozilla.org/show_bug.cgi?id=1287928
- equal(onVisited.title, "", "onVisited received a blank title");
- equal(onVisited.lastVisitTime, expected.time, "onVisited received the expected time");
- equal(onVisited.visitCount, expected.visitCount, "onVisited received the expected visitCount");
- }
-
- let expected = {
- url: PAGE_INFOS[0].url,
- title: PAGE_INFOS[0].title,
- time: PAGE_INFOS[0].visits[0].date.getTime(),
- visitCount: 1,
- };
- checkOnVisitedData(0, expected);
-
- expected.url = PAGE_INFOS[1].url;
- expected.title = PAGE_INFOS[1].title;
- expected.time = PAGE_INFOS[1].visits[0].date.getTime();
- checkOnVisitedData(1, expected);
-
- expected.time = PAGE_INFOS[1].visits[1].date.getTime();
- expected.visitCount = 2;
- checkOnVisitedData(2, expected);
-
- yield extension.unload();
-});
diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js
deleted file mode 100644
index 4de7afe01..000000000
--- a/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-
-add_task(function* test_manifest_commands() {
- let normalized = yield ExtensionTestUtils.normalizeManifest({
- "commands": {
- "toggle-feature": {
- "suggested_key": {"default": "Shifty+Y"},
- "description": "Send a 'toggle-feature' event to the extension",
- },
- },
- });
-
- let expectedError = (
- String.raw`commands.toggle-feature.suggested_key.default: Value must either: ` +
- String.raw`match the pattern /^\s*(Alt|Ctrl|Command|MacCtrl)\s*\+\s*(Shift\s*\+\s*)?([A-Z0-9]|Comma|Period|Home|End|PageUp|PageDown|Space|Insert|Delete|Up|Down|Left|Right)\s*$/, or ` +
- String.raw`match the pattern /^(MediaNextTrack|MediaPlayPause|MediaPrevTrack|MediaStop)$/`
- );
-
- ok(normalized.error.includes(expectedError),
- `The manifest error ${JSON.stringify(normalized.error)} must contain ${JSON.stringify(expectedError)}`);
-});
diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js
deleted file mode 100644
index 2cb141235..000000000
--- a/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-function* testKeyword(params) {
- let normalized = yield ExtensionTestUtils.normalizeManifest({
- "omnibox": {
- "keyword": params.keyword,
- },
- });
-
- if (params.expectError) {
- let expectedError = (
- String.raw`omnibox.keyword: String "${params.keyword}" ` +
- String.raw`must match /^[^?\s:]([^\s:]*[^/\s:])?$/`
- );
- ok(normalized.error.includes(expectedError),
- `The manifest error ${JSON.stringify(normalized.error)} ` +
- `must contain ${JSON.stringify(expectedError)}`);
- } else {
- equal(normalized.error, undefined, "Should not have an error");
- equal(normalized.errors.length, 0, "Should not have warnings");
- }
-}
-
-add_task(function* test_manifest_commands() {
- // accepted single character keywords
- yield testKeyword({keyword: "a", expectError: false});
- yield testKeyword({keyword: "-", expectError: false});
- yield testKeyword({keyword: "å—¨", expectError: false});
- yield testKeyword({keyword: "*", expectError: false});
- yield testKeyword({keyword: "/", expectError: false});
-
- // rejected single character keywords
- yield testKeyword({keyword: "?", expectError: true});
- yield testKeyword({keyword: " ", expectError: true});
- yield testKeyword({keyword: ":", expectError: true});
-
- // accepted multi-character keywords
- yield testKeyword({keyword: "aa", expectError: false});
- yield testKeyword({keyword: "http", expectError: false});
- yield testKeyword({keyword: "f?a", expectError: false});
- yield testKeyword({keyword: "fa?", expectError: false});
- yield testKeyword({keyword: "f/x", expectError: false});
- yield testKeyword({keyword: "/fx", expectError: false});
-
- // rejected multi-character keywords
- yield testKeyword({keyword: " a", expectError: true});
- yield testKeyword({keyword: "a ", expectError: true});
- yield testKeyword({keyword: " ", expectError: true});
- yield testKeyword({keyword: " a ", expectError: true});
- yield testKeyword({keyword: "?fx", expectError: true});
- yield testKeyword({keyword: "fx/", expectError: true});
- yield testKeyword({keyword: "f:x", expectError: true});
- yield testKeyword({keyword: "fx:", expectError: true});
- yield testKeyword({keyword: "f x", expectError: true});
-
- // miscellaneous tests
- yield testKeyword({keyword: "ã“ã‚“ã«ã¡ã¯", expectError: false});
- yield testKeyword({keyword: "http://", expectError: true});
-});
diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js
deleted file mode 100644
index 2c436535d..000000000
--- a/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set sts=2 sw=2 et tw=80: */
-"use strict";
-
-/* globals chrome */
-
-function* testPermission(options) {
- function background(bgOptions) {
- browser.test.sendMessage("typeof-namespace", {
- browser: typeof browser[bgOptions.namespace],
- chrome: typeof chrome[bgOptions.namespace],
- });
- }
-
- let extensionDetails = {
- background: `(${background})(${JSON.stringify(options)})`,
- };
-
- let extension = ExtensionTestUtils.loadExtension(extensionDetails);
-
- yield extension.startup();
-
- let types = yield extension.awaitMessage("typeof-namespace");
- equal(types.browser, "undefined", `Type of browser.${options.namespace} without manifest entry`);
- equal(types.chrome, "undefined", `Type of chrome.${options.namespace} without manifest entry`);
-
- yield extension.unload();
-
- extensionDetails.manifest = options.manifest;
- extension = ExtensionTestUtils.loadExtension(extensionDetails);
-
- yield extension.startup();
-
- types = yield extension.awaitMessage("typeof-namespace");
- equal(types.browser, "object", `Type of browser.${options.namespace} with manifest entry`);
- equal(types.chrome, "object", `Type of chrome.${options.namespace} with manifest entry`);
-
- yield extension.unload();
-}
-
-add_task(function* test_browserAction() {
- yield testPermission({
- namespace: "browserAction",
- manifest: {
- browser_action: {},
- },
- });
-});
-
-add_task(function* test_pageAction() {
- yield testPermission({
- namespace: "pageAction",
- manifest: {
- page_action: {},
- },
- });
-});
diff --git a/browser/components/extensions/test/xpcshell/xpcshell.ini b/browser/components/extensions/test/xpcshell/xpcshell.ini
deleted file mode 100644
index b9148a697..000000000
--- a/browser/components/extensions/test/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-tags = webextensions
-
-[test_ext_bookmarks.js]
-[test_ext_history.js]
-[test_ext_manifest_commands.js]
-[test_ext_manifest_omnibox.js]
-[test_ext_manifest_permissions.js]
diff --git a/browser/components/feeds/test/.eslintrc.js b/browser/components/feeds/test/.eslintrc.js
deleted file mode 100644
index 3c788d6d6..000000000
--- a/browser/components/feeds/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/browser/components/feeds/test/bug368464-data.xml b/browser/components/feeds/test/bug368464-data.xml
deleted file mode 100644
index 2745b061d..000000000
--- a/browser/components/feeds/test/bug368464-data.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0"?>
- <rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://my.netscape.com/rdf/simple/0.9/">
- <channel>
- <title>Tinderbox - Firefox</title>
- <description>Build bustages for Firefox</description>
- <link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link>
- </channel>
- <image>
- <title>Bad</title>
- <url>http://tinderbox.mozilla.org/channelflames.gif</url>
- <link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link>
- </image>
- <item><title>The tree is currently closed</title><link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link></item>
-
-<item><title>MacOSX Darwin 8.8.4 qm-xserve01 dep unit test is in flames</title><link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link></item>
-</rdf:RDF>
diff --git a/browser/components/feeds/test/bug408328-data.xml b/browser/components/feeds/test/bug408328-data.xml
deleted file mode 100644
index e9385e5ab..000000000
--- a/browser/components/feeds/test/bug408328-data.xml
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
-
- <title>Good item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>data: link</title>
- <link href="data:text/plain,Hi"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b</id>
- <updated>2003-12-13T18:30:03Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>javascript: link</title>
- <link href="javascript:alert('Hi')"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6c</id>
- <updated>2003-12-13T18:30:04Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>file: link</title>
- <link href="file:///var/"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6d</id>
- <updated>2003-12-13T18:30:05Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>chrome: link</title>
- <link href="chrome://browser/content/browser.js"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6e</id>
- <updated>2003-12-13T18:30:06Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/feeds/test/bug436801-data.xml b/browser/components/feeds/test/bug436801-data.xml
deleted file mode 100644
index 0e45c7ed8..000000000
--- a/browser/components/feeds/test/bug436801-data.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom" xml:base="http://www.example.com/">
-
- <title type="xhtml" xml:base="/foo/bar/">
- <div xmlns="http://www.w3.org/1999/xhtml">Example of a <em>special</em> feed (<img height="20px" src="baz.png" alt="base test sprite"/>)</div>
- </title>
-
- <subtitle type="html" xml:base="/foo/bar/">
- <![CDATA[
- With a <em>special</em> subtitle (<img height="20px" src="baz.png" alt="base test sprite"/>)
- ]]>
- </subtitle>
-
- <link href="http://example.org/"/>
-
- <updated>2010-09-02T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
-
- <id>urn:uuid:22906062-ecbd-46e2-b6a7-3039506a398f</id>
-
- <entry>
- <title type="xhtml" xml:base="/foo/bar/">
- <div xmlns="http://www.w3.org/1999/xhtml">Some <abbr title="Extensible Hyper-text Mark-up Language">XHTML</abbr> examples (<img height="20px" src="baz.png" alt="base test sprite"/>)</div>
- </title>
- <id>urn:uuid:b48083a7-71a7-4c9c-8515-b7c0d22955e7</id>
- <updated>2010-09-02T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
- <entry>
- <title type="html" xml:base="/foo/bar/">
- <![CDATA[
- Some <abbr title="Hyper-text Mark-up Language">HTML</abbr> examples (<img height="20px" src="baz.png" alt="base test sprite"/>)
- ]]>
- </title>
- <id>urn:uuid:1424967a-280a-414d-b0ab-8b11c4ac1bb7</id>
- <updated>2010-09-02T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/feeds/test/bug494328-data.xml b/browser/components/feeds/test/bug494328-data.xml
deleted file mode 100644
index 58342bafc..000000000
--- a/browser/components/feeds/test/bug494328-data.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<rss version="2.0">
- <channel>
- <title>Channel title</title>
- <description>Channel description</description>
- <link>Channel link</link>
- <item>
- <title>Episode 1</title>
- <enclosure url="http://www.example.com/podcasts/Episode%201" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 2</title>
- <enclosure url="http://www.example.com/podcasts/Episode%20%232" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 3</title>
- <enclosure url="http://www.example.com/podcasts/Episode%20%233/" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 4</title>
- <enclosure url="http://www.example.com/podcasts/Is%20This%20Episode%20%234%3F" length="0" type="audio/x-m4a" />
- </item>
- </channel>
-</rss>
diff --git a/browser/components/feeds/test/bug589543-data.xml b/browser/components/feeds/test/bug589543-data.xml
deleted file mode 100644
index 0e700b6d8..000000000
--- a/browser/components/feeds/test/bug589543-data.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id>
-
- <entry>
-
- <title>Item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/feeds/test/chrome/.eslintrc.js b/browser/components/feeds/test/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/browser/components/feeds/test/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/browser/components/feeds/test/chrome/chrome.ini b/browser/components/feeds/test/chrome/chrome.ini
deleted file mode 100644
index 7bad142ab..000000000
--- a/browser/components/feeds/test/chrome/chrome.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-support-files = sample_feed.atom
- !/browser/components/feeds/test/bug408328-data.xml
- !/browser/components/feeds/test/valid-feed.xml
- !/browser/components/feeds/test/valid-unsniffable-feed.xml
-
-[test_423060.xul]
-[test_bug368464.html]
-[test_bug408328.html]
-[test_maxSniffing.html]
diff --git a/browser/components/feeds/test/chrome/sample_feed.atom b/browser/components/feeds/test/chrome/sample_feed.atom
deleted file mode 100644
index add75efb4..000000000
--- a/browser/components/feeds/test/chrome/sample_feed.atom
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
-
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/feeds/test/chrome/test_423060.xul b/browser/components/feeds/test/chrome/test_423060.xul
deleted file mode 100644
index 465cf2dd2..000000000
--- a/browser/components/feeds/test/chrome/test_423060.xul
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Make sure feed preview works when a default reader is selected"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <script type="application/javascript">
- SimpleTest.waitForExplicitFinish();
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- var wccrID = "@mozilla.org/embeddor.implemented/web-content-handler-registrar;1";
- /* abort the test if web feed handlers are not available */
- if (!Cc[wccrID])
- SimpleTest.finish()
-
- /* Turn off the first run UI */
- var prefBranch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
- prefBranch.setBoolPref("browser.feeds.showFirstRunUI", false);
-
- /* register a handler for the feed type */
- const MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
- var handlerPage = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/demohandler.html?feedurl=%s";
- var wccr = Cc[wccrID].getService(Ci.nsIWebContentConverterService);
- wccr.registerContentHandler(MAYBE_FEED, handlerPage, "Demo handler", null);
- var demoHandler = wccr.getWebContentHandlerByURI(MAYBE_FEED, handlerPage);
- wccr.setAutoHandler(MAYBE_FEED, demoHandler);
-
- /* Don't show the preview page */
- prefBranch.setCharPref("browser.feeds.handler", "reader");
-
- function finishUp() {
- var theframe = document.getElementById('theframe');
- var previewURL = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/demohandler.html?feedurl=http%3A%2F%2Fmochi.test%3A8888%2Ftests%2Ftoolkit%2Fcomponents%2Fplaces%2Ftests%2Fchrome%2Fsample_feed.atom";
- is(theframe.contentDocument.URL, previewURL);
-
- /* remove our demoHandler */
- wccr.setAutoHandler(MAYBE_FEED, null);
- wccr.removeContentHandler(MAYBE_FEED, handlerPage);
- prefBranch.setCharPref("browser.feeds.handler", "ask");
- prefBranch.setBoolPref("browser.feeds.showFirstRunUI", true);
-
- SimpleTest.finish();
- }
- </script>
- <html:iframe src="http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/sample_feed.atom" height="400px"
- id="theframe" onload="finishUp();">
- </html:iframe>
-</window>
diff --git a/browser/components/feeds/test/chrome/test_bug368464.html b/browser/components/feeds/test/chrome/test_bug368464.html
deleted file mode 100644
index dd7486f66..000000000
--- a/browser/components/feeds/test/chrome/test_bug368464.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=368464
--->
-<head>
- <title>Test that RSS 0.90 isn't sniffed</title>
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=368464">Mozilla Bug 368464</a>
-<p id="display"><iframe id="testFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/bug368464-data.xml"></iframe></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 368464 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- ok($("testFrame").contentDocument.documentElement.id != "feedHandler",
- "RSS 0.90 shouldn't be sniffed as a feed");
-});
-addLoadEvent(SimpleTest.finish);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/components/feeds/test/chrome/test_bug408328.html b/browser/components/feeds/test/chrome/test_bug408328.html
deleted file mode 100644
index e4901320a..000000000
--- a/browser/components/feeds/test/chrome/test_bug408328.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=408328
--->
-<head>
- <title>Test feed preview safe-linkification</title>
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=408328">Mozilla Bug 408328</a>
-<p id="display"><iframe id="testFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/bug408328-data.xml"></iframe></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 408328 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- var links = $("testFrame").contentDocument.getElementById("feedContent").getElementsByTagName("a");
- is(links.length, 5, "wrong number of linked items in feed preview");
- for (var i = 0; i < links.length; i++) {
- if (links[i].href)
- is(links[i].href, "http://example.org/first", "bad linkified item");
- }
-});
-addLoadEvent(SimpleTest.finish);
-
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/browser/components/feeds/test/chrome/test_maxSniffing.html b/browser/components/feeds/test/chrome/test_maxSniffing.html
deleted file mode 100644
index 7a2044687..000000000
--- a/browser/components/feeds/test/chrome/test_maxSniffing.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=739040
--->
-<head>
- <title>Test that we only sniff 512 bytes</title>
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=739040">Mozilla Bug 739040</a>
-<p id="display">
- <iframe id="validTestFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/valid-feed.xml"></iframe>
- <iframe id="unsniffableTestFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/valid-unsniffable-feed.xml"></iframe>
-</p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 739040 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- is($("validTestFrame").contentDocument.documentElement.id, "feedHandler",
- "valid feed should be sniffed");
- isnot($("unsniffableTestFrame").contentDocument.documentElement.id, "feedHandler",
- "unsniffable feed should not be sniffed");
-});
-addLoadEvent(SimpleTest.finish);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/components/feeds/test/mochitest.ini b/browser/components/feeds/test/mochitest.ini
deleted file mode 100644
index fc1e6a1a9..000000000
--- a/browser/components/feeds/test/mochitest.ini
+++ /dev/null
@@ -1,14 +0,0 @@
-[DEFAULT]
-support-files =
- bug368464-data.xml
- bug408328-data.xml
- bug436801-data.xml
- bug494328-data.xml
- bug589543-data.xml
- valid-feed.xml
- valid-unsniffable-feed.xml
-
-[test_bug436801.html]
-[test_bug494328.html]
-[test_bug589543.html]
-[test_registerHandler.html]
diff --git a/browser/components/feeds/test/test_bug436801.html b/browser/components/feeds/test/test_bug436801.html
deleted file mode 100644
index 29fb5acf0..000000000
--- a/browser/components/feeds/test/test_bug436801.html
+++ /dev/null
@@ -1,118 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=436801
--->
-<head>
- <title>Test feed preview subscribe UI</title>
- <script type="text/javascript" src="/MochiKit/packed.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=436801">Mozilla Bug 436801</a>
-<p id="display"><iframe id="testFrame" src="bug436801-data.xml"></iframe></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function () {
- var doc = SpecialPowers.wrap($("testFrame")).contentDocument;
-
- checkNode(doc.getElementById("feedTitleText"), [
- "ELEMENT", "h1", { "xml:base": "http://www.example.com/foo/bar/" }, [
- ["TEXT", "Example of a "],
- ["ELEMENT", "em", [
- ["TEXT", "special"],
- ]],
- ["TEXT", " feed ("],
- ["ELEMENT", "img", { "src": "baz.png" }],
- ["TEXT", ")"],
- ]
- ]);
-
- checkNode(doc.getElementById("feedSubtitleText"), [
- "ELEMENT", "h2", { "xml:base": "http://www.example.com/foo/bar/" }, [
- ["TEXT", "With a "],
- ["ELEMENT", "em", [
- ["TEXT", "special"],
- ]],
- ["TEXT", " subtitle ("],
- ["ELEMENT", "img", { "src": "baz.png" }],
- ["TEXT", ")"],
- ]
- ]);
-
- checkNode(doc.querySelector(".entry").firstChild.firstChild.firstChild, [
- "ELEMENT", "span", { "xml:base": "http://www.example.com/foo/bar/" }, [
- ["TEXT", "Some "],
- ["ELEMENT", "abbr", { title: "Extensible Hyper-text Mark-up Language" }, [
- ["TEXT", "XHTML"],
- ]],
- ["TEXT", " examples ("],
- ["ELEMENT", "img", { "src": "baz.png" }],
- ["TEXT", ")"],
- ]
- ]);
-
- checkNode(doc.querySelectorAll(".entry")[1].firstChild.firstChild.firstChild, [
- "ELEMENT", "span", { "xml:base": "http://www.example.com/foo/bar/" }, [
- ["TEXT", "Some "],
- ["ELEMENT", "abbr", { title: "Hyper-text Mark-up Language" }, [
- ["TEXT", "HTML"],
- ]],
- ["TEXT", " examples ("],
- ["ELEMENT", "img", { "src": "baz.png" }],
- ["TEXT", ")"],
- ]
- ]);
-});
-
-addLoadEvent(SimpleTest.finish);
-
-function checkNode(node, schema) {
- var typeName = schema.shift() + "_NODE";
- var type = Node[typeName];
- is(node.nodeType, type, "Node should be expected type " + typeName);
- if (type == Node.TEXT_NODE) {
- var text = schema.shift();
- is(node.data, text, "Text should match");
- return;
- }
- // type == Node.ELEMENT_NODE
- var tag = schema.shift();
- is(node.localName, tag, "Element should have expected tag");
- while (schema.length) {
- let val = schema.shift();
- if (Array.isArray(val))
- var childSchema = val;
- else
- var attrSchema = val;
- }
- if (attrSchema) {
- var nsTable = {
- xml: "http://www.w3.org/XML/1998/namespace",
- };
- for (var name in attrSchema) {
- var [ns, nsName] = name.split(":");
- let val = nsName ? node.getAttributeNS(nsTable[ns], nsName) :
- node.getAttribute(name);
- is(val, attrSchema[name], "Attribute " + name + " should match");
- }
- }
- if (childSchema) {
- var numChildren = node.childNodes.length;
- is(childSchema.length, numChildren,
- "Element should have expected number of children");
- for (var i = 0; i < numChildren; i++)
- checkNode(node.childNodes[i], childSchema[i]);
- }
-}
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/components/feeds/test/test_bug494328.html b/browser/components/feeds/test/test_bug494328.html
deleted file mode 100644
index 054f62c1d..000000000
--- a/browser/components/feeds/test/test_bug494328.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=494328
--->
-<head>
- <title>Test for bug 494328</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=494328">Mozilla Bug 494328</a>
-<p id="display"><iframe id="testFrame" src="bug494328-data.xml"></iframe></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 494328 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- var links = SpecialPowers.wrap($("testFrame")).contentDocument.getElementById("feedContent").querySelectorAll("div.enclosure > a");
- is(links[0].textContent, "Episode 1", "filename decoded incorrectly");
- is(links[1].textContent, "Episode #2", "filename decoded incorrectly");
- is(links[2].textContent, "http://www.example.com/podcasts/Episode #3/", "filename decoded incorrectly");
- is(links[3].textContent, "Is This Episode #4?", "filename decoded incorrectly");
-});
-addLoadEvent(SimpleTest.finish);
-
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/browser/components/feeds/test/test_bug589543.html b/browser/components/feeds/test/test_bug589543.html
deleted file mode 100644
index cee2a9661..000000000
--- a/browser/components/feeds/test/test_bug589543.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=589543
--->
-<head>
- <title>Test feed preview subscribe UI</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=589543">Mozilla Bug 589543</a>
-<p id="display"><iframe id="testFrame" src="bug589543-data.xml"></iframe></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 589543 **/
-SimpleTest.waitForExplicitFinish();
-
-addLoadEvent(function() {
- var doc = SpecialPowers.wrap($("testFrame")).contentDocument;
- var popup = doc.getElementById("handlersMenuList");
- isnot(popup, null, "Feed preview should have a handlers popup");
-});
-addLoadEvent(SimpleTest.finish);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/components/feeds/test/test_registerHandler.html b/browser/components/feeds/test/test_registerHandler.html
deleted file mode 100644
index 34e61d034..000000000
--- a/browser/components/feeds/test/test_registerHandler.html
+++ /dev/null
@@ -1,85 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=402788
--->
-<head>
- <title>Test for Bug 402788</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=402788">Mozilla Bug 402788</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 402788 **/
-
- // return false if an exception has been catched, true otherwise
- function testRegisterHandler(aIsProtocol, aTxt, aUri, aTitle)
- {
- try {
- if (aIsProtocol)
- navigator.registerProtocolHandler(aTxt, aUri, aTitle);
- else
- navigator.registerContentHandler(aTxt, aUri, aTitle);
- }
- catch (e) {
- return false;
- }
-
- return true;
- }
-
- ok(navigator.registerProtocolHandler, "navigator.registerProtocolHandler should be defined");
- ok(navigator.registerContentHandler, "navigator.registerContentHandler should be defined");
-
- // testing a generic case
- is(testRegisterHandler(true, "foo", "http://mochi.test:8888/%s", "Foo handler"), true, "registering a foo protocol handler should work");
- is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering a foo content handler should work");
-
- // testing with wrong uris
- is(testRegisterHandler(true, "foo", "http://mochi.test:8888/", "Foo handler"), false, "a protocol handler uri should contain %s");
- is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/", "Foo handler"), false, "a content handler uri should contain %s");
-
- // the spec explicitly allows relative urls to be passed
- is(testRegisterHandler(true, "foo", "foo/%s", "Foo handler"), true, "a protocol handler uri should be valid");
- is(testRegisterHandler(false, "application/rss+xml", "foo/%s", "Foo handler"), true, "a content handler uri should be valid");
-
- // we should only accept to register when the handler has the same host as the current page (bug 402287)
- is(testRegisterHandler(true, "foo", "http://remotehost:8888/%s", "Foo handler"), false, "registering a foo protocol handler with a different host should not work");
- is(testRegisterHandler(false, "application/rss+xml", "http://remotehost:8888/%s", "Foo handler"), false, "registering a foo content handler with a different host should not work");
-
- // restriction to http(s) for the uri of the handler (bug 401343)
- // https should work (http already tested in the generic case)
- is(testRegisterHandler(true, "foo", "https://mochi.test:8888/%s", "Foo handler"), true, "registering a foo protocol handler with https scheme should work");
- is(testRegisterHandler(false, "application/rss+xml", "https://mochi.test:8888/%s", "Foo handler"), true, "registering a foo content handler with https scheme should work");
- // ftp should not work
- is(testRegisterHandler(true, "foo", "ftp://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with ftp scheme should not work");
- is(testRegisterHandler(false, "application/rss+xml", "ftp://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with ftp scheme should not work");
- // chrome should not work
- is(testRegisterHandler(true, "foo", "chrome://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with chrome scheme should not work");
- is(testRegisterHandler(false, "application/rss+xml", "chrome://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with chrome scheme should not work");
- // foo should not work
- is(testRegisterHandler(true, "foo", "foo://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with foo scheme should not work");
- is(testRegisterHandler(false, "application/rss+xml", "foo://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with foo scheme should not work");
-
- // for security reasons, protocol handlers should never be registered for some schemes (chrome, vbscript, ...) (bug 402788)
- is(testRegisterHandler(true, "chrome", "http://mochi.test:8888/%s", "chrome handler"), false, "registering a chrome protocol handler should not work");
- is(testRegisterHandler(true, "vbscript", "http://mochi.test:8888/%s", "vbscript handler"), false, "registering a vbscript protocol handler should not work");
- is(testRegisterHandler(true, "javascript", "http://mochi.test:8888/%s", "javascript handler"), false, "registering a javascript protocol handler should not work");
- is(testRegisterHandler(true, "moz-icon", "http://mochi.test:8888/%s", "moz-icon handler"), false, "registering a moz-icon protocol handler should not work");
-
- // for security reasons, content handlers should never be registered for some types (html, ...)
- is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering rss content handlers should work");
- is(testRegisterHandler(false, "application/atom+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering atom content handlers should work");
- todo_is(testRegisterHandler(false, "text/html", "http://mochi.test:8888/%s", "Foo handler"), false, "registering html content handlers should not work"); // bug 403798
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/browser/components/feeds/test/unit/.eslintrc.js b/browser/components/feeds/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/feeds/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/feeds/test/unit/head_feeds.js b/browser/components/feeds/test/unit/head_feeds.js
deleted file mode 100644
index 3b1135ef7..000000000
--- a/browser/components/feeds/test/unit/head_feeds.js
+++ /dev/null
@@ -1,5 +0,0 @@
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
diff --git a/browser/components/feeds/test/unit/test_355473.js b/browser/components/feeds/test/unit/test_355473.js
deleted file mode 100644
index 8a20d1389..000000000
--- a/browser/components/feeds/test/unit/test_355473.js
+++ /dev/null
@@ -1,43 +0,0 @@
-var Cu = Components.utils;
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-function run_test() {
- var feedFeedURI = ios.newURI("feed://example.com/feed.xml", null, null);
- var httpFeedURI = ios.newURI("feed:http://example.com/feed.xml", null, null);
- var httpURI = ios.newURI("http://example.com/feed.xml", null, null);
-
- var httpsFeedURI =
- ios.newURI("feed:https://example.com/feed.xml", null, null);
- var httpsURI = ios.newURI("https://example.com/feed.xml", null, null);
-
- var feedChannel = NetUtil.newChannel({
- uri: feedFeedURI,
- loadUsingSystemPrincipal: true
- });
-
- var httpChannel = NetUtil.newChannel({
- uri: httpFeedURI,
- loadUsingSystemPrincipal: true
- });
-
- var httpsChannel = NetUtil.newChannel({
- uri: httpsFeedURI,
- loadUsingSystemPrincipal: true
- });
-
- // not setting .originalURI to the original URI is naughty
- do_check_true(feedFeedURI.equals(feedChannel.originalURI));
- do_check_true(httpFeedURI.equals(httpChannel.originalURI));
- do_check_true(httpsFeedURI.equals(httpsChannel.originalURI));
-
- // actually using the horrible mess that's a feed: URI is suicidal
- do_check_true(httpURI.equals(feedChannel.URI));
- do_check_true(httpURI.equals(httpChannel.URI));
- do_check_true(httpsURI.equals(httpsChannel.URI));
-
- // check that we throw creating feed: URIs from file and ftp
- Assert.throws(function() { ios.newURI("feed:ftp://example.com/feed.xml", null, null); },
- "Should throw an exception when trying to create a feed: URI with an ftp: inner");
- Assert.throws(function() { ios.newURI("feed:file:///var/feed.xml", null, null); },
- "Should throw an exception when trying to create a feed: URI with a file: inner");
-}
diff --git a/browser/components/feeds/test/unit/test_758990.js b/browser/components/feeds/test/unit/test_758990.js
deleted file mode 100644
index e6f88baf2..000000000
--- a/browser/components/feeds/test/unit/test_758990.js
+++ /dev/null
@@ -1,42 +0,0 @@
-function run_test() {
- var success = false;
- try {
- ios.newURI("feed:javascript:alert('hi');", null, null);
- }
- catch (e) {
- success = e.result == Cr.NS_ERROR_MALFORMED_URI;
- }
- if (!success)
- do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:javascript: URI");
-
- success = false;
- try {
- ios.newURI("feed:data:text/html,hi", null, null);
- }
- catch (e) {
- success = e.result == Cr.NS_ERROR_MALFORMED_URI;
- }
- if (!success)
- do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:data: URI");
-
- success = false;
- try {
- ios.newURI("pcast:javascript:alert('hi');", null, null);
- }
- catch (e) {
- success = e.result == Cr.NS_ERROR_MALFORMED_URI;
- }
- if (!success)
- do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:javascript: URI");
-
- success = false;
- try {
- ios.newURI("pcast:data:text/html,hi", null, null);
- }
- catch (e) {
- success = e.result == Cr.NS_ERROR_MALFORMED_URI;
- }
- if (!success)
- do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:data: URI");
-
-}
diff --git a/browser/components/feeds/test/unit/xpcshell.ini b/browser/components/feeds/test/unit/xpcshell.ini
deleted file mode 100644
index 9faf57396..000000000
--- a/browser/components/feeds/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head = head_feeds.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_355473.js]
-[test_758990.js]
diff --git a/browser/components/feeds/test/valid-feed.xml b/browser/components/feeds/test/valid-feed.xml
deleted file mode 100644
index 0e700b6d8..000000000
--- a/browser/components/feeds/test/valid-feed.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id>
-
- <entry>
-
- <title>Item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/feeds/test/valid-unsniffable-feed.xml b/browser/components/feeds/test/valid-unsniffable-feed.xml
deleted file mode 100644
index e75315739..000000000
--- a/browser/components/feeds/test/valid-unsniffable-feed.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 512 bytes!
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- -->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id>
-
- <entry>
-
- <title>Item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id>
- <updated>2010-08-22T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/browser/components/migration/tests/browser/.eslintrc.js b/browser/components/migration/tests/browser/.eslintrc.js
deleted file mode 100644
index 3ea6eeb8c..000000000
--- a/browser/components/migration/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,9 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js",
- "../../../../../testing/mochitest/mochitest.eslintrc.js",
- ]
-};
-
diff --git a/browser/components/migration/tests/browser/browser.ini b/browser/components/migration/tests/browser/browser.ini
deleted file mode 100644
index 94edfe7aa..000000000
--- a/browser/components/migration/tests/browser/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[browser_undo_notification.js]
-[browser_undo_notification_wording.js]
-[browser_undo_notification_multiple_dismissal.js]
diff --git a/browser/components/migration/tests/browser/browser_undo_notification.js b/browser/components/migration/tests/browser/browser_undo_notification.js
deleted file mode 100644
index 6c97922e0..000000000
--- a/browser/components/migration/tests/browser/browser_undo_notification.js
+++ /dev/null
@@ -1,67 +0,0 @@
-"use strict";
-
-let scope = {};
-Cu.import("resource:///modules/AutoMigrate.jsm", scope);
-let oldCanUndo = scope.AutoMigrate.canUndo;
-let oldUndo = scope.AutoMigrate.undo;
-registerCleanupFunction(function() {
- scope.AutoMigrate.canUndo = oldCanUndo;
- scope.AutoMigrate.undo = oldUndo;
-});
-
-const kExpectedNotificationId = "automigration-undo";
-
-add_task(function* autoMigrationUndoNotificationShows() {
- let getNotification = browser =>
- gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId);
-
- scope.AutoMigrate.canUndo = () => true;
- let undoCalled;
- scope.AutoMigrate.undo = () => { undoCalled = true };
- for (let url of ["about:newtab", "about:home"]) {
- undoCalled = false;
- // Can't use pushPrefEnv because of bug 1323779
- Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false);
- let browser = tab.linkedBrowser;
- if (!getNotification(browser)) {
- info(`Notification for ${url} not immediately present, waiting for it.`);
- yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId);
- }
-
- ok(true, `Got notification for ${url}`);
- let notification = getNotification(browser);
- let notificationBox = notification.parentNode;
- notification.querySelector("button.notification-button-default").click();
- ok(!undoCalled, "Undo should not be called when clicking the default button");
- is(notification, notificationBox._closedNotification, "Notification should be closing");
- yield BrowserTestUtils.removeTab(tab);
-
- undoCalled = false;
- Services.prefs.setCharPref("browser.migrate.automigrate.browser", "chrome");
- tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false);
- browser = tab.linkedBrowser;
- if (!getNotification(browser)) {
- info(`Notification for ${url} not immediately present, waiting for it.`);
- yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId);
- }
-
- ok(true, `Got notification for ${url}`);
- notification = getNotification(browser);
- notificationBox = notification.parentNode;
- // Set up the survey:
- yield SpecialPowers.pushPrefEnv({set: [
- ["browser.migrate.automigrate.undo-survey", "https://example.com/?browser=%IMPORTEDBROWSER%"],
- ["browser.migrate.automigrate.undo-survey-locales", "en-US"],
- ]});
- let tabOpenedPromise = BrowserTestUtils.waitForNewTab(gBrowser, "https://example.com/?browser=Google%20Chrome");
- notification.querySelector("button:not(.notification-button-default)").click();
- ok(undoCalled, "Undo should be called when clicking the non-default (Don't Keep) button");
- is(notification, notificationBox._closedNotification, "Notification should be closing");
- let surveyTab = yield tabOpenedPromise;
- ok(surveyTab, "Should have opened a tab with a survey");
- yield BrowserTestUtils.removeTab(surveyTab);
- yield BrowserTestUtils.removeTab(tab);
- }
-});
-
diff --git a/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js b/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js
deleted file mode 100644
index 90b5d0d08..000000000
--- a/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js
+++ /dev/null
@@ -1,122 +0,0 @@
-"use strict";
-
-
-const kExpectedNotificationId = "automigration-undo";
-
-/**
- * Pretend we can undo something, trigger a notification, pick the undo option,
- * and verify that the notifications are all dismissed immediately.
- */
-add_task(function* checkNotificationsDismissed() {
- yield SpecialPowers.pushPrefEnv({set: [
- ["browser.migrate.automigrate.enabled", true],
- ["browser.migrate.automigrate.ui.enabled", true],
- ]});
- let getNotification = browser =>
- gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId);
-
- Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser");
-
- let {guid, lastModified} = yield PlacesUtils.bookmarks.insert(
- {title: "Some imported bookmark", parentGuid: PlacesUtils.bookmarks.toolbarGuid, url: "http://www.example.com"}
- );
-
- let testUndoData = {
- visits: [],
- bookmarks: [{guid, lastModified: lastModified.getTime()}],
- logins: [],
- };
- let path = OS.Path.join(OS.Constants.Path.profileDir, "initialMigrationMetadata.jsonlz4");
- registerCleanupFunction(() => {
- return OS.File.remove(path, {ignoreAbsent: true});
- });
- yield OS.File.writeAtomic(path, JSON.stringify(testUndoData), {
- encoding: "utf-8",
- compression: "lz4",
- tmpPath: path + ".tmp",
- });
-
- let firstTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home", false);
- if (!getNotification(firstTab.linkedBrowser)) {
- info(`Notification not immediately present on first tab, waiting for it.`);
- yield BrowserTestUtils.waitForNotificationBar(gBrowser, firstTab.linkedBrowser, kExpectedNotificationId);
- }
- let secondTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home", false);
- if (!getNotification(secondTab.linkedBrowser)) {
- info(`Notification not immediately present on second tab, waiting for it.`);
- yield BrowserTestUtils.waitForNotificationBar(gBrowser, secondTab.linkedBrowser, kExpectedNotificationId);
- }
-
- // Create a listener for the removal in the first tab, and a listener for bookmarks removal,
- // then click 'Don't keep' in the second tab, and verify that the notification is removed
- // before we start removing bookmarks.
- let haveRemovedBookmark = false;
- let bmObserver;
- let bookmarkRemovedPromise = new Promise(resolve => {
- bmObserver = {
- onItemRemoved(itemId, parentId, index, itemType, uri, removedGuid) {
- if (guid == removedGuid) {
- haveRemovedBookmark = true;
- resolve();
- }
- },
- };
- PlacesUtils.bookmarks.addObserver(bmObserver, false);
- registerCleanupFunction(() => PlacesUtils.bookmarks.removeObserver(bmObserver));
- });
-
- let firstTabNotificationRemovedPromise = new Promise(resolve => {
- let notification = getNotification(firstTab.linkedBrowser);
- // Save this reference because notification.parentNode will be null once it's removed.
- let notificationBox = notification.parentNode;
- let mut = new MutationObserver(mutations => {
- // Yucky, but we have to detect either the removal via animation (with marginTop)
- // or when the element is removed. We can't just detect the element being removed
- // because this happens asynchronously (after the animation) and so it'd race
- // with the rest of the undo happening.
- for (let mutation of mutations) {
- if (mutation.target == notification && mutation.attributeName == "style" &&
- parseInt(notification.style.marginTop, 10) < 0) {
- ok(!haveRemovedBookmark, "Should not have removed bookmark yet");
- mut.disconnect();
- resolve();
- return;
- }
- if (mutation.target == notificationBox && mutation.removedNodes.length &&
- mutation.removedNodes[0] == notification) {
- ok(!haveRemovedBookmark, "Should not have removed bookmark yet");
- mut.disconnect();
- resolve();
- return;
- }
- }
- });
- mut.observe(notification.parentNode, {childList: true});
- mut.observe(notification, {attributes: true});
- });
-
- let prefResetPromise = new Promise(resolve => {
- const kObservedPref = "browser.migrate.automigrate.browser";
- let obs = () => {
- Services.prefs.removeObserver(kObservedPref, obs);
- ok(!Services.prefs.prefHasUserValue(kObservedPref),
- "Pref should have been reset");
- resolve();
- };
- Services.prefs.addObserver(kObservedPref, obs, false);
- });
-
- // Click "Don't keep" button:
- let notificationToActivate = getNotification(secondTab.linkedBrowser);
- notificationToActivate.querySelector("button:not(.notification-button-default)").click();
- info("Waiting for notification to be removed in first (background) tab");
- yield firstTabNotificationRemovedPromise;
- info("Waiting for bookmark to be removed");
- yield bookmarkRemovedPromise;
- info("Waiting for prefs to be reset");
- yield prefResetPromise;
-
- info("Removing spare tabs");
- yield BrowserTestUtils.removeTab(firstTab);
- yield BrowserTestUtils.removeTab(secondTab);
-});
diff --git a/browser/components/migration/tests/browser/browser_undo_notification_wording.js b/browser/components/migration/tests/browser/browser_undo_notification_wording.js
deleted file mode 100644
index f0a9ceec9..000000000
--- a/browser/components/migration/tests/browser/browser_undo_notification_wording.js
+++ /dev/null
@@ -1,67 +0,0 @@
-"use strict";
-
-let scope = {};
-Cu.import("resource:///modules/AutoMigrate.jsm", scope);
-let oldCanUndo = scope.AutoMigrate.canUndo;
-registerCleanupFunction(function() {
- scope.AutoMigrate.canUndo = oldCanUndo;
-});
-
-const kExpectedNotificationId = "automigration-undo";
-
-add_task(function* autoMigrationUndoNotificationShows() {
- let getNotification = browser =>
- gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId);
- let localizedVersionOf = str => {
- if (str == "logins") {
- return "passwords";
- }
- if (str == "visits") {
- return "history";
- }
- return str;
- };
-
- scope.AutoMigrate.canUndo = () => true;
- let url = "about:newtab";
- Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser");
- const kSubsets = [
- ["bookmarks", "logins", "visits"],
- ["bookmarks", "logins"],
- ["bookmarks", "visits"],
- ["logins", "visits"],
- ["bookmarks"],
- ["logins"],
- ["visits"],
- ];
- const kAllItems = ["bookmarks", "logins", "visits"];
- for (let subset of kSubsets) {
- let state = new Map(subset.map(item => [item, [{}]]));
- scope.AutoMigrate._setImportedItemPrefFromState(state);
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false);
- let browser = tab.linkedBrowser;
-
- if (!getNotification(browser)) {
- info(`Notification for ${url} not immediately present, waiting for it.`);
- yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId);
- }
-
- ok(true, `Got notification for ${url}`);
- let notification = getNotification(browser);
- let notificationText = document.getAnonymousElementByAttribute(notification, "class", "messageText");
- notificationText = notificationText.textContent;
- for (let potentiallyImported of kAllItems) {
- let localizedImportItem = localizedVersionOf(potentiallyImported);
- if (subset.includes(potentiallyImported)) {
- ok(notificationText.includes(localizedImportItem),
- "Expected notification to contain " + localizedImportItem);
- } else {
- ok(!notificationText.includes(localizedImportItem),
- "Expected notification not to contain " + localizedImportItem);
- }
- }
-
- yield BrowserTestUtils.removeTab(tab);
- }
-});
-
diff --git a/browser/components/migration/tests/marionette/manifest.ini b/browser/components/migration/tests/marionette/manifest.ini
deleted file mode 100644
index 3f404e724..000000000
--- a/browser/components/migration/tests/marionette/manifest.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'browser'
-
-[test_refresh_firefox.py]
-
diff --git a/browser/components/migration/tests/marionette/test_refresh_firefox.py b/browser/components/migration/tests/marionette/test_refresh_firefox.py
deleted file mode 100644
index b348a3dcd..000000000
--- a/browser/components/migration/tests/marionette/test_refresh_firefox.py
+++ /dev/null
@@ -1,416 +0,0 @@
-import os
-import shutil
-
-from marionette_harness import MarionetteTestCase
-
-
-class TestFirefoxRefresh(MarionetteTestCase):
- _username = "marionette-test-login"
- _password = "marionette-test-password"
- _bookmarkURL = "about:mozilla"
- _bookmarkText = "Some bookmark from Marionette"
-
- _cookieHost = "firefox-refresh.marionette-test.mozilla.org"
- _cookiePath = "some/cookie/path"
- _cookieName = "somecookie"
- _cookieValue = "some cookie value"
-
- _historyURL = "http://firefox-refresh.marionette-test.mozilla.org/"
- _historyTitle = "Test visit for Firefox Reset"
-
- _formHistoryFieldName = "some-very-unique-marionette-only-firefox-reset-field"
- _formHistoryValue = "special-pumpkin-value"
-
- _expectedURLs = ["about:robots", "about:mozilla"]
-
- def savePassword(self):
- self.runCode("""
- let myLogin = new global.LoginInfo(
- "test.marionette.mozilla.com",
- "http://test.marionette.mozilla.com/some/form/",
- null,
- arguments[0],
- arguments[1],
- "username",
- "password"
- );
- Services.logins.addLogin(myLogin)
- """, script_args=[self._username, self._password])
-
- def createBookmark(self):
- self.marionette.execute_script("""
- let url = arguments[0];
- let title = arguments[1];
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarks.bookmarksMenuFolder,
- makeURI(url), 0, title);
- """, script_args=[self._bookmarkURL, self._bookmarkText])
-
- def createHistory(self):
- error = self.runAsyncCode("""
- // Copied from PlacesTestUtils, which isn't available in Marionette tests.
- let didReturn;
- PlacesUtils.asyncHistory.updatePlaces(
- [{title: arguments[1], uri: makeURI(arguments[0]), visits: [{
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- visitDate: (Date.now() - 5000) * 1000,
- referrerURI: makeURI("about:mozilla"),
- }]
- }],
- {
- handleError(resultCode, place) {
- didReturn = true;
- marionetteScriptFinished("Unexpected error in adding visit: " + resultCode);
- },
- handleResult() {},
- handleCompletion() {
- if (!didReturn) {
- marionetteScriptFinished(false);
- }
- },
- }
- );
- """, script_args=[self._historyURL, self._historyTitle])
- if error:
- print error
-
- def createFormHistory(self):
- error = self.runAsyncCode("""
- let updateDefinition = {
- op: "add",
- fieldname: arguments[0],
- value: arguments[1],
- firstUsed: (Date.now() - 5000) * 1000,
- };
- let finished = false;
- global.FormHistory.update(updateDefinition, {
- handleError(error) {
- finished = true;
- marionetteScriptFinished(error);
- },
- handleCompletion() {
- if (!finished) {
- marionetteScriptFinished(false);
- }
- }
- });
- """, script_args=[self._formHistoryFieldName, self._formHistoryValue])
- if error:
- print error
-
- def createCookie(self):
- self.runCode("""
- // Expire in 15 minutes:
- let expireTime = Math.floor(Date.now() / 1000) + 15 * 60;
- Services.cookies.add(arguments[0], arguments[1], arguments[2], arguments[3],
- true, false, false, expireTime);
- """, script_args=[self._cookieHost, self._cookiePath, self._cookieName, self._cookieValue])
-
- def createSession(self):
- self.runAsyncCode("""
- const COMPLETE_STATE = Ci.nsIWebProgressListener.STATE_STOP +
- Ci.nsIWebProgressListener.STATE_IS_NETWORK;
- let {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
- let expectedURLs = Array.from(arguments[0])
- gBrowser.addTabsProgressListener({
- onStateChange(browser, webprogress, request, flags, status) {
- try {
- request && request.QueryInterface(Ci.nsIChannel);
- } catch (ex) {}
- let uriLoaded = request.originalURI && request.originalURI.spec;
- if ((flags & COMPLETE_STATE == COMPLETE_STATE) && uriLoaded &&
- expectedURLs.includes(uriLoaded)) {
- TabStateFlusher.flush(browser).then(function() {
- expectedURLs.splice(expectedURLs.indexOf(uriLoaded), 1);
- if (!expectedURLs.length) {
- gBrowser.removeTabsProgressListener(this);
- marionetteScriptFinished();
- }
- });
- }
- }
- });
- for (let url of expectedURLs) {
- gBrowser.addTab(url);
- }
- """, script_args=[self._expectedURLs])
-
- def checkPassword(self):
- loginInfo = self.marionette.execute_script("""
- let ary = Services.logins.findLogins({},
- "test.marionette.mozilla.com",
- "http://test.marionette.mozilla.com/some/form/",
- null, {});
- return ary.length ? ary : {username: "null", password: "null"};
- """)
- self.assertEqual(len(loginInfo), 1)
- self.assertEqual(loginInfo[0]['username'], self._username)
- self.assertEqual(loginInfo[0]['password'], self._password)
-
- loginCount = self.marionette.execute_script("""
- return Services.logins.getAllLogins().length;
- """)
- self.assertEqual(loginCount, 1, "No other logins are present")
-
- def checkBookmark(self):
- titleInBookmarks = self.marionette.execute_script("""
- let url = arguments[0];
- let bookmarkIds = PlacesUtils.bookmarks.getBookmarkIdsForURI(makeURI(url), {}, {});
- return bookmarkIds.length == 1 ? PlacesUtils.bookmarks.getItemTitle(bookmarkIds[0]) : "";
- """, script_args=[self._bookmarkURL])
- self.assertEqual(titleInBookmarks, self._bookmarkText)
-
- def checkHistory(self):
- historyResults = self.runAsyncCode("""
- let placeInfos = [];
- PlacesUtils.asyncHistory.getPlacesInfo(makeURI(arguments[0]), {
- handleError(resultCode, place) {
- placeInfos = null;
- marionetteScriptFinished("Unexpected error in fetching visit: " + resultCode);
- },
- handleResult(placeInfo) {
- placeInfos.push(placeInfo);
- },
- handleCompletion() {
- if (placeInfos) {
- if (!placeInfos.length) {
- marionetteScriptFinished("No visits found");
- } else {
- marionetteScriptFinished(placeInfos);
- }
- }
- },
- });
- """, script_args=[self._historyURL])
- if type(historyResults) == str:
- self.fail(historyResults)
- return
-
- historyCount = len(historyResults)
- self.assertEqual(historyCount, 1, "Should have exactly 1 entry for URI, got %d" % historyCount)
- if historyCount == 1:
- self.assertEqual(historyResults[0]['title'], self._historyTitle)
-
- def checkFormHistory(self):
- formFieldResults = self.runAsyncCode("""
- let results = [];
- global.FormHistory.search(["value"], {fieldname: arguments[0]}, {
- handleError(error) {
- results = error;
- },
- handleResult(result) {
- results.push(result);
- },
- handleCompletion() {
- marionetteScriptFinished(results);
- },
- });
- """, script_args=[self._formHistoryFieldName])
- if type(formFieldResults) == str:
- self.fail(formFieldResults)
- return
-
- formFieldResultCount = len(formFieldResults)
- self.assertEqual(formFieldResultCount, 1, "Should have exactly 1 entry for this field, got %d" % formFieldResultCount)
- if formFieldResultCount == 1:
- self.assertEqual(formFieldResults[0]['value'], self._formHistoryValue)
-
- formHistoryCount = self.runAsyncCode("""
- let count;
- let callbacks = {
- handleResult: rv => count = rv,
- handleCompletion() {
- marionetteScriptFinished(count);
- },
- };
- global.FormHistory.count({}, callbacks);
- """)
- self.assertEqual(formHistoryCount, 1, "There should be only 1 entry in the form history")
-
- def checkCookie(self):
- cookieInfo = self.runCode("""
- try {
- let cookieEnum = Services.cookies.getCookiesFromHost(arguments[0]);
- let cookie = null;
- while (cookieEnum.hasMoreElements()) {
- let hostCookie = cookieEnum.getNext();
- hostCookie.QueryInterface(Ci.nsICookie2);
- // getCookiesFromHost returns any cookie from the BASE host.
- if (hostCookie.rawHost != arguments[0])
- continue;
- if (cookie != null) {
- return "more than 1 cookie! That shouldn't happen!";
- }
- cookie = hostCookie;
- }
- return {path: cookie.path, name: cookie.name, value: cookie.value};
- } catch (ex) {
- return "got exception trying to fetch cookie: " + ex;
- }
- """, script_args=[self._cookieHost])
- if not isinstance(cookieInfo, dict):
- self.fail(cookieInfo)
- return
- self.assertEqual(cookieInfo['path'], self._cookiePath)
- self.assertEqual(cookieInfo['value'], self._cookieValue)
- self.assertEqual(cookieInfo['name'], self._cookieName)
-
- def checkSession(self):
- tabURIs = self.runCode("""
- return [... gBrowser.browsers].map(b => b.currentURI && b.currentURI.spec)
- """)
- self.assertSequenceEqual(tabURIs, ["about:welcomeback"])
-
- tabURIs = self.runAsyncCode("""
- let mm = gBrowser.selectedBrowser.messageManager;
- let fs = function() {
- content.document.getElementById("errorTryAgain").click();
- };
- let {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
- window.addEventListener("SSWindowStateReady", function testSSPostReset() {
- window.removeEventListener("SSWindowStateReady", testSSPostReset, false);
- Promise.all(gBrowser.browsers.map(b => TabStateFlusher.flush(b))).then(function() {
- marionetteScriptFinished([... gBrowser.browsers].map(b => b.currentURI && b.currentURI.spec));
- });
- }, false);
- mm.loadFrameScript("data:application/javascript,(" + fs.toString() + ")()", true);
- """)
- self.assertSequenceEqual(tabURIs, ["about:blank"] + self._expectedURLs)
- pass
-
- def checkProfile(self, hasMigrated=False):
- self.checkPassword()
- self.checkBookmark()
- self.checkHistory()
- self.checkFormHistory()
- self.checkCookie()
- if hasMigrated:
- self.checkSession()
-
- def createProfileData(self):
- self.savePassword()
- self.createBookmark()
- self.createHistory()
- self.createFormHistory()
- self.createCookie()
- self.createSession()
-
- def setUpScriptData(self):
- self.marionette.set_context(self.marionette.CONTEXT_CHROME)
- self.marionette.execute_script("""
- global.LoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", "nsILoginInfo", "init");
- global.profSvc = Cc["@mozilla.org/toolkit/profile-service;1"].getService(Ci.nsIToolkitProfileService);
- global.Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
- global.FormHistory = Cu.import("resource://gre/modules/FormHistory.jsm", {}).FormHistory;
- """, new_sandbox=False, sandbox='system')
-
- def runCode(self, script, *args, **kwargs):
- return self.marionette.execute_script(script, new_sandbox=False, sandbox='system', *args, **kwargs)
-
- def runAsyncCode(self, script, *args, **kwargs):
- return self.marionette.execute_async_script(script, new_sandbox=False, sandbox='system', *args, **kwargs)
-
- def setUp(self):
- MarionetteTestCase.setUp(self)
- self.setUpScriptData()
-
- self.reset_profile_path = None
- self.desktop_backup_path = None
-
- self.createProfileData()
-
- def tearDown(self):
- # Force yet another restart with a clean profile to disconnect from the
- # profile and environment changes we've made, to leave a more or less
- # blank slate for the next person.
- self.marionette.restart(clean=True, in_app=False)
- self.setUpScriptData()
-
- # Super
- MarionetteTestCase.tearDown(self)
-
- # Some helpers to deal with removing a load of files
- import errno, stat
- def handleRemoveReadonly(func, path, exc):
- excvalue = exc[1]
- if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
- os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
- func(path)
- else:
- raise
-
- if self.desktop_backup_path:
- shutil.rmtree(self.desktop_backup_path, ignore_errors=False, onerror=handleRemoveReadonly)
-
- if self.reset_profile_path:
- # Remove ourselves from profiles.ini
- profileLeafName = os.path.basename(os.path.normpath(self.reset_profile_path))
- self.runCode("""
- let [salt, name] = arguments[0].split(".");
- let profile = global.profSvc.getProfileByName(name);
- profile.remove(false)
- global.profSvc.flush();
- """, script_args=[profileLeafName])
- # And delete all the files.
- shutil.rmtree(self.reset_profile_path, ignore_errors=False, onerror=handleRemoveReadonly)
-
- def doReset(self):
- self.runCode("""
- // Ensure the current (temporary) profile is in profiles.ini:
- let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let profileName = "marionette-test-profile-" + Date.now();
- let myProfile = global.profSvc.createProfile(profD, profileName);
- global.profSvc.flush()
-
- // Now add the reset parameters:
- let env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
- let allMarionettePrefs = Services.prefs.getChildList("marionette.");
- let prefObj = {};
- for (let pref of allMarionettePrefs) {
- let prefSuffix = pref.substr("marionette.".length);
- let prefVal = global.Preferences.get(pref);
- prefObj[prefSuffix] = prefVal;
- }
- let marionetteInfo = JSON.stringify(prefObj);
- env.set("MOZ_MARIONETTE_PREF_STATE_ACROSS_RESTARTS", marionetteInfo);
- env.set("MOZ_RESET_PROFILE_RESTART", "1");
- env.set("XRE_PROFILE_PATH", arguments[0]);
- env.set("XRE_PROFILE_NAME", profileName);
- """, script_args=[self.marionette.instance.profile.profile])
-
- profileLeafName = os.path.basename(os.path.normpath(self.marionette.instance.profile.profile))
-
- # Now restart the browser to get it reset:
- self.marionette.restart(clean=False, in_app=True)
- self.setUpScriptData()
-
- # Determine the new profile path (we'll need to remove it when we're done)
- self.reset_profile_path = self.runCode("""
- let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
- return profD.path;
- """)
-
- # Determine the backup path
- self.desktop_backup_path = self.runCode("""
- let container;
- try {
- container = Services.dirsvc.get("Desk", Ci.nsIFile);
- } catch (ex) {
- container = Services.dirsvc.get("Home", Ci.nsIFile);
- }
- let bundle = Services.strings.createBundle("chrome://mozapps/locale/profile/profileSelection.properties");
- let dirName = bundle.formatStringFromName("resetBackupDirectory", [Services.appinfo.name], 1);
- container.append(dirName);
- container.append(arguments[0]);
- return container.path;
- """, script_args = [profileLeafName])
-
- self.assertTrue(os.path.isdir(self.reset_profile_path), "Reset profile path should be present")
- self.assertTrue(os.path.isdir(self.desktop_backup_path), "Backup profile path should be present")
-
- def testReset(self):
- self.checkProfile()
-
- self.doReset()
-
- # Now check that we're doing OK...
- self.checkProfile(hasMigrated=True)
diff --git a/browser/components/migration/tests/unit/.eslintrc.js b/browser/components/migration/tests/unit/.eslintrc.js
deleted file mode 100644
index ba65517f9..000000000
--- a/browser/components/migration/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data b/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data
deleted file mode 100644
index 914149c71..000000000
--- a/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data
+++ /dev/null
Binary files differ
diff --git a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies b/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies
deleted file mode 100644
index 83d855cb3..000000000
--- a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies
+++ /dev/null
Binary files differ
diff --git a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State b/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State
deleted file mode 100644
index 01b99455e..000000000
--- a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "profile" : {
- "info_cache" : {
- "Default" : {
- "active_time" : 1430950755.65137,
- "is_using_default_name" : true,
- "is_ephemeral" : false,
- "is_omitted_from_profile_list" : false,
- "user_name" : "",
- "background_apps" : false,
- "is_using_default_avatar" : true,
- "avatar_icon" : "chrome://theme/IDR_PROFILE_AVATAR_0",
- "name" : "Person 1"
- }
- },
- "profiles_created" : 1,
- "last_used" : "Default",
- "last_active_profiles" : [
- "Default"
- ]
- }
-}
diff --git a/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist b/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist
deleted file mode 100644
index 40783c7b1..000000000
--- a/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist
+++ /dev/null
Binary files differ
diff --git a/browser/components/migration/tests/unit/head_migration.js b/browser/components/migration/tests/unit/head_migration.js
deleted file mode 100644
index d3c258d54..000000000
--- a/browser/components/migration/tests/unit/head_migration.js
+++ /dev/null
@@ -1,69 +0,0 @@
-"use strict";
-
-/* exported gProfD, promiseMigration, registerFakePath */
-
-var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
-
-Cu.importGlobalProperties([ "URL" ]);
-
-Cu.import("resource:///modules/MigrationUtils.jsm");
-Cu.import("resource://gre/modules/LoginHelper.jsm");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/PromiseUtils.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://testing-common/TestUtils.jsm");
-Cu.import("resource://testing-common/PlacesTestUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-// Initialize profile.
-var gProfD = do_get_profile();
-
-Cu.import("resource://testing-common/AppInfo.jsm"); /* globals updateAppInfo */
-updateAppInfo();
-
-/**
- * Migrates the requested resource and waits for the migration to be complete.
- */
-function promiseMigration(migrator, resourceType, aProfile = null) {
- // Ensure resource migration is available.
- let availableSources = migrator.getMigrateData(aProfile, false);
- Assert.ok((availableSources & resourceType) > 0, "Resource supported by migrator");
-
- return new Promise (resolve => {
- Services.obs.addObserver(function onMigrationEnded() {
- Services.obs.removeObserver(onMigrationEnded, "Migration:Ended");
- resolve();
- }, "Migration:Ended", false);
-
- migrator.migrate(resourceType, null, aProfile);
- });
-}
-
-/**
- * Replaces a directory service entry with a given nsIFile.
- */
-function registerFakePath(key, file) {
- // Register our own provider for the Library directory.
- let provider = {
- getFile(prop, persistent) {
- persistent.value = true;
- if (prop == key) {
- return file;
- }
- throw Cr.NS_ERROR_FAILURE;
- },
- QueryInterface: XPCOMUtils.generateQI([ Ci.nsIDirectoryServiceProvider ])
- };
- Services.dirsvc.QueryInterface(Ci.nsIDirectoryService)
- .registerProvider(provider);
- do_register_cleanup(() => {
- Services.dirsvc.QueryInterface(Ci.nsIDirectoryService)
- .unregisterProvider(provider);
- });
-}
diff --git a/browser/components/migration/tests/unit/test_Chrome_cookies.js b/browser/components/migration/tests/unit/test_Chrome_cookies.js
deleted file mode 100644
index 006693951..000000000
--- a/browser/components/migration/tests/unit/test_Chrome_cookies.js
+++ /dev/null
@@ -1,51 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/ForgetAboutSite.jsm");
-
-add_task(function* () {
- registerFakePath("ULibDir", do_get_file("Library/"));
- let migrator = MigrationUtils.getMigrator("chrome");
-
- Assert.ok(migrator.sourceExists, "Sanity check the source exists");
-
- const COOKIE = {
- expiry: 2145934800,
- host: "unencryptedcookie.invalid",
- isHttpOnly: false,
- isSession: false,
- name: "testcookie",
- path: "/",
- value: "testvalue",
- };
-
- // Sanity check.
- Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0,
- "There are no cookies initially");
-
- const PROFILE = {
- id: "Default",
- name: "Person 1",
- };
-
- // Migrate unencrypted cookies.
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.COOKIES, PROFILE);
-
- Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 1,
- "Migrated the expected number of unencrypted cookies");
- Assert.equal(Services.cookies.countCookiesFromHost("encryptedcookie.invalid"), 0,
- "Migrated the expected number of encrypted cookies");
-
- // Now check the cookie details.
- let enumerator = Services.cookies.getCookiesFromHost(COOKIE.host, {});
- Assert.ok(enumerator.hasMoreElements(), "Cookies available");
- let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
-
- for (let prop of Object.keys(COOKIE)) {
- Assert.equal(foundCookie[prop], COOKIE[prop], "Check cookie " + prop);
- }
-
- // Cleanup.
- ForgetAboutSite.removeDataFromDomain(COOKIE.host);
- Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0,
- "There are no cookies after cleanup");
-});
diff --git a/browser/components/migration/tests/unit/test_Chrome_passwords.js b/browser/components/migration/tests/unit/test_Chrome_passwords.js
deleted file mode 100644
index 49147bd61..000000000
--- a/browser/components/migration/tests/unit/test_Chrome_passwords.js
+++ /dev/null
@@ -1,219 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/OSCrypto.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-const PROFILE = {
- id: "Default",
- name: "Person 1",
-};
-
-const TEST_LOGINS = [
- {
- id: 1, // id of the row in the chrome login db
- username: "username",
- password: "password",
- hostname: "https://c9.io",
- formSubmitURL: "https://c9.io",
- httpRealm: null,
- usernameField: "inputEmail",
- passwordField: "inputPassword",
- timeCreated: 1437418416037,
- timePasswordChanged: 1437418416037,
- timesUsed: 1,
- },
- {
- id: 2,
- username: "username@gmail.com",
- password: "password2",
- hostname: "https://accounts.google.com",
- formSubmitURL: "https://accounts.google.com",
- httpRealm: null,
- usernameField: "Email",
- passwordField: "Passwd",
- timeCreated: 1437418446598,
- timePasswordChanged: 1437418446598,
- timesUsed: 6,
- },
- {
- id: 3,
- username: "username",
- password: "password3",
- hostname: "https://www.facebook.com",
- formSubmitURL: "https://www.facebook.com",
- httpRealm: null,
- usernameField: "email",
- passwordField: "pass",
- timeCreated: 1437418478851,
- timePasswordChanged: 1437418478851,
- timesUsed: 1,
- },
- {
- id: 4,
- username: "user",
- password: "password",
- hostname: "http://httpbin.org",
- formSubmitURL: null,
- httpRealm: "me@kennethreitz.com", // Digest auth.
- usernameField: "",
- passwordField: "",
- timeCreated: 1437787462368,
- timePasswordChanged: 1437787462368,
- timesUsed: 1,
- },
- {
- id: 5,
- username: "buser",
- password: "bpassword",
- hostname: "http://httpbin.org",
- formSubmitURL: null,
- httpRealm: "Fake Realm", // Basic auth.
- usernameField: "",
- passwordField: "",
- timeCreated: 1437787539233,
- timePasswordChanged: 1437787539233,
- timesUsed: 1,
- },
-];
-
-var crypto = new OSCrypto();
-var dbConn;
-
-function promiseSetPassword(login) {
- return new Promise((resolve, reject) => {
- let stmt = dbConn.createAsyncStatement(`
- UPDATE logins
- SET password_value = :password_value
- WHERE rowid = :rowid
- `);
- let passwordValue = crypto.stringToArray(crypto.encryptData(login.password));
- stmt.bindBlobByName("password_value", passwordValue, passwordValue.length);
- stmt.params.rowid = login.id;
-
- stmt.executeAsync({
- handleError(aError) {
- reject("Error with the query: " + aError.message);
- },
-
- handleCompletion(aReason) {
- if (aReason === Ci.mozIStorageStatementCallback.REASON_FINISHED) {
- resolve();
- } else {
- reject("Query has failed: " + aReason);
- }
- },
- });
- stmt.finalize();
- });
-}
-
-function checkLoginsAreEqual(passwordManagerLogin, chromeLogin, id) {
- passwordManagerLogin.QueryInterface(Ci.nsILoginMetaInfo);
-
- Assert.equal(passwordManagerLogin.username, chromeLogin.username,
- "The two logins ID " + id + " have the same username");
- Assert.equal(passwordManagerLogin.password, chromeLogin.password,
- "The two logins ID " + id + " have the same password");
- Assert.equal(passwordManagerLogin.hostname, chromeLogin.hostname,
- "The two logins ID " + id + " have the same hostname");
- Assert.equal(passwordManagerLogin.formSubmitURL, chromeLogin.formSubmitURL,
- "The two logins ID " + id + " have the same formSubmitURL");
- Assert.equal(passwordManagerLogin.httpRealm, chromeLogin.httpRealm,
- "The two logins ID " + id + " have the same httpRealm");
- Assert.equal(passwordManagerLogin.usernameField, chromeLogin.usernameField,
- "The two logins ID " + id + " have the same usernameElement");
- Assert.equal(passwordManagerLogin.passwordField, chromeLogin.passwordField,
- "The two logins ID " + id + " have the same passwordElement");
- Assert.equal(passwordManagerLogin.timeCreated, chromeLogin.timeCreated,
- "The two logins ID " + id + " have the same timeCreated");
- Assert.equal(passwordManagerLogin.timePasswordChanged, chromeLogin.timePasswordChanged,
- "The two logins ID " + id + " have the same timePasswordChanged");
- Assert.equal(passwordManagerLogin.timesUsed, chromeLogin.timesUsed,
- "The two logins ID " + id + " have the same timesUsed");
-}
-
-function generateDifferentLogin(login) {
- let newLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
-
- newLogin.init(login.hostname, login.formSubmitURL, null,
- login.username, login.password + 1, login.usernameField + 1,
- login.passwordField + 1);
- newLogin.QueryInterface(Ci.nsILoginMetaInfo);
- newLogin.timeCreated = login.timeCreated + 1;
- newLogin.timePasswordChanged = login.timePasswordChanged + 1;
- newLogin.timesUsed = login.timesUsed + 1;
- return newLogin;
-}
-
-add_task(function* setup() {
- let loginDataFile = do_get_file("AppData/Local/Google/Chrome/User Data/Default/Login Data");
- dbConn = Services.storage.openUnsharedDatabase(loginDataFile);
- registerFakePath("LocalAppData", do_get_file("AppData/Local/"));
-
- do_register_cleanup(() => {
- Services.logins.removeAllLogins();
- dbConn.asyncClose();
- crypto.finalize();
- });
-});
-
-add_task(function* test_importIntoEmptyDB() {
- for (let login of TEST_LOGINS) {
- yield promiseSetPassword(login);
- }
-
- let migrator = MigrationUtils.getMigrator("chrome");
- Assert.ok(migrator.sourceExists, "Sanity check the source exists");
-
- let logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0, "There are no logins initially");
-
- // Migrate the logins.
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.PASSWORDS, PROFILE);
-
- logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, TEST_LOGINS.length, "Check login count after importing the data");
- Assert.equal(logins.length, MigrationUtils._importQuantities.logins,
- "Check telemetry matches the actual import.");
-
- for (let i = 0; i < TEST_LOGINS.length; i++) {
- checkLoginsAreEqual(logins[i], TEST_LOGINS[i], i + 1);
- }
-});
-
-// Test that existing logins for the same primary key don't get overwritten
-add_task(function* test_importExistingLogins() {
- let migrator = MigrationUtils.getMigrator("chrome");
- Assert.ok(migrator.sourceExists, "Sanity check the source exists");
-
- Services.logins.removeAllLogins();
- let logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0, "There are no logins after removing all of them");
-
- let newLogins = [];
-
- // Create 3 new logins that are different but where the key properties are still the same.
- for (let i = 0; i < 3; i++) {
- newLogins.push(generateDifferentLogin(TEST_LOGINS[i]));
- Services.logins.addLogin(newLogins[i]);
- }
-
- logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, newLogins.length, "Check login count after the insertion");
-
- for (let i = 0; i < newLogins.length; i++) {
- checkLoginsAreEqual(logins[i], newLogins[i], i + 1);
- }
- // Migrate the logins.
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.PASSWORDS, PROFILE);
-
- logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, TEST_LOGINS.length,
- "Check there are still the same number of logins after re-importing the data");
- Assert.equal(logins.length, MigrationUtils._importQuantities.logins,
- "Check telemetry matches the actual import.");
-
- for (let i = 0; i < newLogins.length; i++) {
- checkLoginsAreEqual(logins[i], newLogins[i], i + 1);
- }
-});
diff --git a/browser/components/migration/tests/unit/test_Edge_availability.js b/browser/components/migration/tests/unit/test_Edge_availability.js
deleted file mode 100644
index dba0e27bb..000000000
--- a/browser/components/migration/tests/unit/test_Edge_availability.js
+++ /dev/null
@@ -1,20 +0,0 @@
-"use strict";
-
-const EDGE_AVAILABLE_MIGRATIONS =
- MigrationUtils.resourceTypes.COOKIES |
- MigrationUtils.resourceTypes.BOOKMARKS |
- MigrationUtils.resourceTypes.HISTORY |
- MigrationUtils.resourceTypes.PASSWORDS;
-
-add_task(function* () {
- let migrator = MigrationUtils.getMigrator("edge");
- Cu.import("resource://gre/modules/AppConstants.jsm");
- Assert.equal(!!(migrator && migrator.sourceExists), AppConstants.isPlatformAndVersionAtLeast("win", "10"),
- "Edge should be available for migration if and only if we're on Win 10+");
- if (migrator) {
- let migratableData = migrator.getMigrateData(null, false);
- Assert.equal(migratableData, EDGE_AVAILABLE_MIGRATIONS,
- "All the data types we expect should be available");
- }
-});
-
diff --git a/browser/components/migration/tests/unit/test_Edge_db_migration.js b/browser/components/migration/tests/unit/test_Edge_db_migration.js
deleted file mode 100644
index 56ff612d5..000000000
--- a/browser/components/migration/tests/unit/test_Edge_db_migration.js
+++ /dev/null
@@ -1,471 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/ctypes.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-let eseBackStage = Cu.import("resource:///modules/ESEDBReader.jsm");
-let ESE = eseBackStage.ESE;
-let KERNEL = eseBackStage.KERNEL;
-let gLibs = eseBackStage.gLibs;
-let COLUMN_TYPES = eseBackStage.COLUMN_TYPES;
-let declareESEFunction = eseBackStage.declareESEFunction;
-let loadLibraries = eseBackStage.loadLibraries;
-
-let gESEInstanceCounter = 1;
-
-ESE.JET_COLUMNCREATE_W = new ctypes.StructType("JET_COLUMNCREATE_W", [
- {"cbStruct": ctypes.unsigned_long},
- {"szColumnName": ESE.JET_PCWSTR},
- {"coltyp": ESE.JET_COLTYP },
- {"cbMax": ctypes.unsigned_long },
- {"grbit": ESE.JET_GRBIT },
- {"pvDefault": ctypes.voidptr_t},
- {"cbDefault": ctypes.unsigned_long },
- {"cp": ctypes.unsigned_long },
- {"columnid": ESE.JET_COLUMNID},
- {"err": ESE.JET_ERR},
-]);
-
-function createColumnCreationWrapper({name, type, cbMax}) {
- // We use a wrapper object because we need to be sure the JS engine won't GC
- // data that we're "only" pointing to.
- let wrapper = {};
- wrapper.column = new ESE.JET_COLUMNCREATE_W();
- wrapper.column.cbStruct = ESE.JET_COLUMNCREATE_W.size;
- let wchar_tArray = ctypes.ArrayType(ctypes.char16_t);
- wrapper.name = new wchar_tArray(name.length + 1);
- wrapper.name.value = String(name);
- wrapper.column.szColumnName = wrapper.name;
- wrapper.column.coltyp = type;
- let fallback = 0;
- switch (type) {
- case COLUMN_TYPES.JET_coltypText:
- fallback = 255;
- // Intentional fall-through
- case COLUMN_TYPES.JET_coltypLongText:
- wrapper.column.cbMax = cbMax || fallback || 64 * 1024;
- break;
- case COLUMN_TYPES.JET_coltypGUID:
- wrapper.column.cbMax = 16;
- break;
- case COLUMN_TYPES.JET_coltypBit:
- wrapper.column.cbMax = 1;
- break;
- case COLUMN_TYPES.JET_coltypLongLong:
- wrapper.column.cbMax = 8;
- break;
- default:
- throw new Error("Unknown column type!");
- }
-
- wrapper.column.columnid = new ESE.JET_COLUMNID();
- wrapper.column.grbit = 0;
- wrapper.column.pvDefault = null;
- wrapper.column.cbDefault = 0;
- wrapper.column.cp = 0;
-
- return wrapper;
-}
-
-// "forward declarations" of indexcreate and setinfo structs, which we don't use.
-ESE.JET_INDEXCREATE = new ctypes.StructType("JET_INDEXCREATE");
-ESE.JET_SETINFO = new ctypes.StructType("JET_SETINFO");
-
-ESE.JET_TABLECREATE_W = new ctypes.StructType("JET_TABLECREATE_W", [
- {"cbStruct": ctypes.unsigned_long},
- {"szTableName": ESE.JET_PCWSTR},
- {"szTemplateTableName": ESE.JET_PCWSTR},
- {"ulPages": ctypes.unsigned_long},
- {"ulDensity": ctypes.unsigned_long},
- {"rgcolumncreate": ESE.JET_COLUMNCREATE_W.ptr},
- {"cColumns": ctypes.unsigned_long},
- {"rgindexcreate": ESE.JET_INDEXCREATE.ptr},
- {"cIndexes": ctypes.unsigned_long},
- {"grbit": ESE.JET_GRBIT},
- {"tableid": ESE.JET_TABLEID},
- {"cCreated": ctypes.unsigned_long},
-]);
-
-function createTableCreationWrapper(tableName, columns) {
- let wrapper = {};
- let wchar_tArray = ctypes.ArrayType(ctypes.char16_t);
- wrapper.name = new wchar_tArray(tableName.length + 1);
- wrapper.name.value = String(tableName);
- wrapper.table = new ESE.JET_TABLECREATE_W();
- wrapper.table.cbStruct = ESE.JET_TABLECREATE_W.size;
- wrapper.table.szTableName = wrapper.name;
- wrapper.table.szTemplateTableName = null;
- wrapper.table.ulPages = 1;
- wrapper.table.ulDensity = 0;
- let columnArrayType = ESE.JET_COLUMNCREATE_W.array(columns.length);
- wrapper.columnAry = new columnArrayType();
- wrapper.table.rgcolumncreate = wrapper.columnAry.addressOfElement(0);
- wrapper.table.cColumns = columns.length;
- wrapper.columns = [];
- for (let i = 0; i < columns.length; i++) {
- let column = columns[i];
- let columnWrapper = createColumnCreationWrapper(column);
- wrapper.columnAry.addressOfElement(i).contents = columnWrapper.column;
- wrapper.columns.push(columnWrapper);
- }
- wrapper.table.rgindexcreate = null;
- wrapper.table.cIndexes = 0;
- return wrapper;
-}
-
-function convertValueForWriting(value, valueType) {
- let buffer;
- let valueOfValueType = ctypes.UInt64.lo(valueType);
- switch (valueOfValueType) {
- case COLUMN_TYPES.JET_coltypLongLong:
- if (value instanceof Date) {
- buffer = new KERNEL.FILETIME();
- let sysTime = new KERNEL.SYSTEMTIME();
- sysTime.wYear = value.getUTCFullYear();
- sysTime.wMonth = value.getUTCMonth() + 1;
- sysTime.wDay = value.getUTCDate();
- sysTime.wHour = value.getUTCHours();
- sysTime.wMinute = value.getUTCMinutes();
- sysTime.wSecond = value.getUTCSeconds();
- sysTime.wMilliseconds = value.getUTCMilliseconds();
- let rv = KERNEL.SystemTimeToFileTime(sysTime.address(), buffer.address());
- if (!rv) {
- throw new Error("Failed to get FileTime.");
- }
- return [buffer, KERNEL.FILETIME.size];
- }
- throw new Error("Unrecognized value for longlong column");
- case COLUMN_TYPES.JET_coltypLongText:
- let wchar_tArray = ctypes.ArrayType(ctypes.char16_t);
- buffer = new wchar_tArray(value.length + 1);
- buffer.value = String(value);
- return [buffer, buffer.length * 2];
- case COLUMN_TYPES.JET_coltypBit:
- buffer = new ctypes.uint8_t();
- // Bizarre boolean values, but whatever:
- buffer.value = value ? 255 : 0;
- return [buffer, 1];
- case COLUMN_TYPES.JET_coltypGUID:
- let byteArray = ctypes.ArrayType(ctypes.uint8_t);
- buffer = new byteArray(16);
- let j = 0;
- for (let i = 0; i < value.length; i++) {
- if (!(/[0-9a-f]/i).test(value[i])) {
- continue;
- }
- let byteAsHex = value.substr(i, 2);
- buffer[j++] = parseInt(byteAsHex, 16);
- i++;
- }
- return [buffer, 16];
- }
-
- throw new Error("Unknown type " + valueType);
-}
-
-let initializedESE = false;
-
-let eseDBWritingHelpers = {
- setupDB(dbFile, tableName, columns, rows) {
- if (!initializedESE) {
- initializedESE = true;
- loadLibraries();
-
- KERNEL.SystemTimeToFileTime = gLibs.kernel.declare("SystemTimeToFileTime",
- ctypes.default_abi, ctypes.bool, KERNEL.SYSTEMTIME.ptr, KERNEL.FILETIME.ptr);
-
- declareESEFunction("CreateDatabaseW", ESE.JET_SESID, ESE.JET_PCWSTR,
- ESE.JET_PCWSTR, ESE.JET_DBID.ptr, ESE.JET_GRBIT);
- declareESEFunction("CreateTableColumnIndexW", ESE.JET_SESID, ESE.JET_DBID,
- ESE.JET_TABLECREATE_W.ptr);
- declareESEFunction("BeginTransaction", ESE.JET_SESID);
- declareESEFunction("CommitTransaction", ESE.JET_SESID, ESE.JET_GRBIT);
- declareESEFunction("PrepareUpdate", ESE.JET_SESID, ESE.JET_TABLEID,
- ctypes.unsigned_long);
- declareESEFunction("Update", ESE.JET_SESID, ESE.JET_TABLEID,
- ctypes.voidptr_t, ctypes.unsigned_long,
- ctypes.unsigned_long.ptr);
- declareESEFunction("SetColumn", ESE.JET_SESID, ESE.JET_TABLEID,
- ESE.JET_COLUMNID, ctypes.voidptr_t,
- ctypes.unsigned_long, ESE.JET_GRBIT, ESE.JET_SETINFO.ptr);
- ESE.SetSystemParameterW(null, 0, 64 /* JET_paramDatabasePageSize*/,
- 8192, null);
- }
-
- let rootPath = dbFile.parent.path + "\\";
- let logPath = rootPath + "LogFiles\\";
-
- try {
- this._instanceId = new ESE.JET_INSTANCE();
- ESE.CreateInstanceW(this._instanceId.address(),
- "firefox-dbwriter-" + (gESEInstanceCounter++));
- this._instanceCreated = true;
-
- ESE.SetSystemParameterW(this._instanceId.address(), 0,
- 0 /* JET_paramSystemPath*/, 0, rootPath);
- ESE.SetSystemParameterW(this._instanceId.address(), 0,
- 1 /* JET_paramTempPath */, 0, rootPath);
- ESE.SetSystemParameterW(this._instanceId.address(), 0,
- 2 /* JET_paramLogFilePath*/, 0, logPath);
- // Shouldn't try to call JetTerm if the following call fails.
- this._instanceCreated = false;
- ESE.Init(this._instanceId.address());
- this._instanceCreated = true;
- this._sessionId = new ESE.JET_SESID();
- ESE.BeginSessionW(this._instanceId, this._sessionId.address(), null,
- null);
- this._sessionCreated = true;
-
- this._dbId = new ESE.JET_DBID();
- this._dbPath = rootPath + "spartan.edb";
- ESE.CreateDatabaseW(this._sessionId, this._dbPath, null,
- this._dbId.address(), 0);
- this._opened = this._attached = true;
-
- let tableCreationWrapper = createTableCreationWrapper(tableName, columns);
- ESE.CreateTableColumnIndexW(this._sessionId, this._dbId,
- tableCreationWrapper.table.address());
- this._tableId = tableCreationWrapper.table.tableid;
-
- let columnIdMap = new Map();
- if (rows.length) {
- // Iterate over the struct we passed into ESENT because they have the
- // created column ids.
- let columnCount = ctypes.UInt64.lo(tableCreationWrapper.table.cColumns);
- let columnsPassed = tableCreationWrapper.table.rgcolumncreate;
- for (let i = 0; i < columnCount; i++) {
- let column = columnsPassed.contents;
- columnIdMap.set(column.szColumnName.readString(), column);
- columnsPassed = columnsPassed.increment();
- }
- ESE.ManualMove(this._sessionId, this._tableId,
- -2147483648 /* JET_MoveFirst */, 0);
- ESE.BeginTransaction(this._sessionId);
- for (let row of rows) {
- ESE.PrepareUpdate(this._sessionId, this._tableId, 0 /* JET_prepInsert */);
- for (let columnName in row) {
- let col = columnIdMap.get(columnName);
- let colId = col.columnid;
- let [val, valSize] = convertValueForWriting(row[columnName], col.coltyp);
- /* JET_bitSetOverwriteLV */
- ESE.SetColumn(this._sessionId, this._tableId, colId, val.address(), valSize, 4, null);
- }
- let actualBookmarkSize = new ctypes.unsigned_long();
- ESE.Update(this._sessionId, this._tableId, null, 0, actualBookmarkSize.address());
- }
- ESE.CommitTransaction(this._sessionId, 0 /* JET_bitWaitLastLevel0Commit */);
- }
- } finally {
- try {
- this._close();
- } catch (ex) {
- Cu.reportError(ex);
- }
- }
- },
-
- _close() {
- if (this._tableId) {
- ESE.FailSafeCloseTable(this._sessionId, this._tableId);
- delete this._tableId;
- }
- if (this._opened) {
- ESE.FailSafeCloseDatabase(this._sessionId, this._dbId, 0);
- this._opened = false;
- }
- if (this._attached) {
- ESE.FailSafeDetachDatabaseW(this._sessionId, this._dbPath);
- this._attached = false;
- }
- if (this._sessionCreated) {
- ESE.FailSafeEndSession(this._sessionId, 0);
- this._sessionCreated = false;
- }
- if (this._instanceCreated) {
- ESE.FailSafeTerm(this._instanceId);
- this._instanceCreated = false;
- }
- },
-};
-
-add_task(function*() {
- let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
- tempFile.append("fx-xpcshell-edge-db");
- tempFile.createUnique(tempFile.DIRECTORY_TYPE, 0o600);
-
- let db = tempFile.clone();
- db.append("spartan.edb");
-
- let logs = tempFile.clone();
- logs.append("LogFiles");
- logs.create(tempFile.DIRECTORY_TYPE, 0o600);
-
- let creationDate = new Date(Date.now() - 5000);
- const kEdgeMenuParent = "62d07e2b-5f0d-4e41-8426-5f5ec9717beb";
- let itemsInDB = [
- {
- URL: "http://www.mozilla.org/",
- Title: "Mozilla",
- DateUpdated: new Date(creationDate.valueOf() + 100),
- ItemId: "1c00c10a-15f6-4618-92dd-22575102a4da",
- ParentId: kEdgeMenuParent,
- IsFolder: false,
- IsDeleted: false,
- },
- {
- Title: "Folder",
- DateUpdated: new Date(creationDate.valueOf() + 200),
- ItemId: "564b21f2-05d6-4f7d-8499-304d00ccc3aa",
- ParentId: kEdgeMenuParent,
- IsFolder: true,
- IsDeleted: false,
- },
- {
- Title: "Item in folder",
- URL: "http://www.iteminfolder.org/",
- DateUpdated: new Date(creationDate.valueOf() + 300),
- ItemId: "c295ddaf-04a1-424a-866c-0ebde011e7c8",
- ParentId: "564b21f2-05d6-4f7d-8499-304d00ccc3aa",
- IsFolder: false,
- IsDeleted: false,
- },
- {
- Title: "Deleted folder",
- DateUpdated: new Date(creationDate.valueOf() + 400),
- ItemId: "a547573c-4d4d-4406-a736-5b5462d93bca",
- ParentId: kEdgeMenuParent,
- IsFolder: true,
- IsDeleted: true,
- },
- {
- Title: "Deleted item",
- URL: "http://www.deleteditem.org/",
- DateUpdated: new Date(creationDate.valueOf() + 500),
- ItemId: "37a574bb-b44b-4bbc-a414-908615536435",
- ParentId: kEdgeMenuParent,
- IsFolder: false,
- IsDeleted: true,
- },
- {
- Title: "Item in deleted folder (should be in root)",
- URL: "http://www.itemindeletedfolder.org/",
- DateUpdated: new Date(creationDate.valueOf() + 600),
- ItemId: "74dd1cc3-4c5d-471f-bccc-7bc7c72fa621",
- ParentId: "a547573c-4d4d-4406-a736-5b5462d93bca",
- IsFolder: false,
- IsDeleted: false,
- },
- {
- Title: "_Favorites_Bar_",
- DateUpdated: new Date(creationDate.valueOf() + 700),
- ItemId: "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf",
- ParentId: kEdgeMenuParent,
- IsFolder: true,
- IsDeleted: false,
- },
- {
- Title: "Item in favorites bar",
- URL: "http://www.iteminfavoritesbar.org/",
- DateUpdated: new Date(creationDate.valueOf() + 800),
- ItemId: "9f2b1ff8-b651-46cf-8f41-16da8bcb6791",
- ParentId: "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf",
- IsFolder: false,
- IsDeleted: false,
- },
- ];
- eseDBWritingHelpers.setupDB(db, "Favorites", [
- {type: COLUMN_TYPES.JET_coltypLongText, name: "URL", cbMax: 4096},
- {type: COLUMN_TYPES.JET_coltypLongText, name: "Title", cbMax: 4096},
- {type: COLUMN_TYPES.JET_coltypLongLong, name: "DateUpdated"},
- {type: COLUMN_TYPES.JET_coltypGUID, name: "ItemId"},
- {type: COLUMN_TYPES.JET_coltypBit, name: "IsDeleted"},
- {type: COLUMN_TYPES.JET_coltypBit, name: "IsFolder"},
- {type: COLUMN_TYPES.JET_coltypGUID, name: "ParentId"},
- ], itemsInDB);
-
- let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=edge"]
- .createInstance(Ci.nsIBrowserProfileMigrator);
- let bookmarksMigrator = migrator.wrappedJSObject.getESEMigratorForTesting(db);
- Assert.ok(bookmarksMigrator.exists, "Should recognize table we just created");
-
- let source = MigrationUtils.getLocalizedString("sourceNameEdge");
- let sourceLabel = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]);
-
- let seenBookmarks = [];
- let bookmarkObserver = {
- onItemAdded(itemId, parentId, index, itemType, url, title, dateAdded, itemGuid, parentGuid) {
- if (title.startsWith("Deleted")) {
- ok(false, "Should not see deleted items being bookmarked!");
- }
- seenBookmarks.push({itemId, parentId, index, itemType, url, title, dateAdded, itemGuid, parentGuid});
- },
- onBeginUpdateBatch() {},
- onEndUpdateBatch() {},
- onItemRemoved() {},
- onItemChanged() {},
- onItemVisited() {},
- onItemMoved() {},
- };
- PlacesUtils.bookmarks.addObserver(bookmarkObserver, false);
-
- let migrateResult = yield new Promise(resolve => bookmarksMigrator.migrate(resolve)).catch(ex => {
- Cu.reportError(ex);
- Assert.ok(false, "Got an exception trying to migrate data! " + ex);
- return false;
- });
- PlacesUtils.bookmarks.removeObserver(bookmarkObserver);
- Assert.ok(migrateResult, "Migration should succeed");
- Assert.equal(seenBookmarks.length, 7, "Should have seen 7 items being bookmarked.");
- Assert.equal(seenBookmarks.filter(bm => bm.title != sourceLabel).length,
- MigrationUtils._importQuantities.bookmarks,
- "Telemetry should have items except for 'From Microsoft Edge' folders");
-
- let menuParents = seenBookmarks.filter(item => item.parentGuid == PlacesUtils.bookmarks.menuGuid);
- Assert.equal(menuParents.length, 1, "Should have a single folder added to the menu");
- let toolbarParents = seenBookmarks.filter(item => item.parentGuid == PlacesUtils.bookmarks.toolbarGuid);
- Assert.equal(toolbarParents.length, 1, "Should have a single item added to the toolbar");
- let menuParentGuid = menuParents[0].itemGuid;
- let toolbarParentGuid = toolbarParents[0].itemGuid;
-
- let expectedTitlesInMenu = itemsInDB.filter(item => item.ParentId == kEdgeMenuParent).map(item => item.Title);
- // Hacky, but seems like much the simplest way:
- expectedTitlesInMenu.push("Item in deleted folder (should be in root)");
- let expectedTitlesInToolbar = itemsInDB.filter(item => item.ParentId == "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf").map(item => item.Title);
-
- let edgeNameStr = MigrationUtils.getLocalizedString("sourceNameEdge");
- let importParentFolderName = MigrationUtils.getLocalizedString("importedBookmarksFolder", [edgeNameStr]);
-
- for (let bookmark of seenBookmarks) {
- let shouldBeInMenu = expectedTitlesInMenu.includes(bookmark.title);
- let shouldBeInToolbar = expectedTitlesInToolbar.includes(bookmark.title);
- if (bookmark.title == "Folder" || bookmark.title == importParentFolderName) {
- Assert.equal(bookmark.itemType, PlacesUtils.bookmarks.TYPE_FOLDER,
- "Bookmark " + bookmark.title + " should be a folder");
- } else {
- Assert.notEqual(bookmark.itemType, PlacesUtils.bookmarks.TYPE_FOLDER,
- "Bookmark " + bookmark.title + " should not be a folder");
- }
-
- if (shouldBeInMenu) {
- Assert.equal(bookmark.parentGuid, menuParentGuid, "Item '" + bookmark.title + "' should be in menu");
- } else if (shouldBeInToolbar) {
- Assert.equal(bookmark.parentGuid, toolbarParentGuid, "Item '" + bookmark.title + "' should be in toolbar");
- } else if (bookmark.itemGuid == menuParentGuid || bookmark.itemGuid == toolbarParentGuid) {
- Assert.ok(true, "Expect toolbar and menu folders to not be in menu or toolbar");
- } else {
- // Bit hacky, but we do need to check this.
- Assert.equal(bookmark.title, "Item in folder", "Subfoldered item shouldn't be in menu or toolbar");
- let parent = seenBookmarks.find(maybeParent => maybeParent.itemGuid == bookmark.parentGuid);
- Assert.equal(parent && parent.title, "Folder", "Subfoldered item should be in subfolder labeled 'Folder'");
- }
-
- let dbItem = itemsInDB.find(someItem => bookmark.title == someItem.Title);
- if (!dbItem) {
- Assert.equal(bookmark.title, importParentFolderName, "Only the extra layer of folders isn't in the input we stuck in the DB.");
- Assert.ok([menuParentGuid, toolbarParentGuid].includes(bookmark.itemGuid), "This item should be one of the containers");
- } else {
- Assert.equal(dbItem.URL || null, bookmark.url && bookmark.url.spec, "URL is correct");
- Assert.equal(dbItem.DateUpdated.valueOf(), (new Date(bookmark.dateAdded / 1000)).valueOf(), "Date added is correct");
- }
- }
-});
-
diff --git a/browser/components/migration/tests/unit/test_IE7_passwords.js b/browser/components/migration/tests/unit/test_IE7_passwords.js
deleted file mode 100644
index 1ce016a7d..000000000
--- a/browser/components/migration/tests/unit/test_IE7_passwords.js
+++ /dev/null
@@ -1,397 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/AppConstants.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry",
- "resource://gre/modules/WindowsRegistry.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto",
- "resource://gre/modules/OSCrypto.jsm");
-
-const IE7_FORM_PASSWORDS_MIGRATOR_NAME = "IE7FormPasswords";
-const LOGINS_KEY = "Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2";
-const EXTENSION = "-backup";
-const TESTED_WEBSITES = {
- twitter: {
- uri: makeURI("https://twitter.com"),
- hash: "A89D42BC6406E27265B1AD0782B6F376375764A301",
- data: [12, 0, 0, 0, 56, 0, 0, 0, 38, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 36, 67, 124, 118, 212, 208, 1, 8, 0, 0, 0, 18, 0, 0, 0, 68, 36, 67, 124, 118, 212, 208, 1, 9, 0, 0, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104, 0, 0, 0, 49, 0, 50, 0, 51, 0, 52, 0, 53, 0, 54, 0, 55, 0, 56, 0, 57, 0, 0, 0],
- logins: [
- {
- username: "abcdefgh",
- password: "123456789",
- hostname: "https://twitter.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439325854000,
- timeLastUsed: 1439325854000,
- timePasswordChanged: 1439325854000,
- timesUsed: 1,
- },
- ],
- },
- facebook: {
- uri: makeURI("https://www.facebook.com/"),
- hash: "EF44D3E034009CB0FD1B1D81A1FF3F3335213BD796",
- data: [12, 0, 0, 0, 152, 0, 0, 0, 160, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 182, 125, 18, 121, 212, 208, 1, 9, 0, 0, 0, 20, 0, 0, 0, 88, 182, 125, 18, 121, 212, 208, 1, 9, 0, 0, 0, 40, 0, 0, 0, 134, 65, 33, 37, 121, 212, 208, 1, 9, 0, 0, 0, 60, 0, 0, 0, 134, 65, 33, 37, 121, 212, 208, 1, 9, 0, 0, 0, 80, 0, 0, 0, 45, 242, 246, 62, 121, 212, 208, 1, 9, 0, 0, 0, 100, 0, 0, 0, 45, 242, 246, 62, 121, 212, 208, 1, 9, 0, 0, 0, 120, 0, 0, 0, 28, 10, 193, 80, 121, 212, 208, 1, 9, 0, 0, 0, 140, 0, 0, 0, 28, 10, 193, 80, 121, 212, 208, 1, 9, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 48, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 48, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 49, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 49, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 50, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 50, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 51, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 51, 0, 0, 0],
- logins: [
- {
- username: "username0",
- password: "password0",
- hostname: "https://www.facebook.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439326966000,
- timeLastUsed: 1439326966000,
- timePasswordChanged: 1439326966000,
- timesUsed: 1,
- },
- {
- username: "username1",
- password: "password1",
- hostname: "https://www.facebook.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439326997000,
- timeLastUsed: 1439326997000,
- timePasswordChanged: 1439326997000,
- timesUsed: 1,
- },
- {
- username: "username2",
- password: "password2",
- hostname: "https://www.facebook.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439327040000,
- timeLastUsed: 1439327040000,
- timePasswordChanged: 1439327040000,
- timesUsed: 1,
- },
- {
- username: "username3",
- password: "password3",
- hostname: "https://www.facebook.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439327070000,
- timeLastUsed: 1439327070000,
- timePasswordChanged: 1439327070000,
- timesUsed: 1,
- },
- ],
- },
- live: {
- uri: makeURI("https://login.live.com/"),
- hash: "7B506F2D6B81D939A8E0456F036EE8970856FF705E",
- data: [12, 0, 0, 0, 56, 0, 0, 0, 44, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 17, 219, 140, 148, 212, 208, 1, 9, 0, 0, 0, 20, 0, 0, 0, 212, 17, 219, 140, 148, 212, 208, 1, 11, 0, 0, 0, 114, 0, 105, 0, 97, 0, 100, 0, 104, 0, 49, 6, 74, 6, 39, 6, 54, 6, 0, 0, 39, 6, 66, 6, 49, 6, 35, 6, 80, 0, 192, 0, 223, 0, 119, 0, 246, 0, 114, 0, 100, 0, 0, 0],
- logins: [
- {
- username: "riadhرياض",
- password: "اقرأPÀßwörd",
- hostname: "https://login.live.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439338767000,
- timeLastUsed: 1439338767000,
- timePasswordChanged: 1439338767000,
- timesUsed: 1,
- },
- ],
- },
- reddit: {
- uri: makeURI("http://www.reddit.com/"),
- hash: "B644028D1C109A91EC2C4B9D1F145E55A1FAE42065",
- data: [12, 0, 0, 0, 152, 0, 0, 0, 212, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 8, 234, 114, 153, 212, 208, 1, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 97, 93, 131, 116, 153, 212, 208, 1, 3, 0, 0, 0, 14, 0, 0, 0, 97, 93, 131, 116, 153, 212, 208, 1, 16, 0, 0, 0, 48, 0, 0, 0, 88, 150, 78, 174, 153, 212, 208, 1, 4, 0, 0, 0, 58, 0, 0, 0, 88, 150, 78, 174, 153, 212, 208, 1, 29, 0, 0, 0, 118, 0, 0, 0, 79, 102, 137, 34, 154, 212, 208, 1, 15, 0, 0, 0, 150, 0, 0, 0, 79, 102, 137, 34, 154, 212, 208, 1, 30, 0, 0, 0, 97, 0, 0, 0, 0, 0, 252, 140, 173, 138, 146, 48, 0, 0, 66, 0, 105, 0, 116, 0, 116, 0, 101, 0, 32, 0, 98, 0, 101, 0, 115, 0, 116, 0, 228, 0, 116, 0, 105, 0, 103, 0, 101, 0, 110, 0, 0, 0, 205, 145, 110, 127, 198, 91, 1, 120, 0, 0, 31, 4, 48, 4, 64, 4, 62, 4, 59, 4, 76, 4, 32, 0, 67, 4, 65, 4, 63, 4, 53, 4, 72, 4, 61, 4, 62, 4, 32, 0, 65, 4, 49, 4, 64, 4, 62, 4, 72, 4, 53, 4, 61, 4, 46, 0, 32, 0, 18, 4, 62, 4, 57, 4, 66, 4, 56, 4, 0, 0, 40, 6, 51, 6, 69, 6, 32, 0, 39, 6, 68, 6, 68, 6, 71, 6, 32, 0, 39, 6, 68, 6, 49, 6, 45, 6, 69, 6, 70, 6, 0, 0, 118, 0, 101, 0, 117, 0, 105, 0, 108, 0, 108, 0, 101, 0, 122, 0, 32, 0, 108, 0, 101, 0, 32, 0, 118, 0, 233, 0, 114, 0, 105, 0, 102, 0, 105, 0, 101, 0, 114, 0, 32, 0, 224, 0, 32, 0, 110, 0, 111, 0, 117, 0, 118, 0, 101, 0, 97, 0, 117, 0, 0, 0],
- logins: [
- {
- username: "購読を",
- password: "Bitte bestätigen",
- hostname: "http://www.reddit.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439340874000,
- timeLastUsed: 1439340874000,
- timePasswordChanged: 1439340874000,
- timesUsed: 1,
- },
- {
- username: "é‡ç½®å¯†ç ",
- password: "Пароль уÑпешно Ñброшен. Войти",
- hostname: "http://www.reddit.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439340971000,
- timeLastUsed: 1439340971000,
- timePasswordChanged: 1439340971000,
- timesUsed: 1,
- },
- {
- username: "بسم الله الرحمن",
- password: "veuillez le vérifier à nouveau",
- hostname: "http://www.reddit.com",
- formSubmitURL: "",
- httpRealm: null,
- usernameField: "",
- passwordField: "",
- timeCreated: 1439341166000,
- timeLastUsed: 1439341166000,
- timePasswordChanged: 1439341166000,
- timesUsed: 1,
- },
- ],
- },
-};
-
-const TESTED_URLS = [
- "http://a.foo.com",
- "http://b.foo.com",
- "http://c.foo.com",
- "http://www.test.net",
- "http://www.test.net/home",
- "http://www.test.net/index",
- "https://a.bar.com",
- "https://b.bar.com",
- "https://c.bar.com",
-];
-
-var nsIWindowsRegKey = Ci.nsIWindowsRegKey;
-var Storage2Key;
-
-/*
- * If the key value exists, it's going to be backed up and replaced, so the value could be restored.
- * Otherwise a new value is going to be created.
- */
-function backupAndStore(key, name, value) {
- if (key.hasValue(name)) {
- // backup the the current value
- let type = key.getValueType(name);
- // create a new value using use the current value name followed by EXTENSION as its new name
- switch (type) {
- case nsIWindowsRegKey.TYPE_STRING:
- key.writeStringValue(name + EXTENSION, key.readStringValue(name));
- break;
- case nsIWindowsRegKey.TYPE_BINARY:
- key.writeBinaryValue(name + EXTENSION, key.readBinaryValue(name));
- break;
- case nsIWindowsRegKey.TYPE_INT:
- key.writeIntValue(name + EXTENSION, key.readIntValue(name));
- break;
- case nsIWindowsRegKey.TYPE_INT64:
- key.writeInt64Value(name + EXTENSION, key.readInt64Value(name));
- break;
- }
- }
- key.writeBinaryValue(name, value);
-}
-
-// Remove all values where their names are members of the names array from the key of registry
-function removeAllValues(key, names) {
- for (let name of names) {
- key.removeValue(name);
- }
-}
-
-// Restore all the backed up values
-function restore(key) {
- let count = key.valueCount;
- let names = []; // the names of the key values
- for (let i = 0; i < count; ++i) {
- names.push(key.getValueName(i));
- }
-
- for (let name of names) {
- // backed up values have EXTENSION at the end of their names
- if (name.lastIndexOf(EXTENSION) == name.length - EXTENSION.length) {
- let valueName = name.substr(0, name.length - EXTENSION.length);
- let type = key.getValueType(name);
- // create a new value using the name before the backup and removed the backed up one
- switch (type) {
- case nsIWindowsRegKey.TYPE_STRING:
- key.writeStringValue(valueName, key.readStringValue(name));
- key.removeValue(name);
- break;
- case nsIWindowsRegKey.TYPE_BINARY:
- key.writeBinaryValue(valueName, key.readBinaryValue(name));
- key.removeValue(name);
- break;
- case nsIWindowsRegKey.TYPE_INT:
- key.writeIntValue(valueName, key.readIntValue(name));
- key.removeValue(name);
- break;
- case nsIWindowsRegKey.TYPE_INT64:
- key.writeInt64Value(valueName, key.readInt64Value(name));
- key.removeValue(name);
- break;
- }
- }
- }
-}
-
-function checkLoginsAreEqual(passwordManagerLogin, IELogin, id) {
- passwordManagerLogin.QueryInterface(Ci.nsILoginMetaInfo);
- for (let attribute in IELogin) {
- Assert.equal(passwordManagerLogin[attribute], IELogin[attribute],
- "The two logins ID " + id + " have the same " + attribute);
- }
-}
-
-function createRegistryPath(path) {
- let loginPath = path.split("\\");
- let parentKey = Cc["@mozilla.org/windows-registry-key;1"].
- createInstance(nsIWindowsRegKey);
- let currentPath = [];
- for (let currentKey of loginPath) {
- parentKey.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, currentPath.join("\\"),
- nsIWindowsRegKey.ACCESS_ALL);
-
- if (!parentKey.hasChild(currentKey)) {
- parentKey.createChild(currentKey, 0);
- }
- currentPath.push(currentKey);
- parentKey.close();
- }
-}
-
-function getFirstResourceOfType(type) {
- let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=ie"]
- .createInstance(Ci.nsISupports)
- .wrappedJSObject;
- let migrators = migrator.getResources();
- for (let m of migrators) {
- if (m.name == IE7_FORM_PASSWORDS_MIGRATOR_NAME && m.type == type) {
- return m;
- }
- }
- throw new Error("failed to find the " + type + " migrator");
-}
-
-function makeURI(aURL) {
- return Services.io.newURI(aURL, null, null);
-}
-
-add_task(function* setup() {
- if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) {
- Assert.throws(() => getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS),
- "The migrator doesn't exist for win8+");
- return;
- }
- // create the path to Storage2 in the registry if it doest exist.
- createRegistryPath(LOGINS_KEY);
- Storage2Key = Cc["@mozilla.org/windows-registry-key;1"].
- createInstance(nsIWindowsRegKey);
- Storage2Key.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, LOGINS_KEY,
- nsIWindowsRegKey.ACCESS_ALL);
-
- // create a dummy value otherwise the migrator doesn't exist
- if (!Storage2Key.hasValue("dummy")) {
- Storage2Key.writeBinaryValue("dummy", "dummy");
- }
-});
-
-add_task(function* test_passwordsNotAvailable() {
- if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) {
- return;
- }
-
- let migrator = getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS);
- Assert.ok(migrator.exists, "The migrator has to exist");
- let logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0, "There are no logins at the beginning of the test");
-
- let uris = []; // the uris of the migrated logins
- for (let url of TESTED_URLS) {
- uris.push(makeURI(url));
- // in this test, there is no IE login data in the registry, so after the migration, the number
- // of logins in the store should be 0
- migrator._migrateURIs(uris);
- logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0,
- "There are no logins after doing the migration without adding values to the registry");
- }
-});
-
-add_task(function* test_passwordsAvailable() {
- if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) {
- return;
- }
-
- let crypto = new OSCrypto();
- let hashes = []; // the hashes of all migrator websites, this is going to be used for the clean up
-
- do_register_cleanup(() => {
- Services.logins.removeAllLogins();
- logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0, "There are no logins after the cleanup");
- // remove all the values created in this test from the registry
- removeAllValues(Storage2Key, hashes);
- // restore all backed up values
- restore(Storage2Key);
-
- // clean the dummy value
- if (Storage2Key.hasValue("dummy")) {
- Storage2Key.removeValue("dummy");
- }
- Storage2Key.close();
- crypto.finalize();
- });
-
- let migrator = getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS);
- Assert.ok(migrator.exists, "The migrator has to exist");
- let logins = Services.logins.getAllLogins({});
- Assert.equal(logins.length, 0, "There are no logins at the beginning of the test");
-
- let uris = []; // the uris of the migrated logins
-
- let loginCount = 0;
- for (let current in TESTED_WEBSITES) {
- let website = TESTED_WEBSITES[current];
- // backup the current the registry value if it exists and replace the existing value/create a
- // new value with the encrypted data
- backupAndStore(Storage2Key, website.hash,
- crypto.encryptData(crypto.arrayToString(website.data),
- website.uri.spec, true));
- Assert.ok(migrator.exists, "The migrator has to exist");
- uris.push(website.uri);
- hashes.push(website.hash);
-
- migrator._migrateURIs(uris);
- logins = Services.logins.getAllLogins({});
- // check that the number of logins in the password manager has increased as expected which means
- // that all the values for the current website were imported
- loginCount += website.logins.length;
- Assert.equal(logins.length, loginCount,
- "The number of logins has increased after the migration");
- // NB: because telemetry records any login data passed to the login manager, it
- // also gets told about logins that are duplicates or invalid (for one reason
- // or another) and so its counts might exceed those of the login manager itself.
- Assert.greaterOrEqual(MigrationUtils._importQuantities.logins, loginCount,
- "Telemetry quantities equal or exceed the actual import.");
- // Reset - this normally happens at the start of a new migration, but we're calling
- // the migrator directly so can't rely on that:
- MigrationUtils._importQuantities.logins = 0;
-
- let startIndex = loginCount - website.logins.length;
- // compares the imported password manager logins with their expected logins
- for (let i = 0; i < website.logins.length; i++) {
- checkLoginsAreEqual(logins[startIndex + i], website.logins[i],
- " " + current + " - " + i + " ");
- }
- }
-});
diff --git a/browser/components/migration/tests/unit/test_IE_bookmarks.js b/browser/components/migration/tests/unit/test_IE_bookmarks.js
deleted file mode 100644
index a166c0502..000000000
--- a/browser/components/migration/tests/unit/test_IE_bookmarks.js
+++ /dev/null
@@ -1,44 +0,0 @@
-"use strict";
-
-add_task(function* () {
- let migrator = MigrationUtils.getMigrator("ie");
- // Sanity check for the source.
- Assert.ok(migrator.sourceExists);
-
- // Wait for the imported bookmarks. Check that "From Internet Explorer"
- // folders are created in the menu and on the toolbar.
- let source = MigrationUtils.getLocalizedString("sourceNameIE");
- let label = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]);
-
- let expectedParents = [ PlacesUtils.bookmarksMenuFolderId,
- PlacesUtils.toolbarFolderId ];
-
- let itemCount = 0;
- let bmObserver = {
- onItemAdded(aItemId, aParentId, aIndex, aItemType, aURI, aTitle) {
- if (aTitle != label) {
- itemCount++;
- }
- if (expectedParents.length > 0 && aTitle == label) {
- let index = expectedParents.indexOf(aParentId);
- Assert.notEqual(index, -1);
- expectedParents.splice(index, 1);
- }
- },
- onBeginUpdateBatch() {},
- onEndUpdateBatch() {},
- onItemRemoved() {},
- onItemChanged() {},
- onItemVisited() {},
- onItemMoved() {},
- };
- PlacesUtils.bookmarks.addObserver(bmObserver, false);
-
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.BOOKMARKS);
- PlacesUtils.bookmarks.removeObserver(bmObserver);
- Assert.equal(MigrationUtils._importQuantities.bookmarks, itemCount,
- "Ensure telemetry matches actual number of imported items.");
-
- // Check the bookmarks have been imported to all the expected parents.
- Assert.equal(expectedParents.length, 0, "Got all the expected parents");
-});
diff --git a/browser/components/migration/tests/unit/test_IE_cookies.js b/browser/components/migration/tests/unit/test_IE_cookies.js
deleted file mode 100644
index 37a7462f2..000000000
--- a/browser/components/migration/tests/unit/test_IE_cookies.js
+++ /dev/null
@@ -1,111 +0,0 @@
-"use strict";
-
-XPCOMUtils.defineLazyModuleGetter(this, "ctypes",
- "resource://gre/modules/ctypes.jsm");
-
-add_task(function* () {
- let migrator = MigrationUtils.getMigrator("ie");
- // Sanity check for the source.
- Assert.ok(migrator.sourceExists);
-
- const BOOL = ctypes.bool;
- const LPCTSTR = ctypes.char16_t.ptr;
- const DWORD = ctypes.uint32_t;
- const LPDWORD = DWORD.ptr;
-
- let wininet = ctypes.open("Wininet");
-
- /*
- BOOL InternetSetCookieW(
- _In_ LPCTSTR lpszUrl,
- _In_ LPCTSTR lpszCookieName,
- _In_ LPCTSTR lpszCookieData
- );
- */
- let setIECookie = wininet.declare("InternetSetCookieW",
- ctypes.default_abi,
- BOOL,
- LPCTSTR,
- LPCTSTR,
- LPCTSTR);
-
- /*
- BOOL InternetGetCookieW(
- _In_ LPCTSTR lpszUrl,
- _In_ LPCTSTR lpszCookieName,
- _Out_ LPCTSTR lpszCookieData,
- _Inout_ LPDWORD lpdwSize
- );
- */
- let getIECookie = wininet.declare("InternetGetCookieW",
- ctypes.default_abi,
- BOOL,
- LPCTSTR,
- LPCTSTR,
- LPCTSTR,
- LPDWORD);
-
- // We need to randomize the cookie to avoid clashing with other cookies
- // that might have been set by previous tests and not properly cleared.
- let date = (new Date()).getDate();
- const COOKIE = {
- get host() {
- return new URL(this.href).host;
- },
- href: `http://mycookietest.${Math.random()}.com`,
- name: "testcookie",
- value: "testvalue",
- expiry: new Date(new Date().setDate(date + 2))
- };
- let data = ctypes.char16_t.array()(256);
- let sizeRef = DWORD(256).address();
-
- do_register_cleanup(() => {
- // Remove the cookie.
- try {
- let expired = new Date(new Date().setDate(date - 2));
- let rv = setIECookie(COOKIE.href, COOKIE.name,
- `; expires=${expired.toUTCString()}`);
- Assert.ok(rv, "Expired the IE cookie");
- Assert.ok(!getIECookie(COOKIE.href, COOKIE.name, data, sizeRef),
- "The cookie has been properly removed");
- } catch (ex) {}
-
- // Close the library.
- try {
- wininet.close();
- } catch (ex) {}
- });
-
- // Create the persistent cookie in IE.
- let value = `${COOKIE.value}; expires=${COOKIE.expiry.toUTCString()}`;
- let rv = setIECookie(COOKIE.href, COOKIE.name, value);
- Assert.ok(rv, "Added a persistent IE cookie: " + value);
-
- // Sanity check the cookie has been created.
- Assert.ok(getIECookie(COOKIE.href, COOKIE.name, data, sizeRef),
- "Found the added persistent IE cookie");
- do_print("Found cookie: " + data.readString());
- Assert.equal(data.readString(), `${COOKIE.name}=${COOKIE.value}`,
- "Found the expected cookie");
-
- // Sanity check that there are no cookies.
- Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0,
- "There are no cookies initially");
-
- // Migrate cookies.
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.COOKIES);
-
- Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 1,
- "Migrated the expected number of cookies");
-
- // Now check the cookie details.
- let enumerator = Services.cookies.getCookiesFromHost(COOKIE.host, {});
- Assert.ok(enumerator.hasMoreElements());
- let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
-
- Assert.equal(foundCookie.name, COOKIE.name);
- Assert.equal(foundCookie.value, COOKIE.value);
- Assert.equal(foundCookie.host, "." + COOKIE.host);
- Assert.equal(foundCookie.expiry, Math.floor(COOKIE.expiry / 1000));
-});
diff --git a/browser/components/migration/tests/unit/test_Safari_bookmarks.js b/browser/components/migration/tests/unit/test_Safari_bookmarks.js
deleted file mode 100644
index edc32dc72..000000000
--- a/browser/components/migration/tests/unit/test_Safari_bookmarks.js
+++ /dev/null
@@ -1,46 +0,0 @@
-"use strict";
-
-add_task(function* () {
- registerFakePath("ULibDir", do_get_file("Library/"));
-
- let migrator = MigrationUtils.getMigrator("safari");
- // Sanity check for the source.
- Assert.ok(migrator.sourceExists);
-
- // Wait for the imported bookmarks. Check that "From Safari"
- // folders are created on the toolbar.
- let source = MigrationUtils.getLocalizedString("sourceNameSafari");
- let label = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]);
-
- let expectedParents = [ PlacesUtils.toolbarFolderId ];
- let itemCount = 0;
-
- let bmObserver = {
- onItemAdded(aItemId, aParentId, aIndex, aItemType, aURI, aTitle) {
- if (aTitle != label) {
- itemCount++;
- }
- if (expectedParents.length > 0 && aTitle == label) {
- let index = expectedParents.indexOf(aParentId);
- Assert.ok(index != -1, "Found expected parent");
- expectedParents.splice(index, 1);
- }
- },
- onBeginUpdateBatch() {},
- onEndUpdateBatch() {},
- onItemRemoved() {},
- onItemChanged() {},
- onItemVisited() {},
- onItemMoved() {},
- };
- PlacesUtils.bookmarks.addObserver(bmObserver, false);
-
- yield promiseMigration(migrator, MigrationUtils.resourceTypes.BOOKMARKS);
- PlacesUtils.bookmarks.removeObserver(bmObserver);
-
- // Check the bookmarks have been imported to all the expected parents.
- Assert.ok(!expectedParents.length, "No more expected parents");
- Assert.equal(itemCount, 13, "Should import all 13 items.");
- // Check that the telemetry matches:
- Assert.equal(MigrationUtils._importQuantities.bookmarks, itemCount, "Telemetry reporting correct.");
-});
diff --git a/browser/components/migration/tests/unit/test_automigration.js b/browser/components/migration/tests/unit/test_automigration.js
deleted file mode 100644
index bc9076a6c..000000000
--- a/browser/components/migration/tests/unit/test_automigration.js
+++ /dev/null
@@ -1,695 +0,0 @@
-"use strict";
-
-let AutoMigrateBackstage = Cu.import("resource:///modules/AutoMigrate.jsm"); /* globals AutoMigrate */
-
-let gShimmedMigratorKeyPicker = null;
-let gShimmedMigrator = null;
-
-const kUsecPerMin = 60 * 1000000;
-
-// This is really a proxy on MigrationUtils, but if we specify that directly,
-// we get in trouble because the object itself is frozen, and Proxies can't
-// return a different value to an object when directly proxying a frozen
-// object.
-AutoMigrateBackstage.MigrationUtils = new Proxy({}, {
- get(target, name) {
- if (name == "getMigratorKeyForDefaultBrowser" && gShimmedMigratorKeyPicker) {
- return gShimmedMigratorKeyPicker;
- }
- if (name == "getMigrator" && gShimmedMigrator) {
- return function() { return gShimmedMigrator };
- }
- return MigrationUtils[name];
- },
-});
-
-do_register_cleanup(function() {
- AutoMigrateBackstage.MigrationUtils = MigrationUtils;
-});
-
-// This should be replaced by using History.fetch with a fetchVisits option,
-// once that becomes available
-function* visitsForURL(url)
-{
- let visitCount = 0;
- let db = yield PlacesUtils.promiseDBConnection();
- visitCount = yield db.execute(
- `SELECT count(*) FROM moz_historyvisits v
- JOIN moz_places h ON h.id = v.place_id
- WHERE url_hash = hash(:url) AND url = :url`,
- {url});
- visitCount = visitCount[0].getInt64(0);
- return visitCount;
-}
-
-
-/**
- * Test automatically picking a browser to migrate from
- */
-add_task(function* checkMigratorPicking() {
- Assert.throws(() => AutoMigrate.pickMigrator("firefox"),
- /Can't automatically migrate from Firefox/,
- "Should throw when explicitly picking Firefox.");
-
- Assert.throws(() => AutoMigrate.pickMigrator("gobbledygook"),
- /migrator object is not available/,
- "Should throw when passing unknown migrator key");
- gShimmedMigratorKeyPicker = function() {
- return "firefox";
- };
- Assert.throws(() => AutoMigrate.pickMigrator(),
- /Can't automatically migrate from Firefox/,
- "Should throw when implicitly picking Firefox.");
- gShimmedMigratorKeyPicker = function() {
- return "gobbledygook";
- };
- Assert.throws(() => AutoMigrate.pickMigrator(),
- /migrator object is not available/,
- "Should throw when an unknown migrator is the default");
- gShimmedMigratorKeyPicker = function() {
- return "";
- };
- Assert.throws(() => AutoMigrate.pickMigrator(),
- /Could not determine default browser key/,
- "Should throw when an unknown migrator is the default");
-});
-
-
-/**
- * Test automatically picking a profile to migrate from
- */
-add_task(function* checkProfilePicking() {
- let fakeMigrator = {sourceProfiles: [{id: "a"}, {id: "b"}]};
- let profB = fakeMigrator.sourceProfiles[1];
- Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator),
- /Don't know how to pick a profile when more/,
- "Should throw when there are multiple profiles.");
- Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator, "c"),
- /Profile specified was not found/,
- "Should throw when the profile supplied doesn't exist.");
- let profileToMigrate = AutoMigrate.pickProfile(fakeMigrator, "b");
- Assert.equal(profileToMigrate, profB, "Should return profile supplied");
-
- fakeMigrator.sourceProfiles = null;
- Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator, "c"),
- /Profile specified but only a default profile found./,
- "Should throw when the profile supplied doesn't exist.");
- profileToMigrate = AutoMigrate.pickProfile(fakeMigrator);
- Assert.equal(profileToMigrate, null, "Should return default profile when that's the only one.");
-
- fakeMigrator.sourceProfiles = [];
- Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator),
- /No profile data found/,
- "Should throw when no profile data is present.");
-
- fakeMigrator.sourceProfiles = [{id: "a"}];
- let profA = fakeMigrator.sourceProfiles[0];
- profileToMigrate = AutoMigrate.pickProfile(fakeMigrator);
- Assert.equal(profileToMigrate, profA, "Should return the only profile if only one is present.");
-});
-
-/**
- * Test the complete automatic process including browser and profile selection,
- * and actual migration (which implies startup)
- */
-add_task(function* checkIntegration() {
- gShimmedMigrator = {
- get sourceProfiles() {
- do_print("Read sourceProfiles");
- return null;
- },
- getMigrateData(profileToMigrate) {
- this._getMigrateDataArgs = profileToMigrate;
- return Ci.nsIBrowserProfileMigrator.BOOKMARKS;
- },
- migrate(types, startup, profileToMigrate) {
- this._migrateArgs = [types, startup, profileToMigrate];
- },
- };
- gShimmedMigratorKeyPicker = function() {
- return "gobbledygook";
- };
- AutoMigrate.migrate("startup");
- Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null,
- "getMigrateData called with 'null' as a profile");
-
- let {BOOKMARKS, HISTORY, PASSWORDS} = Ci.nsIBrowserProfileMigrator;
- let expectedTypes = BOOKMARKS | HISTORY | PASSWORDS;
- Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null],
- "migrate called with 'null' as a profile");
-});
-
-/**
- * Test the undo preconditions and a no-op undo in the automigrator.
- */
-add_task(function* checkUndoPreconditions() {
- let shouldAddData = false;
- gShimmedMigrator = {
- get sourceProfiles() {
- do_print("Read sourceProfiles");
- return null;
- },
- getMigrateData(profileToMigrate) {
- this._getMigrateDataArgs = profileToMigrate;
- return Ci.nsIBrowserProfileMigrator.BOOKMARKS;
- },
- migrate(types, startup, profileToMigrate) {
- this._migrateArgs = [types, startup, profileToMigrate];
- if (shouldAddData) {
- // Insert a login and check that that worked.
- MigrationUtils.insertLoginWrapper({
- hostname: "www.mozilla.org",
- formSubmitURL: "http://www.mozilla.org",
- username: "user",
- password: "pass",
- });
- }
- TestUtils.executeSoon(function() {
- Services.obs.notifyObservers(null, "Migration:Ended", undefined);
- });
- },
- };
-
- gShimmedMigratorKeyPicker = function() {
- return "gobbledygook";
- };
- AutoMigrate.migrate("startup");
- let migrationFinishedPromise = TestUtils.topicObserved("Migration:Ended");
- Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null,
- "getMigrateData called with 'null' as a profile");
-
- let {BOOKMARKS, HISTORY, PASSWORDS} = Ci.nsIBrowserProfileMigrator;
- let expectedTypes = BOOKMARKS | HISTORY | PASSWORDS;
- Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null],
- "migrate called with 'null' as a profile");
-
- yield migrationFinishedPromise;
- Assert.ok(Preferences.has("browser.migrate.automigrate.browser"),
- "Should have set browser pref");
- Assert.ok(!(yield AutoMigrate.canUndo()), "Should not be able to undo migration, as there's no data");
- gShimmedMigrator._migrateArgs = null;
- gShimmedMigrator._getMigrateDataArgs = null;
- Preferences.reset("browser.migrate.automigrate.browser");
- shouldAddData = true;
-
- AutoMigrate.migrate("startup");
- migrationFinishedPromise = TestUtils.topicObserved("Migration:Ended");
- Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null,
- "getMigrateData called with 'null' as a profile");
- Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null],
- "migrate called with 'null' as a profile");
-
- yield migrationFinishedPromise;
- let storedLogins = Services.logins.findLogins({}, "www.mozilla.org",
- "http://www.mozilla.org", null);
- Assert.equal(storedLogins.length, 1, "Should have 1 login");
-
- Assert.ok(Preferences.has("browser.migrate.automigrate.browser"),
- "Should have set browser pref");
- Assert.ok((yield AutoMigrate.canUndo()), "Should be able to undo migration, as now there's data");
-
- yield AutoMigrate.undo();
- Assert.ok(true, "Should be able to finish an undo cycle.");
-
- // Check that the undo removed the passwords:
- storedLogins = Services.logins.findLogins({}, "www.mozilla.org",
- "http://www.mozilla.org", null);
- Assert.equal(storedLogins.length, 0, "Should have no logins");
-});
-
-/**
- * Fake a migration and then try to undo it to verify all data gets removed.
- */
-add_task(function* checkUndoRemoval() {
- MigrationUtils.initializeUndoData();
- Preferences.set("browser.migrate.automigrate.browser", "automationbrowser");
- // Insert a login and check that that worked.
- MigrationUtils.insertLoginWrapper({
- hostname: "www.mozilla.org",
- formSubmitURL: "http://www.mozilla.org",
- username: "user",
- password: "pass",
- });
- let storedLogins = Services.logins.findLogins({}, "www.mozilla.org",
- "http://www.mozilla.org", null);
- Assert.equal(storedLogins.length, 1, "Should have 1 login");
-
- // Insert a bookmark and check that we have exactly 1 bookmark for that URI.
- yield MigrationUtils.insertBookmarkWrapper({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: "http://www.example.org/",
- title: "Some example bookmark",
- });
-
- let bookmark = yield PlacesUtils.bookmarks.fetch({url: "http://www.example.org/"});
- Assert.ok(bookmark, "Should have a bookmark before undo");
- Assert.equal(bookmark.title, "Some example bookmark", "Should have correct bookmark before undo.");
-
- // Insert 2 history visits
- let now_uSec = Date.now() * 1000;
- let visitedURI = Services.io.newURI("http://www.example.com/", null, null);
- let frecencyUpdatePromise = new Promise(resolve => {
- let expectedChanges = 2;
- let observer = {
- onFrecencyChanged: function() {
- if (!--expectedChanges) {
- PlacesUtils.history.removeObserver(observer);
- resolve();
- }
- },
- };
- PlacesUtils.history.addObserver(observer, false);
- });
- yield MigrationUtils.insertVisitsWrapper([{
- uri: visitedURI,
- visits: [
- {
- transitionType: PlacesUtils.history.TRANSITION_LINK,
- visitDate: now_uSec,
- },
- {
- transitionType: PlacesUtils.history.TRANSITION_LINK,
- visitDate: now_uSec - 100 * kUsecPerMin,
- },
- ]
- }]);
- yield frecencyUpdatePromise;
-
- // Verify that both visits get reported.
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- let query = PlacesUtils.history.getNewQuery();
- query.uri = visitedURI;
- let visits = PlacesUtils.history.executeQuery(query, opts);
- visits.root.containerOpen = true;
- Assert.equal(visits.root.childCount, 2, "Should have 2 visits");
- // Clean up:
- visits.root.containerOpen = false;
-
- yield AutoMigrate.saveUndoState();
-
- // Verify that we can undo, then undo:
- Assert.ok(AutoMigrate.canUndo(), "Should be possible to undo migration");
- yield AutoMigrate.undo();
-
- let histograms = [
- "FX_STARTUP_MIGRATION_UNDO_BOOKMARKS_ERRORCOUNT",
- "FX_STARTUP_MIGRATION_UNDO_LOGINS_ERRORCOUNT",
- "FX_STARTUP_MIGRATION_UNDO_VISITS_ERRORCOUNT",
- ];
- for (let histogramId of histograms) {
- let keyedHistogram = Services.telemetry.getKeyedHistogramById(histogramId);
- let histogramData = keyedHistogram.snapshot().automationbrowser;
- Assert.equal(histogramData.sum, 0, `Should have reported 0 errors to ${histogramId}.`);
- Assert.greaterOrEqual(histogramData.counts[0], 1, `Should have reported value of 0 one time to ${histogramId}.`);
- }
- histograms = [
- "FX_STARTUP_MIGRATION_UNDO_BOOKMARKS_MS",
- "FX_STARTUP_MIGRATION_UNDO_LOGINS_MS",
- "FX_STARTUP_MIGRATION_UNDO_VISITS_MS",
- "FX_STARTUP_MIGRATION_UNDO_TOTAL_MS",
- ];
- for (let histogramId of histograms) {
- Assert.greater(Services.telemetry.getKeyedHistogramById(histogramId).snapshot().automationbrowser.sum, 0,
- `Should have reported non-zero time spent using undo for ${histogramId}`);
- }
-
- // Check that the undo removed the history visits:
- visits = PlacesUtils.history.executeQuery(query, opts);
- visits.root.containerOpen = true;
- Assert.equal(visits.root.childCount, 0, "Should have no more visits");
- visits.root.containerOpen = false;
-
- // Check that the undo removed the bookmarks:
- bookmark = yield PlacesUtils.bookmarks.fetch({url: "http://www.example.org/"});
- Assert.ok(!bookmark, "Should have no bookmarks after undo");
-
- // Check that the undo removed the passwords:
- storedLogins = Services.logins.findLogins({}, "www.mozilla.org",
- "http://www.mozilla.org", null);
- Assert.equal(storedLogins.length, 0, "Should have no logins");
-});
-
-add_task(function* checkUndoBookmarksState() {
- MigrationUtils.initializeUndoData();
- const {TYPE_FOLDER, TYPE_BOOKMARK} = PlacesUtils.bookmarks;
- let title = "Some example bookmark";
- let url = "http://www.example.com";
- let parentGuid = PlacesUtils.bookmarks.toolbarGuid;
- let {guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({
- title, url, parentGuid
- });
- Assert.deepEqual((yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks"),
- [{lastModified, parentGuid, guid, type: TYPE_BOOKMARK}]);
-
- MigrationUtils.initializeUndoData();
- ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({
- title, parentGuid, type: TYPE_FOLDER
- }));
- let folder = {guid, lastModified, parentGuid, type: TYPE_FOLDER};
- let folderGuid = folder.guid;
- ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({
- title, url, parentGuid: folderGuid
- }));
- let kid1 = {guid, lastModified, parentGuid: folderGuid, type: TYPE_BOOKMARK};
- ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({
- title, url, parentGuid: folderGuid
- }));
- let kid2 = {guid, lastModified, parentGuid: folderGuid, type: TYPE_BOOKMARK};
-
- let bookmarksUndo = (yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks");
- Assert.equal(bookmarksUndo.length, 3);
- // We expect that the last modified time from first kid #1 and then kid #2
- // has been propagated to the folder:
- folder.lastModified = kid2.lastModified;
- // Not just using deepEqual on the entire array (which should work) because
- // the failure messages get truncated by xpcshell which is unhelpful.
- Assert.deepEqual(bookmarksUndo[0], folder);
- Assert.deepEqual(bookmarksUndo[1], kid1);
- Assert.deepEqual(bookmarksUndo[2], kid2);
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* testBookmarkRemovalByUndo() {
- const {TYPE_FOLDER} = PlacesUtils.bookmarks;
- MigrationUtils.initializeUndoData();
- let title = "Some example bookmark";
- let url = "http://www.mymagicaluniqueurl.com";
- let parentGuid = PlacesUtils.bookmarks.toolbarGuid;
- let {guid} = yield MigrationUtils.insertBookmarkWrapper({
- title: "Some folder", parentGuid, type: TYPE_FOLDER
- });
- let folderGuid = guid;
- let itemsToRemove = [];
- ({guid} = yield MigrationUtils.insertBookmarkWrapper({
- title: "Inner folder", parentGuid: folderGuid, type: TYPE_FOLDER
- }));
- let innerFolderGuid = guid;
- itemsToRemove.push(innerFolderGuid);
-
- ({guid} = yield MigrationUtils.insertBookmarkWrapper({
- title: "Inner inner folder", parentGuid: innerFolderGuid, type: TYPE_FOLDER
- }));
- itemsToRemove.push(guid);
-
- ({guid} = yield MigrationUtils.insertBookmarkWrapper({
- title: "Inner nested item", url: "http://inner-nested-example.com", parentGuid: guid
- }));
- itemsToRemove.push(guid);
-
- ({guid} = yield MigrationUtils.insertBookmarkWrapper({
- title, url, parentGuid: folderGuid
- }));
- itemsToRemove.push(guid);
-
- for (let toBeRemovedGuid of itemsToRemove) {
- let dbResultForGuid = yield PlacesUtils.bookmarks.fetch(toBeRemovedGuid);
- Assert.ok(dbResultForGuid, "Should be able to find items that will be removed.");
- }
- let bookmarkUndoState = (yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks");
- // Now insert a separate item into this folder, not related to the migration.
- let newItem = yield PlacesUtils.bookmarks.insert(
- {title: "Not imported", parentGuid: folderGuid, url: "http://www.example.com"}
- );
-
- yield AutoMigrate._removeUnchangedBookmarks(bookmarkUndoState);
- Assert.ok(true, "Successfully removed imported items.");
-
- let itemFromDB = yield PlacesUtils.bookmarks.fetch(newItem.guid);
- Assert.ok(itemFromDB, "Item we inserted outside of migration is still there.");
- itemFromDB = yield PlacesUtils.bookmarks.fetch(folderGuid);
- Assert.ok(itemFromDB, "Folder we inserted in migration is still there because of new kids.");
- for (let removedGuid of itemsToRemove) {
- let dbResultForGuid = yield PlacesUtils.bookmarks.fetch(removedGuid);
- let dbgStr = dbResultForGuid && dbResultForGuid.title;
- Assert.equal(null, dbResultForGuid, "Should not be able to find items that should have been removed, but found " + dbgStr);
- }
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* checkUndoLoginsState() {
- MigrationUtils.initializeUndoData();
- MigrationUtils.insertLoginWrapper({
- username: "foo",
- password: "bar",
- hostname: "https://example.com",
- formSubmitURL: "https://example.com/",
- timeCreated: new Date(),
- });
- let storedLogins = Services.logins.findLogins({}, "https://example.com", "", "");
- let storedLogin = storedLogins[0];
- storedLogin.QueryInterface(Ci.nsILoginMetaInfo);
- let {guid, timePasswordChanged} = storedLogin;
- let undoLoginData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("logins");
- Assert.deepEqual([{guid, timePasswordChanged}], undoLoginData);
- Services.logins.removeAllLogins();
-});
-
-add_task(function* testLoginsRemovalByUndo() {
- MigrationUtils.initializeUndoData();
- MigrationUtils.insertLoginWrapper({
- username: "foo",
- password: "bar",
- hostname: "https://example.com",
- formSubmitURL: "https://example.com/",
- timeCreated: new Date(),
- });
- MigrationUtils.insertLoginWrapper({
- username: "foo",
- password: "bar",
- hostname: "https://example.org",
- formSubmitURL: "https://example.org/",
- timeCreated: new Date(new Date().getTime() - 10000),
- });
- // This should update the existing login
- LoginHelper.maybeImportLogin({
- username: "foo",
- password: "bazzy",
- hostname: "https://example.org",
- formSubmitURL: "https://example.org/",
- timePasswordChanged: new Date(),
- });
- Assert.equal(1, LoginHelper.searchLoginsWithObject({hostname: "https://example.org", formSubmitURL: "https://example.org/"}).length,
- "Should be only 1 login for example.org (that was updated)");
- let undoLoginData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("logins");
-
- yield AutoMigrate._removeUnchangedLogins(undoLoginData);
- Assert.equal(0, LoginHelper.searchLoginsWithObject({hostname: "https://example.com", formSubmitURL: "https://example.com/"}).length,
- "unchanged example.com entry should have been removed.");
- Assert.equal(1, LoginHelper.searchLoginsWithObject({hostname: "https://example.org", formSubmitURL: "https://example.org/"}).length,
- "changed example.org entry should have persisted.");
- Services.logins.removeAllLogins();
-});
-
-add_task(function* checkUndoVisitsState() {
- MigrationUtils.initializeUndoData();
- yield MigrationUtils.insertVisitsWrapper([{
- uri: NetUtil.newURI("http://www.example.com/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2015-07-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-09-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-08-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }, {
- uri: NetUtil.newURI("http://www.example.org/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2016-04-03").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-08-03").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }, {
- uri: NetUtil.newURI("http://www.example.com/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2015-10-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }]);
- let undoVisitData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("visits");
- Assert.deepEqual(Array.from(undoVisitData.map(v => v.url)).sort(),
- ["http://www.example.com/", "http://www.example.org/"]);
- Assert.deepEqual(undoVisitData.find(v => v.url == "http://www.example.com/"), {
- url: "http://www.example.com/",
- visitCount: 4,
- first: new Date("2015-07-10").getTime() * 1000,
- last: new Date("2015-10-10").getTime() * 1000,
- });
- Assert.deepEqual(undoVisitData.find(v => v.url == "http://www.example.org/"), {
- url: "http://www.example.org/",
- visitCount: 2,
- first: new Date("2015-08-03").getTime() * 1000,
- last: new Date("2016-04-03").getTime() * 1000,
- });
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* checkUndoVisitsState() {
- MigrationUtils.initializeUndoData();
- yield MigrationUtils.insertVisitsWrapper([{
- uri: NetUtil.newURI("http://www.example.com/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2015-07-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-09-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-08-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }, {
- uri: NetUtil.newURI("http://www.example.org/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2016-04-03").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }, {
- visitDate: new Date("2015-08-03").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }, {
- uri: NetUtil.newURI("http://www.example.com/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2015-10-10").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }, {
- uri: NetUtil.newURI("http://www.mozilla.org/"),
- title: "Example",
- visits: [{
- visitDate: new Date("2015-01-01").getTime() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK,
- }],
- }]);
-
- // We have to wait until frecency updates have been handled in order
- // to accurately determine whether we're doing the right thing.
- let frecencyUpdatesHandled = new Promise(resolve => {
- PlacesUtils.history.addObserver({
- onFrecencyChanged(aURI) {
- if (aURI.spec == "http://www.unrelated.org/") {
- PlacesUtils.history.removeObserver(this);
- resolve();
- }
- }
- }, false);
- });
- yield PlacesUtils.history.insertMany([{
- url: "http://www.example.com/",
- title: "Example",
- visits: [{
- date: new Date("2015-08-16"),
- }],
- }, {
- url: "http://www.example.org/",
- title: "Example",
- visits: [{
- date: new Date("2016-01-03"),
- }, {
- date: new Date("2015-05-03"),
- }],
- }, {
- url: "http://www.unrelated.org/",
- title: "Unrelated",
- visits: [{
- date: new Date("2015-09-01"),
- }],
- }]);
- yield frecencyUpdatesHandled;
- let undoVisitData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("visits");
-
- let frecencyChangesExpected = new Map([
- ["http://www.example.com/", PromiseUtils.defer()],
- ["http://www.example.org/", PromiseUtils.defer()]
- ]);
- let uriDeletedExpected = new Map([
- ["http://www.mozilla.org/", PromiseUtils.defer()],
- ]);
- let wrongMethodDeferred = PromiseUtils.defer();
- let observer = {
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function(uri) {
- wrongMethodDeferred.reject(new Error("Unexpected call to onVisit " + uri.spec));
- },
- onTitleChanged: function(uri) {
- wrongMethodDeferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec));
- },
- onClearHistory: function() {
- wrongMethodDeferred.reject("Unexpected call to onClearHistory");
- },
- onPageChanged: function(uri) {
- wrongMethodDeferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec));
- },
- onFrecencyChanged: function(aURI) {
- do_print("frecency change");
- Assert.ok(frecencyChangesExpected.has(aURI.spec),
- "Should be expecting frecency change for " + aURI.spec);
- frecencyChangesExpected.get(aURI.spec).resolve();
- },
- onManyFrecenciesChanged: function() {
- do_print("Many frecencies changed");
- wrongMethodDeferred.reject(new Error("This test can't deal with onManyFrecenciesChanged to be called"));
- },
- onDeleteURI: function(aURI) {
- do_print("delete uri");
- Assert.ok(uriDeletedExpected.has(aURI.spec),
- "Should be expecting uri deletion for " + aURI.spec);
- uriDeletedExpected.get(aURI.spec).resolve();
- },
- };
- PlacesUtils.history.addObserver(observer, false);
-
- yield AutoMigrate._removeSomeVisits(undoVisitData);
- PlacesUtils.history.removeObserver(observer);
- yield Promise.all(uriDeletedExpected.values());
- yield Promise.all(frecencyChangesExpected.values());
-
- Assert.equal(yield visitsForURL("http://www.example.com/"), 1,
- "1 example.com visit (out of 5) should have persisted despite being within the range, due to limiting");
- Assert.equal(yield visitsForURL("http://www.mozilla.org/"), 0,
- "0 mozilla.org visits should have persisted (out of 1).");
- Assert.equal(yield visitsForURL("http://www.example.org/"), 2,
- "2 example.org visits should have persisted (out of 4).");
- Assert.equal(yield visitsForURL("http://www.unrelated.org/"), 1,
- "1 unrelated.org visits should have persisted as it's not involved in the import.");
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* checkHistoryRemovalCompletion() {
- AutoMigrate._errorMap = {bookmarks: 0, visits: 0, logins: 0};
- yield AutoMigrate._removeSomeVisits([{url: "http://www.example.com/", limit: -1}]);
- ok(true, "Removing visits should complete even if removing some visits failed.");
- Assert.equal(AutoMigrate._errorMap.visits, 1, "Should have logged the error for visits.");
-
- // Unfortunately there's not a reliable way to make removing bookmarks be
- // unhappy unless the DB is messed up (e.g. contains children but has
- // parents removed already).
- yield AutoMigrate._removeUnchangedBookmarks([
- {guid: PlacesUtils.bookmarks, lastModified: new Date(0), parentGuid: 0},
- {guid: "gobbledygook", lastModified: new Date(0), parentGuid: 0},
- ]);
- ok(true, "Removing bookmarks should complete even if some items are gone or bogus.");
- Assert.equal(AutoMigrate._errorMap.bookmarks, 0,
- "Should have ignored removing non-existing (or builtin) bookmark.");
-
-
- yield AutoMigrate._removeUnchangedLogins([
- {guid: "gobbledygook", timePasswordChanged: new Date(0)},
- ]);
- ok(true, "Removing logins should complete even if logins don't exist.");
- Assert.equal(AutoMigrate._errorMap.logins, 0,
- "Should have ignored removing non-existing logins.");
-});
diff --git a/browser/components/migration/tests/unit/test_fx_telemetry.js b/browser/components/migration/tests/unit/test_fx_telemetry.js
deleted file mode 100644
index a276f52f8..000000000
--- a/browser/components/migration/tests/unit/test_fx_telemetry.js
+++ /dev/null
@@ -1,288 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* globals do_get_tempdir */
-
-"use strict";
-
-function run_test() {
- run_next_test();
-}
-
-function readFile(file) {
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(file, -1, -1, Ci.nsIFileInputStream.CLOSE_ON_EOF);
-
- let sis = Cc["@mozilla.org/scriptableinputstream;1"]
- .createInstance(Ci.nsIScriptableInputStream);
- sis.init(stream);
- let contents = sis.read(file.fileSize);
- sis.close();
- return contents;
-}
-
-function checkDirectoryContains(dir, files) {
- print("checking " + dir.path + " - should contain " + Object.keys(files));
- let seen = new Set();
- let enumerator = dir.directoryEntries;
- while (enumerator.hasMoreElements()) {
- let file = enumerator.getNext().QueryInterface(Ci.nsIFile);
- print("found file: " + file.path);
- Assert.ok(file.leafName in files, file.leafName + " exists, but shouldn't");
-
- let expectedContents = files[file.leafName];
- if (typeof expectedContents != "string") {
- // it's a subdir - recurse!
- Assert.ok(file.isDirectory(), "should be a subdir");
- let newDir = dir.clone();
- newDir.append(file.leafName);
- checkDirectoryContains(newDir, expectedContents);
- } else {
- Assert.ok(!file.isDirectory(), "should be a regular file");
- let contents = readFile(file);
- Assert.equal(contents, expectedContents);
- }
- seen.add(file.leafName);
- }
- let missing = [];
- for (let x in files) {
- if (!seen.has(x)) {
- missing.push(x);
- }
- }
- Assert.deepEqual(missing, [], "no missing files in " + dir.path);
-}
-
-function getTestDirs() {
- // we make a directory structure in a temp dir which mirrors what we are
- // testing.
- let tempDir = do_get_tempdir();
- let srcDir = tempDir.clone();
- srcDir.append("test_source_dir");
- srcDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- let targetDir = tempDir.clone();
- targetDir.append("test_target_dir");
- targetDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- // no need to cleanup these dirs - the xpcshell harness will do it for us.
- return [srcDir, targetDir];
-}
-
-function writeToFile(dir, leafName, contents) {
- let file = dir.clone();
- file.append(leafName);
-
- let outputStream = FileUtils.openFileOutputStream(file);
- outputStream.write(contents, contents.length);
- outputStream.close();
-}
-
-function createSubDir(dir, subDirName) {
- let subDir = dir.clone();
- subDir.append(subDirName);
- subDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- return subDir;
-}
-
-function promiseMigrator(name, srcDir, targetDir) {
- let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=firefox"]
- .createInstance(Ci.nsISupports)
- .wrappedJSObject;
- let migrators = migrator._getResourcesInternal(srcDir, targetDir);
- for (let m of migrators) {
- if (m.name == name) {
- return new Promise(resolve => m.migrate(resolve));
- }
- }
- throw new Error("failed to find the " + name + " migrator");
-}
-
-function promiseTelemetryMigrator(srcDir, targetDir) {
- return promiseMigrator("telemetry", srcDir, targetDir);
-}
-
-add_task(function* test_empty() {
- let [srcDir, targetDir] = getTestDirs();
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true with empty directories");
- // check both are empty
- checkDirectoryContains(srcDir, {});
- checkDirectoryContains(targetDir, {});
-});
-
-add_task(function* test_migrate_files() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Set up datareporting files, some to copy, some not.
- let stateContent = JSON.stringify({
- clientId: "68d5474e-19dc-45c1-8e9a-81fca592707c",
- });
- let sessionStateContent = "foobar 5432";
- let subDir = createSubDir(srcDir, "datareporting");
- writeToFile(subDir, "state.json", stateContent);
- writeToFile(subDir, "session-state.json", sessionStateContent);
- writeToFile(subDir, "other.file", "do not copy");
-
- let archived = createSubDir(subDir, "archived");
- writeToFile(archived, "other.file", "do not copy");
-
- // Set up FHR files, they should not be copied.
- writeToFile(srcDir, "healthreport.sqlite", "do not copy");
- writeToFile(srcDir, "healthreport.sqlite-wal", "do not copy");
- subDir = createSubDir(srcDir, "healthreport");
- writeToFile(subDir, "state.json", "do not copy");
- writeToFile(subDir, "other.file", "do not copy");
-
- // Perform migration.
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true with important telemetry files copied");
-
- checkDirectoryContains(targetDir, {
- "datareporting": {
- "state.json": stateContent,
- "session-state.json": sessionStateContent,
- },
- });
-});
-
-add_task(function* test_fallback_fhr_state() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Test that we fall back to migrating FHR state if the datareporting
- // state file does not exist.
- let stateContent = JSON.stringify({
- clientId: "68d5474e-19dc-45c1-8e9a-81fca592707c",
- });
- let subDir = createSubDir(srcDir, "healthreport");
- writeToFile(subDir, "state.json", stateContent);
-
- // Perform migration.
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- checkDirectoryContains(targetDir, {
- "healthreport": {
- "state.json": stateContent,
- },
- });
-});
-
-
-add_task(function* test_datareporting_not_dir() {
- let [srcDir, targetDir] = getTestDirs();
-
- writeToFile(srcDir, "datareporting", "I'm a file but should be a directory");
-
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true even though the directory was a file");
-
- checkDirectoryContains(targetDir, {});
-});
-
-add_task(function* test_datareporting_empty() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Migrate with an empty 'datareporting' subdir.
- createSubDir(srcDir, "datareporting");
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- // We should end up with no migrated files.
- checkDirectoryContains(targetDir, {
- "datareporting": {},
- });
-});
-
-add_task(function* test_healthreport_empty() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Migrate with no 'datareporting' and an empty 'healthreport' subdir.
- createSubDir(srcDir, "healthreport");
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- // We should end up with no migrated files.
- checkDirectoryContains(targetDir, {});
-});
-
-add_task(function* test_datareporting_many() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Create some datareporting files.
- let subDir = createSubDir(srcDir, "datareporting");
- let shouldBeCopied = "should be copied";
- writeToFile(subDir, "state.json", shouldBeCopied);
- writeToFile(subDir, "session-state.json", shouldBeCopied);
- writeToFile(subDir, "something.else", "should not");
- createSubDir(subDir, "emptyDir");
-
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- checkDirectoryContains(targetDir, {
- "datareporting" : {
- "state.json": shouldBeCopied,
- "session-state.json": shouldBeCopied,
- }
- });
-});
-
-add_task(function* test_no_session_state() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Check that migration still works properly if we only have state.json.
- let subDir = createSubDir(srcDir, "datareporting");
- let stateContent = "abcd984";
- writeToFile(subDir, "state.json", stateContent);
-
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- checkDirectoryContains(targetDir, {
- "datareporting" : {
- "state.json": stateContent,
- }
- });
-});
-
-add_task(function* test_no_state() {
- let [srcDir, targetDir] = getTestDirs();
-
- // Check that migration still works properly if we only have session-state.json.
- let subDir = createSubDir(srcDir, "datareporting");
- let sessionStateContent = "abcd512";
- writeToFile(subDir, "session-state.json", sessionStateContent);
-
- let ok = yield promiseTelemetryMigrator(srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
-
- checkDirectoryContains(targetDir, {
- "datareporting" : {
- "session-state.json": sessionStateContent,
- }
- });
-});
-
-add_task(function* test_times_migration() {
- let [srcDir, targetDir] = getTestDirs();
-
- // create a times.json in the source directory.
- let contents = JSON.stringify({created: 1234});
- writeToFile(srcDir, "times.json", contents);
-
- let earliest = Date.now();
- let ok = yield promiseMigrator("times", srcDir, targetDir);
- Assert.ok(ok, "callback should have been true");
- let latest = Date.now();
-
- let timesFile = targetDir.clone();
- timesFile.append("times.json");
-
- let raw = readFile(timesFile);
- let times = JSON.parse(raw);
- Assert.ok(times.reset >= earliest && times.reset <= latest);
- // and it should have left the creation time alone.
- Assert.equal(times.created, 1234);
-});
diff --git a/browser/components/migration/tests/unit/xpcshell.ini b/browser/components/migration/tests/unit/xpcshell.ini
deleted file mode 100644
index 1b9f0a5f1..000000000
--- a/browser/components/migration/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,26 +0,0 @@
-[DEFAULT]
-head = head_migration.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files =
- Library/**
- AppData/**
-
-[test_automigration.js]
-[test_Chrome_cookies.js]
-skip-if = os != "mac" # Relies on ULibDir
-[test_Chrome_passwords.js]
-skip-if = os != "win"
-[test_Edge_availability.js]
-[test_Edge_db_migration.js]
-skip-if = os != "win" || os_version == "5.1" || os_version == "5.2" # Relies on post-XP bits of ESEDB
-[test_fx_telemetry.js]
-[test_IE_bookmarks.js]
-skip-if = os != "win"
-[test_IE_cookies.js]
-skip-if = os != "win"
-[test_IE7_passwords.js]
-skip-if = os != "win"
-[test_Safari_bookmarks.js]
-skip-if = os != "mac"
diff --git a/browser/components/newtab/tests/browser/.eslintrc.js b/browser/components/newtab/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/newtab/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/newtab/tests/browser/blue_page.html b/browser/components/newtab/tests/browser/blue_page.html
deleted file mode 100644
index a7f000bfd..000000000
--- a/browser/components/newtab/tests/browser/blue_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
- <meta charset="utf-8">
-</head>
-<body style="background-color: blue">
-</body>
-</html>
diff --git a/browser/components/newtab/tests/browser/browser.ini b/browser/components/newtab/tests/browser/browser.ini
deleted file mode 100644
index fa740be9e..000000000
--- a/browser/components/newtab/tests/browser/browser.ini
+++ /dev/null
@@ -1,16 +0,0 @@
-[DEFAULT]
-support-files =
- blue_page.html
- dummy_page.html
- newtabwebchannel_basic.html
- newtabmessages_places.html
- newtabmessages_prefs.html
- newtabmessages_preview.html
- newtabmessages_search.html
-
-[browser_PreviewProvider.js]
-[browser_remotenewtab_pageloads.js]
-[browser_newtab_overrides.js]
-[browser_newtabmessages.js]
-skip-if = true # Bug 1271177, bug 1262719
-[browser_newtabwebchannel.js]
diff --git a/browser/components/newtab/tests/browser/browser_PreviewProvider.js b/browser/components/newtab/tests/browser/browser_PreviewProvider.js
deleted file mode 100644
index b1e3eda9f..000000000
--- a/browser/components/newtab/tests/browser/browser_PreviewProvider.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* globals XPCOMUtils, Services, PreviewProvider, registerCleanupFunction */
-"use strict";
-
-let Cu = Components.utils;
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PreviewProvider",
- "resource:///modules/PreviewProvider.jsm");
-
-var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled");
-Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false);
-
-registerCleanupFunction(function() {
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeTab(gBrowser.tabs[1]);
- }
- Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref);
-});
-
-const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/blue_page.html";
-
-function pixelsForDataURI(dataURI, options) {
- return new Promise(resolve => {
- if (!options) {
- options = {};
- }
- let {width, height} = options;
- if (!width) {
- width = 100;
- }
- if (!height) {
- height = 100;
- }
-
- let htmlns = "http://www.w3.org/1999/xhtml";
- let img = document.createElementNS(htmlns, "img");
- img.setAttribute("src", dataURI);
-
- img.addEventListener("load", function onLoad() {
- img.removeEventListener("load", onLoad, true);
- let canvas = document.createElementNS(htmlns, "canvas");
- canvas.setAttribute("width", width);
- canvas.setAttribute("height", height);
- let ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0, width, height);
- let result = ctx.getImageData(0, 0, width, height).data;
- resolve(result);
- });
- });
-}
-
-function* chunk_four(listData) {
- let index = 0;
- while (index < listData.length) {
- yield listData.slice(index, index + 5);
- index += 4;
- }
-}
-
-add_task(function* open_page() {
- let dataURI = yield PreviewProvider.getThumbnail(TEST_URL);
- let pixels = yield pixelsForDataURI(dataURI, {width: 10, height: 10});
- let rgbCount = {r: 0, g: 0, b: 0, a: 0};
- for (let [r, g, b, a] of chunk_four(pixels)) {
- if (r === 255) {
- rgbCount.r += 1;
- }
- if (g === 255) {
- rgbCount.g += 1;
- }
- if (b === 255) {
- rgbCount.b += 1;
- }
- if (a === 255) {
- rgbCount.a += 1;
- }
- }
- Assert.equal(`${rgbCount.r},${rgbCount.g},${rgbCount.b},${rgbCount.a}`,
- "0,0,100,100", "there should be 100 blue-only pixels at full opacity");
-});
-
-add_task(function* invalid_url() {
- try {
- yield PreviewProvider.getThumbnail("invalid:URL");
- } catch (err) {
- Assert.ok(true, "URL Failed");
- }
-});
diff --git a/browser/components/newtab/tests/browser/browser_newtab_overrides.js b/browser/components/newtab/tests/browser/browser_newtab_overrides.js
deleted file mode 100644
index eab9092a0..000000000
--- a/browser/components/newtab/tests/browser/browser_newtab_overrides.js
+++ /dev/null
@@ -1,139 +0,0 @@
-/* globals
- XPCOMUtils,
- aboutNewTabService,
- Services,
- ContentTask,
- TestUtils,
- BrowserOpenTab,
- registerCleanupFunction,
- is,
- content
-*/
-
-"use strict";
-
-let Cu = Components.utils;
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
- "@mozilla.org/browser/aboutnewtab-service;1",
- "nsIAboutNewTabService");
-
-registerCleanupFunction(function() {
- Services.prefs.setBoolPref("browser.newtabpage.remote", false);
- aboutNewTabService.resetNewTabURL();
-});
-
-/*
- * Tests that the default newtab page is always returned when one types "about:newtab" in the URL bar,
- * even when overridden.
- */
-add_task(function* redirector_ignores_override() {
- let overrides = [
- "chrome://browser/content/downloads/contentAreaDownloadsView.xul",
- "about:home",
- ];
-
- for (let overrideURL of overrides) {
- let notificationPromise = nextChangeNotificationPromise(overrideURL, `newtab page now points to ${overrideURL}`);
- aboutNewTabService.newTabURL = overrideURL;
-
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "url has been overridden");
-
- let tabOptions = {
- gBrowser,
- url: "about:newtab",
- };
-
- /*
- * Simulate typing "about:newtab" in the url bar.
- *
- * Bug 1240169 - We expect the redirector to lead the user to "about:newtab", the default URL,
- * due to invoking AboutRedirector. A user interacting with the chrome otherwise would lead
- * to the overriding URLs.
- */
- yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) {
- yield ContentTask.spawn(browser, {}, function*() {
- Assert.equal(content.location.href, "about:newtab", "Got right URL");
- Assert.equal(content.document.location.href, "about:newtab", "Got right URL");
- Assert.equal(content.document.nodePrincipal,
- Services.scriptSecurityManager.getSystemPrincipal(),
- "nodePrincipal should match systemPrincipal");
- });
- }); // jshint ignore:line
- }
-});
-
-/*
- * Tests loading an overridden newtab page by simulating opening a newtab page from chrome
- */
-add_task(function* override_loads_in_browser() {
- let overrides = [
- "chrome://browser/content/downloads/contentAreaDownloadsView.xul",
- "about:home",
- " about:home",
- ];
-
- for (let overrideURL of overrides) {
- let notificationPromise = nextChangeNotificationPromise(overrideURL.trim(), `newtab page now points to ${overrideURL}`);
- aboutNewTabService.newTabURL = overrideURL;
-
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "url has been overridden");
-
- // simulate a newtab open as a user would
- BrowserOpenTab(); // jshint ignore:line
-
- let browser = gBrowser.selectedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, {url: overrideURL}, function*(args) {
- Assert.equal(content.location.href, args.url.trim(), "Got right URL");
- Assert.equal(content.document.location.href, args.url.trim(), "Got right URL");
- }); // jshint ignore:line
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
-});
-
-/*
- * Tests edge cases when someone overrides the newtabpage with whitespace
- */
-add_task(function* override_blank_loads_in_browser() {
- let overrides = [
- "",
- " ",
- "\n\t",
- " about:blank",
- ];
-
- for (let overrideURL of overrides) {
- let notificationPromise = nextChangeNotificationPromise("about:blank", "newtab page now points to about:blank");
- aboutNewTabService.newTabURL = overrideURL;
-
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "url has been overridden");
-
- // simulate a newtab open as a user would
- BrowserOpenTab(); // jshint ignore:line
-
- let browser = gBrowser.selectedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, {}, function*() {
- Assert.equal(content.location.href, "about:blank", "Got right URL");
- Assert.equal(content.document.location.href, "about:blank", "Got right URL");
- }); // jshint ignore:line
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
-});
-
-function nextChangeNotificationPromise(aNewURL, testMessage) {
- return TestUtils.topicObserved("newtab-url-changed", function observer(aSubject, aData) { // jshint unused:false
- Assert.equal(aData, aNewURL, testMessage);
- return true;
- }.bind(this));
-}
diff --git a/browser/components/newtab/tests/browser/browser_newtabmessages.js b/browser/components/newtab/tests/browser/browser_newtabmessages.js
deleted file mode 100644
index 319ca1c34..000000000
--- a/browser/components/newtab/tests/browser/browser_newtabmessages.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/* globals Cu, XPCOMUtils, Preferences, is, registerCleanupFunction, NewTabWebChannel,
-PlacesTestUtils, NewTabMessages, ok, Services, PlacesUtils, NetUtil, Task */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel",
- "resource:///modules/NewTabWebChannel.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabMessages",
- "resource:///modules/NewTabMessages.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-let setup = Task.async(function*() {
- Preferences.set("browser.newtabpage.enhanced", true);
- Preferences.set("browser.newtabpage.remote.mode", "test");
- Preferences.set("browser.newtabpage.remote", true);
- NewTabMessages.init();
- yield PlacesTestUtils.clearHistory();
-});
-
-let cleanup = Task.async(function*() {
- NewTabMessages.uninit();
- Preferences.set("browser.newtabpage.remote", false);
- Preferences.set("browser.newtabpage.remote.mode", "production");
-});
-registerCleanupFunction(cleanup);
-
-/*
- * Sanity tests for pref messages
- */
-add_task(function* prefMessages_request() {
- yield setup();
-
- let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_prefs.html";
-
- let tabOptions = {
- gBrowser,
- url: testURL
- };
-
- let prefResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("responseAck", () => {
- ok(true, "a request response has been received");
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab(tabOptions, function*() {
- yield prefResponseAck;
- let prefChangeAck = new Promise(resolve => {
- NewTabWebChannel.once("responseAck", () => {
- ok(true, "a change response has been received");
- resolve();
- });
- });
- Preferences.set("browser.newtabpage.enhanced", false);
- yield prefChangeAck;
- });
- yield cleanup();
-});
-
-/*
- * Sanity tests for preview messages
- */
-add_task(function* previewMessages_request() {
- yield setup();
- var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled");
- Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false);
-
- let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_preview.html";
-
- let tabOptions = {
- gBrowser,
- url: testURL
- };
-
- let previewResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("responseAck", () => {
- ok(true, "a request response has been received");
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab(tabOptions, function*() {
- yield previewResponseAck;
- });
- yield cleanup();
- Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref);
-});
-
-/*
- * Sanity tests for places messages
- */
-add_task(function* placesMessages_request() {
- yield setup();
- let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_places.html";
-
- // url prefix for test history population
- const TEST_URL = "https://mozilla.com/";
- // time when the test starts execution
- const TIME_NOW = (new Date()).getTime();
-
- // utility function to compute past timestamp
- function timeDaysAgo(numDays) {
- return TIME_NOW - (numDays * 24 * 60 * 60 * 1000);
- }
-
- // utility function to make a visit for insertion into places db
- function makeVisit(index, daysAgo, isTyped, domain=TEST_URL) {
- let {
- TRANSITION_TYPED,
- TRANSITION_LINK
- } = PlacesUtils.history;
-
- return {
- uri: NetUtil.newURI(`${domain}${index}`),
- visitDate: timeDaysAgo(daysAgo),
- transition: (isTyped) ? TRANSITION_TYPED : TRANSITION_LINK,
- };
- }
-
- yield PlacesTestUtils.clearHistory();
-
- // all four visits must come from different domains to avoid deduplication
- let visits = [
- makeVisit(0, 0, true, "http://bar.com/"), // frecency 200, today
- makeVisit(1, 0, true, "http://foo.com/"), // frecency 200, today
- makeVisit(2, 2, true, "http://buz.com/"), // frecency 200, 2 days ago
- makeVisit(3, 2, false, "http://aaa.com/"), // frecency 10, 2 days ago, transition
- ];
-
- yield PlacesTestUtils.addVisits(visits);
-
- /** Test Begins **/
-
- let tabOptions = {
- gBrowser,
- url: testURL
- };
-
- let placesResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("numItemsAck", (_, msg) => {
- ok(true, "a request response has been received");
- is(msg.data, visits.length + 1, "received an expected number of history items");
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab(tabOptions, function*() {
- yield placesResponseAck;
- ok(true, "a change response has been received");
- let placesChangeAck = new Promise(resolve => {
- NewTabWebChannel.once("clearHistoryAck", (_, msg) => {
- is(msg.data, "clearHistory", "a clear history message has been received");
- resolve();
- });
- });
- yield PlacesTestUtils.clearHistory();
- yield placesChangeAck;
- });
- yield cleanup();
-});
-
-/*
- * Sanity tests for search messages
- */
-add_task(function* searchMessages_request() {
- yield setup();
- let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_search.html";
-
- // create dummy test engines
- Services.search.addEngineWithDetails("Engine1", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- Services.search.addEngineWithDetails("Engine2", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- let tabOptions = {
- gBrowser,
- url: testURL
- };
-
- let UIStringsResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("UIStringsAck", (_, msg) => {
- ok(true, "a search request response for UI string has been received");
- ok(msg.data, "received the UI Strings");
- resolve();
- });
- });
- let suggestionsResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("suggestionsAck", (_, msg) => {
- ok(true, "a search request response for suggestions has been received");
- ok(msg.data, "received the suggestions");
- resolve();
- });
- });
- let stateResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("stateAck", (_, msg) => {
- ok(true, "a search request response for state has been received");
- ok(msg.data, "received a state object");
- resolve();
- });
- });
- let currentEngineResponseAck = new Promise(resolve => {
- NewTabWebChannel.once("currentEngineAck", (_, msg) => {
- ok(true, "a search request response for current engine has been received");
- ok(msg.data, "received a current engine");
- resolve();
- });
- });
-
- yield BrowserTestUtils.withNewTab(tabOptions, function*() {
- yield UIStringsResponseAck;
- yield suggestionsResponseAck;
- yield stateResponseAck;
- yield currentEngineResponseAck;
- });
-
- cleanup();
-});
diff --git a/browser/components/newtab/tests/browser/browser_newtabwebchannel.js b/browser/components/newtab/tests/browser/browser_newtabwebchannel.js
deleted file mode 100644
index f003b105b..000000000
--- a/browser/components/newtab/tests/browser/browser_newtabwebchannel.js
+++ /dev/null
@@ -1,251 +0,0 @@
-/* globals XPCOMUtils, Cu, Preferences, NewTabWebChannel, is, registerCleanupFunction */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel",
- "resource:///modules/NewTabWebChannel.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabMessages",
- "resource:///modules/NewTabMessages.jsm");
-
-const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabwebchannel_basic.html";
-const TEST_URL_2 = "http://mochi.test:8888/browser/browser/components/newtab/tests/browser/newtabwebchannel_basic.html";
-
-function setup(mode = "test") {
- Preferences.set("browser.newtabpage.remote.mode", mode);
- Preferences.set("browser.newtabpage.remote", true);
- NewTabWebChannel.init();
- NewTabMessages.init();
-}
-
-function cleanup() {
- NewTabMessages.uninit();
- NewTabWebChannel.uninit();
- Preferences.set("browser.newtabpage.remote", false);
- Preferences.set("browser.newtabpage.remote.mode", "production");
-}
-registerCleanupFunction(cleanup);
-
-/*
- * Tests flow of messages from newtab to chrome and chrome to newtab
- */
-add_task(function* open_webchannel_basic() {
- setup();
-
- let tabOptions = {
- gBrowser,
- url: TEST_URL
- };
-
- let messagePromise = new Promise(resolve => {
- NewTabWebChannel.once("foo", function(name, msg) {
- is(name, "foo", "Correct message type sent: foo");
- is(msg.data, "bar", "Correct data sent: bar");
- resolve(msg.target);
- });
- });
-
- let replyPromise = new Promise(resolve => {
- NewTabWebChannel.once("reply", function(name, msg) {
- is(name, "reply", "Correct message type sent: reply");
- is(msg.data, "quuz", "Correct data sent: quuz");
- resolve(msg.target);
- });
- });
-
- let unloadPromise = new Promise(resolve => {
- NewTabWebChannel.once("targetUnload", function(name) {
- is(name, "targetUnload", "Correct message type sent: targetUnload");
- resolve();
- });
- });
-
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) {
- let target = yield messagePromise;
- is(NewTabWebChannel.numBrowsers, 1, "One target expected");
- is(target.browser, browser, "Same browser");
- NewTabWebChannel.send("respond", null, target);
- yield replyPromise;
- });
-
- Cu.forceGC();
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield unloadPromise;
- cleanup();
-});
-
-/*
- * Tests message broadcast reaches all open newtab pages
- */
-add_task(function* webchannel_broadcast() {
- setup();
-
- let countingMessagePromise = new Promise(resolve => {
- let count = 0;
- NewTabWebChannel.on("foo", function test_message(name, msg) {
- count += 1;
- if (count === 2) {
- NewTabWebChannel.off("foo", test_message);
- resolve(msg.target);
- }
- }.bind(this));
- });
-
- let countingReplyPromise = new Promise(resolve => {
- let count = 0;
- NewTabWebChannel.on("reply", function test_message(name, msg) {
- count += 1;
- if (count === 2) {
- NewTabWebChannel.off("reply", test_message);
- resolve(msg.target);
- }
- }.bind(this));
- });
-
- let countingUnloadPromise = new Promise(resolve => {
- let count = 0;
- NewTabWebChannel.on("targetUnload", function test_message() {
- count += 1;
- if (count === 2) {
- NewTabWebChannel.off("targetUnload", test_message);
- resolve();
- }
- });
- });
-
- let tabs = [];
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL));
- tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL));
-
- yield countingMessagePromise;
- is(NewTabWebChannel.numBrowsers, 2, "Two targets expected");
-
- NewTabWebChannel.broadcast("respond", null);
- yield countingReplyPromise;
-
- for (let tab of tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- Cu.forceGC();
-
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield countingUnloadPromise;
- cleanup();
-});
-
-/*
- * Tests switching modes
- */
-add_task(function* webchannel_switch() {
- setup();
-
- function newMessagePromise() {
- return new Promise(resolve => {
- NewTabWebChannel.once("foo", function(name, msg) {
- resolve(msg.target);
- }.bind(this));
- });
- }
-
- let replyCount = 0;
- function newReplyPromise() {
- return new Promise(resolve => {
- NewTabWebChannel.on("reply", function() {
- replyCount += 1;
- resolve();
- });
- });
- }
-
- let unloadPromise = new Promise(resolve => {
- NewTabWebChannel.once("targetUnload", function() {
- resolve();
- });
- });
-
- let unloadAllPromise = new Promise(resolve => {
- NewTabWebChannel.once("targetUnloadAll", function() {
- resolve();
- });
- });
-
- let tabs = [];
- let messagePromise;
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
-
- messagePromise = newMessagePromise();
- tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL));
- yield messagePromise;
- is(NewTabWebChannel.numBrowsers, 1, "Correct number of targets");
-
- messagePromise = newMessagePromise();
- Preferences.set("browser.newtabpage.remote.mode", "test2");
- tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL_2));
- yield unloadAllPromise;
- yield messagePromise;
- is(NewTabWebChannel.numBrowsers, 1, "Correct number of targets");
-
- NewTabWebChannel.broadcast("respond", null);
- yield newReplyPromise();
- is(replyCount, 1, "only current channel is listened to for replies");
-
- const webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist";
- let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref);
- let newWhitelist = origWhitelist + " http://mochi.test:8888";
- Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist);
- try {
- NewTabWebChannel.broadcast("respond_object", null);
- yield newReplyPromise();
- } finally {
- Services.prefs.clearUserPref(webchannelWhitelistPref);
- }
-
- for (let tab of tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
-
- Cu.forceGC();
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield unloadPromise;
- cleanup();
-});
-
-add_task(function* open_webchannel_reload() {
- setup();
-
- let tabOptions = {
- gBrowser,
- url: TEST_URL
- };
-
- let messagePromise = new Promise(resolve => {
- NewTabWebChannel.once("foo", function(name, msg) {
- is(name, "foo", "Correct message type sent: foo");
- is(msg.data, "bar", "Correct data sent: bar");
- resolve(msg.target);
- });
- });
- let unloadPromise = new Promise(resolve => {
- NewTabWebChannel.once("targetUnload", function() {
- resolve();
- });
- });
-
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) {
- let target = yield messagePromise;
- is(NewTabWebChannel.numBrowsers, 1, "One target expected");
- is(target.browser, browser, "Same browser");
-
- browser.reload();
- });
-
- Cu.forceGC();
- is(NewTabWebChannel.numBrowsers, 0, "Sanity check");
- yield unloadPromise;
- cleanup();
-});
diff --git a/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js b/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js
deleted file mode 100644
index e99aeffc2..000000000
--- a/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* globals Cu, XPCOMUtils, TestUtils, aboutNewTabService, ContentTask, content, is */
-"use strict";
-
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
- "@mozilla.org/browser/aboutnewtab-service;1",
- "nsIAboutNewTabService");
-
-const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/dummy_page.html";
-
-/*
- * Tests opening a newtab page with a remote URL. Simulates a newtab open from chrome
- */
-add_task(function* open_newtab() {
- let notificationPromise = nextChangeNotificationPromise(TEST_URL, "newtab page now points to test url");
- aboutNewTabService.newTabURL = TEST_URL;
-
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "url has been overridden");
-
- /*
- * Simulate a newtab open as a user would.
- *
- * Bug 1240169 - We cannot set the URL to about:newtab because that would invoke the redirector.
- * The redirector always yields the loading of a default newtab URL. We expect the user to use
- * the browser UI to access overriding URLs, for istance by click on the "+" button in the tab
- * bar, or by using the new tab shortcut key.
- */
- BrowserOpenTab(); // jshint ignore:line
-
- let browser = gBrowser.selectedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, {url: TEST_URL}, function*(args) {
- Assert.equal(content.document.location.href, args.url,
- "document.location should match the external resource");
- Assert.equal(content.document.documentURI, args.url,
- "document.documentURI should match the external resource");
- Assert.equal(content.document.nodePrincipal.URI.spec, args.url,
- "nodePrincipal should match the external resource");
- });
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-function nextChangeNotificationPromise(aNewURL, testMessage) {
- return TestUtils.topicObserved("newtab-url-changed", function observer(aSubject, aData) { // jshint unused:false
- Assert.equal(aData, aNewURL, testMessage);
- return true;
- }.bind(this));
-}
diff --git a/browser/components/newtab/tests/browser/dummy_page.html b/browser/components/newtab/tests/browser/dummy_page.html
deleted file mode 100644
index 4b0689bde..000000000
--- a/browser/components/newtab/tests/browser/dummy_page.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
- <meta charset="utf-8">
-</head>
-<body>
-<p>Dummy Page</p>
-</body>
-</html>
diff --git a/browser/components/newtab/tests/browser/newtabmessages_places.html b/browser/components/newtab/tests/browser/newtabmessages_places.html
deleted file mode 100644
index e89bc4a22..000000000
--- a/browser/components/newtab/tests/browser/newtabmessages_places.html
+++ /dev/null
@@ -1,49 +0,0 @@
-<html>
- <head>
- <meta charset="utf8">
- <title>Newtab WebChannel test</title>
- </head>
- <body>
- <script>
- window.addEventListener("WebChannelMessageToContent", function(e) {
- if (e.detail.message) {
- let reply;
- switch (e.detail.message.type) {
- case "RECEIVE_FRECENT":
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "numItemsAck", data: e.detail.message.data.length}),
- })
- });
- window.dispatchEvent(reply);
- break;
- case "RECEIVE_PLACES_CHANGE":
- if (e.detail.message.data.type === "clearHistory") {
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "clearHistoryAck", data: e.detail.message.data.type}),
- })
- });
- window.dispatchEvent(reply);
- }
- break;
- }
- }
- }, true);
-
- document.onreadystatechange = function () {
- if (document.readyState === "complete") {
- let msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_FRECENT"}),
- })
- });
- window.dispatchEvent(msg);
- }
- }
- </script>
- </body>
-</html>
diff --git a/browser/components/newtab/tests/browser/newtabmessages_prefs.html b/browser/components/newtab/tests/browser/newtabmessages_prefs.html
deleted file mode 100644
index 9b38af4b9..000000000
--- a/browser/components/newtab/tests/browser/newtabmessages_prefs.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<html>
- <head>
- <meta charset="utf8">
- <title>Newtab WebChannel test</title>
- </head>
- <body>
- <script>
- window.addEventListener("WebChannelMessageToContent", function(e) {
- if (e.detail.message && e.detail.message.type === "RECEIVE_PREFS") {
- let reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "responseAck"}),
- })
- });
- window.dispatchEvent(reply);
- }
- }, true);
-
- document.onreadystatechange = function () {
- let msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_PREFS"}),
- })
- });
- window.dispatchEvent(msg);
- };
-
- </script>
- </body>
-</html>
diff --git a/browser/components/newtab/tests/browser/newtabmessages_preview.html b/browser/components/newtab/tests/browser/newtabmessages_preview.html
deleted file mode 100644
index 4fe55132d..000000000
--- a/browser/components/newtab/tests/browser/newtabmessages_preview.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<html>
- <head>
- <meta charset="utf8">
- <title>Newtab WebChannel test</title>
- </head>
- <body>
- <script>
- let thumbURL = "https://example.com/browser/browser/components/newtab/tests/browser/blue_page.html";
-
- window.addEventListener("WebChannelMessageToContent", function(e) {
- if (e.detail.message && e.detail.message.type === "RECEIVE_THUMB") {
- if (e.detail.message.data.imgData && e.detail.message.data.url === thumbURL) {
- let reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "responseAck"}),
- })
- });
- window.dispatchEvent(reply);
- }
- }
- }, true);
-
- document.onreadystatechange = function () {
- if (document.readyState === "complete") {
- let msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_THUMB", data: thumbURL}),
- })
- });
- window.dispatchEvent(msg);
- }
- };
- </script>
- </body>
-</html>
diff --git a/browser/components/newtab/tests/browser/newtabmessages_search.html b/browser/components/newtab/tests/browser/newtabmessages_search.html
deleted file mode 100644
index b8b21c42a..000000000
--- a/browser/components/newtab/tests/browser/newtabmessages_search.html
+++ /dev/null
@@ -1,113 +0,0 @@
-<html>
- <head>
- <meta charset="utf8">
- <title>Newtab WebChannel test</title>
- </head>
- <body>
- <script>
- let suggestionsData = {
- engineName: "Engine1",
- searchString: "test",
- };
- let removeFormHistoryData = "test";
- let performSearchData = {
- engineName: "Engine1",
- healthReportKey: "1",
- searchPurpose: "d",
- searchString: "test",
- };
- let cycleEngineData = "Engine2";
-
- window.addEventListener("WebChannelMessageToContent", function(e) {
- if (e.detail.message) {
- let reply;
- switch (e.detail.message.type) {
- case "RECEIVE_UISTRINGS":
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "UIStringsAck", data: e.detail.message.data}),
- }
- });
- window.dispatchEvent(reply);
- break;
- case "RECEIVE_SEARCH_SUGGESTIONS":
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "suggestionsAck", data: e.detail.message.data}),
- }
- });
- window.dispatchEvent(reply);
- break;
- case "RECEIVE_SEARCH_STATE":
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "stateAck", data: e.detail.message.data}),
- }
- });
- window.dispatchEvent(reply);
- break;
- case "RECEIVE_CURRENT_ENGINE":
- reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "currentEngineAck", data: e.detail.message.data}),
- }
- });
- window.dispatchEvent(reply);
- break;
- }
- }
- }, true);
-
- document.onreadystatechange = function () {
- if (document.readyState === "complete") {
- let msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_UISTRINGS"}),
- }
- });
- window.dispatchEvent(msg);
- msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_SEARCH_SUGGESTIONS", data: suggestionsData}),
- }
- });
- window.dispatchEvent(msg);
- msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_SEARCH_STATE"}),
- }
- });
- window.dispatchEvent(msg);
- msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_REMOVE_FORM_HISTORY", data: removeFormHistoryData}),
- }
- });
- window.dispatchEvent(msg);
- msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_PERFORM_SEARCH", data: performSearchData}),
- }
- });
- window.dispatchEvent(msg);
- msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: {
- id: "newtab",
- message: JSON.stringify({type: "REQUEST_CYCLE_ENGINE", data: cycleEngineData}),
- }
- });
- window.dispatchEvent(msg);
- }
- }
- </script>
- </body>
-</html>
diff --git a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html b/browser/components/newtab/tests/browser/newtabwebchannel_basic.html
deleted file mode 100644
index 7f3c79920..000000000
--- a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<html>
- <head>
- <meta charset="utf8">
- <title>Newtab WebChannel test</title>
- </head>
- <body>
- <script>
- document.onreadystatechange = function () {
- let msg = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: JSON.stringify({
- id: "newtab",
- message: JSON.stringify({type: "foo", data: "bar"}),
- })
- });
- window.dispatchEvent(msg);
- };
-
- window.addEventListener("WebChannelMessageToContent", function(e) {
- if (e.detail.message && e.detail.message.type.startsWith("respond")) {
- var detail = {
- id: "newtab",
- message: JSON.stringify({type: "reply", data: "quuz"}),
- };
- if (e.detail.message.type !== "respond_object") {
- detail = JSON.stringify(detail);
- }
- let reply = new window.CustomEvent("WebChannelMessageToChrome", {
- detail: detail
- });
- window.dispatchEvent(reply);
- }
- }, true);
-
- </script>
- </body>
-</html>
diff --git a/browser/components/newtab/tests/xpcshell/.eslintrc.js b/browser/components/newtab/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/newtab/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js b/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js
deleted file mode 100644
index 21f68ab70..000000000
--- a/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js
+++ /dev/null
@@ -1,236 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-/* globals Services, XPCOMUtils, NewTabPrefsProvider, Preferences, aboutNewTabService, do_register_cleanup */
-
-"use strict";
-
-const {utils: Cu} = Components;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
- "resource:///modules/NewTabPrefsProvider.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
- "@mozilla.org/browser/aboutnewtab-service;1",
- "nsIAboutNewTabService");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Locale",
- "resource://gre/modules/Locale.jsm");
-
-const DEFAULT_HREF = aboutNewTabService.generateRemoteURL();
-const DEFAULT_CHROME_URL = "chrome://browser/content/newtab/newTab.xhtml";
-const DOWNLOADS_URL = "chrome://browser/content/downloads/contentAreaDownloadsView.xul";
-const DEFAULT_VERSION = aboutNewTabService.remoteVersion;
-
-function cleanup() {
- Services.prefs.setBoolPref("browser.newtabpage.remote", false);
- Services.prefs.setCharPref("browser.newtabpage.remote.version", DEFAULT_VERSION);
- aboutNewTabService.resetNewTabURL();
- NewTabPrefsProvider.prefs.uninit();
-}
-
-do_register_cleanup(cleanup);
-
-/**
- * Test the overriding of the default URL
- */
-add_task(function* test_override_remote_disabled() {
- NewTabPrefsProvider.prefs.init();
- let notificationPromise;
- Services.prefs.setBoolPref("browser.newtabpage.remote", false);
-
- // tests default is the local newtab resource
- Assert.equal(aboutNewTabService.defaultURL, DEFAULT_CHROME_URL,
- `Default newtab URL should be ${DEFAULT_CHROME_URL}`);
-
- // override with some remote URL
- let url = "http://example.com/";
- notificationPromise = nextChangeNotificationPromise(url);
- aboutNewTabService.newTabURL = url;
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden");
- Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled");
- Assert.equal(aboutNewTabService.newTabURL, url, "Newtab URL should be the custom URL");
-
- // test reset with remote disabled
- notificationPromise = nextChangeNotificationPromise("about:newtab");
- aboutNewTabService.resetNewTabURL();
- yield notificationPromise;
- Assert.ok(!aboutNewTabService.overridden, "Newtab URL should not be overridden");
- Assert.equal(aboutNewTabService.newTabURL, "about:newtab", "Newtab URL should be the default");
-
- // test override to a chrome URL
- notificationPromise = nextChangeNotificationPromise(DOWNLOADS_URL);
- aboutNewTabService.newTabURL = DOWNLOADS_URL;
- yield notificationPromise;
- Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden");
- Assert.equal(aboutNewTabService.newTabURL, DOWNLOADS_URL, "Newtab URL should be the custom URL");
-
- cleanup();
-});
-
-add_task(function* test_override_remote_enabled() {
- NewTabPrefsProvider.prefs.init();
- let notificationPromise;
- // change newtab page to remote
- notificationPromise = nextChangeNotificationPromise("about:newtab");
- Services.prefs.setBoolPref("browser.newtabpage.remote", true);
- yield notificationPromise;
- let remoteHref = aboutNewTabService.generateRemoteURL();
- Assert.equal(aboutNewTabService.defaultURL, remoteHref, "Newtab URL should be the default remote URL");
- Assert.ok(!aboutNewTabService.overridden, "Newtab URL should not be overridden");
- Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled");
-
- // change to local newtab page while remote is enabled
- notificationPromise = nextChangeNotificationPromise(DEFAULT_CHROME_URL);
- aboutNewTabService.newTabURL = DEFAULT_CHROME_URL;
- yield notificationPromise;
- Assert.equal(aboutNewTabService.newTabURL, DEFAULT_CHROME_URL,
- "Newtab URL set to chrome url");
- Assert.equal(aboutNewTabService.defaultURL, DEFAULT_CHROME_URL,
- "Newtab URL defaultURL set to the default chrome URL");
- Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden");
- Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled");
-
- cleanup();
-});
-
-/**
- * Tests reponse to updates to prefs
- */
-add_task(function* test_updates() {
- /*
- * Simulates a "cold-boot" situation, with some pref already set before testing a series
- * of changes.
- */
- Preferences.set("browser.newtabpage.remote", true);
- aboutNewTabService.resetNewTabURL(); // need to set manually because pref notifs are off
- let notificationPromise;
- let productionModeBaseUrl = "https://content.cdn.mozilla.net";
- let testModeBaseUrl = "https://example.com";
- let expectedPath = `/newtab` +
- `/v${aboutNewTabService.remoteVersion}` +
- `/${aboutNewTabService.remoteReleaseName}` +
- "/en-GB" +
- "/index.html";
- let expectedHref = productionModeBaseUrl + expectedPath;
- Preferences.set("intl.locale.matchOS", true);
- Preferences.set("general.useragent.locale", "en-GB");
- Preferences.set("browser.newtabpage.remote.mode", "production");
- NewTabPrefsProvider.prefs.init();
-
- // test update checks for prefs
- notificationPromise = nextChangeNotificationPromise(
- expectedHref, "Remote href should be updated");
- Preferences.set("intl.locale.matchOS", false);
- yield notificationPromise;
-
- notificationPromise = nextChangeNotificationPromise(
- DEFAULT_HREF, "Remote href changes back to default");
- Preferences.set("general.useragent.locale", "en-US");
- yield notificationPromise;
-
- // test update fires when mode is changed
- expectedPath = expectedPath.replace("/en-GB/", "/en-US/");
- notificationPromise = nextChangeNotificationPromise(
- testModeBaseUrl + expectedPath, "Remote href changes back to origin of test mode");
- Preferences.set("browser.newtabpage.remote.mode", "test");
- yield notificationPromise;
-
- // test invalid mode ends up pointing to production url
- notificationPromise = nextChangeNotificationPromise(
- DEFAULT_HREF, "Remote href changes back to production default");
- Preferences.set("browser.newtabpage.remote.mode", "invalid");
- yield notificationPromise;
-
- // test update fires on override and reset
- let testURL = "https://example.com/";
- notificationPromise = nextChangeNotificationPromise(
- testURL, "a notification occurs on override");
- aboutNewTabService.newTabURL = testURL;
- yield notificationPromise;
-
- // from overridden to default
- notificationPromise = nextChangeNotificationPromise(
- "about:newtab", "a notification occurs on reset");
- aboutNewTabService.resetNewTabURL();
- Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled");
- Assert.equal(aboutNewTabService.defaultURL, DEFAULT_HREF, "Default URL should be the remote page");
- yield notificationPromise;
-
- // override to default URL from default URL
- notificationPromise = nextChangeNotificationPromise(
- testURL, "a notification only occurs for a change in overridden urls");
- aboutNewTabService.newTabURL = aboutNewTabService.generateRemoteURL();
- Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled");
- aboutNewTabService.newTabURL = testURL;
- yield notificationPromise;
- Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled");
-
- // reset twice, only one notification for default URL
- notificationPromise = nextChangeNotificationPromise(
- "about:newtab", "reset occurs");
- aboutNewTabService.resetNewTabURL();
- yield notificationPromise;
-
- cleanup();
-});
-
-/**
- * Verifies that releaseFromUpdateChannel
- * Returns the correct release names
- */
-add_task(function* test_release_names() {
- let valid_channels = ["esr", "release", "beta", "aurora", "nightly"];
- let invalid_channels = new Set(["default", "invalid"]);
-
- for (let channel of valid_channels) {
- Assert.equal(channel, aboutNewTabService.releaseFromUpdateChannel(channel),
- "release == channel name when valid");
- }
-
- for (let channel of invalid_channels) {
- Assert.equal("nightly", aboutNewTabService.releaseFromUpdateChannel(channel),
- "release == nightly when invalid");
- }
-});
-
-/**
- * Verifies that remote version updates changes the remote newtab url
- */
-add_task(function* test_version_update() {
- NewTabPrefsProvider.prefs.init();
-
- Services.prefs.setBoolPref("browser.newtabpage.remote", true);
- Assert.ok(aboutNewTabService.remoteEnabled, "remote mode enabled");
-
- let productionModeBaseUrl = "https://content.cdn.mozilla.net";
- let version_incr = String(parseInt(DEFAULT_VERSION) + 1);
- let expectedPath = `/newtab` +
- `/v${version_incr}` +
- `/${aboutNewTabService.remoteReleaseName}` +
- `/${Locale.getLocale()}` +
- `/index.html`;
- let expectedHref = productionModeBaseUrl + expectedPath;
-
- let notificationPromise;
- notificationPromise = nextChangeNotificationPromise(expectedHref);
- Preferences.set("browser.newtabpage.remote.version", version_incr);
- yield notificationPromise;
-
- cleanup();
-});
-
-function nextChangeNotificationPromise(aNewURL, testMessage) {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) { // jshint unused:false
- Services.obs.removeObserver(observer, aTopic);
- Assert.equal(aData, aNewURL, testMessage);
- resolve();
- }, "newtab-url-changed", false);
- });
-}
diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js b/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js
deleted file mode 100644
index f364d0300..000000000
--- a/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js
+++ /dev/null
@@ -1,50 +0,0 @@
-"use strict";
-
-/* global XPCOMUtils, equal, Preferences, NewTabPrefsProvider, run_next_test */
-/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
-
-const Cu = Components.utils;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
- "resource:///modules/NewTabPrefsProvider.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_observe() {
- let prefsMap = NewTabPrefsProvider.prefs.prefsMap;
- for (let prefName of prefsMap.keys()) {
- let prefValueType = prefsMap.get(prefName);
-
- let beforeVal;
- let afterVal;
-
- switch (prefValueType) {
- case "bool":
- beforeVal = false;
- afterVal = true;
- Preferences.set(prefName, beforeVal);
- break;
- case "localized":
- case "str":
- beforeVal = "";
- afterVal = "someStr";
- Preferences.set(prefName, beforeVal);
- break;
- }
- NewTabPrefsProvider.prefs.init();
- let promise = new Promise(resolve => {
- NewTabPrefsProvider.prefs.once(prefName, (name, data) => { // jshint ignore:line
- resolve([name, data]);
- });
- });
- Preferences.set(prefName, afterVal);
- let [actualName, actualData] = yield promise;
- equal(prefName, actualName, `emitter sent the correct pref: ${prefName}`);
- equal(afterVal, actualData, `emitter collected correct pref data for ${prefName}`);
- NewTabPrefsProvider.prefs.uninit();
- }
-});
diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js b/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js
deleted file mode 100644
index 3e60b282a..000000000
--- a/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js
+++ /dev/null
@@ -1,82 +0,0 @@
-"use strict";
-
-/* global XPCOMUtils, NewTabSearchProvider, run_next_test, ok, equal, do_check_true, do_get_profile, Services */
-/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
-
-const Cu = Components.utils;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabSearchProvider",
- "resource:///modules/NewTabSearchProvider.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "ContentSearch",
- "resource:///modules/ContentSearch.jsm");
-
-// ensure a profile exists
-do_get_profile();
-
-function run_test() {
- run_next_test();
-}
-
-function hasProp(obj) {
- return function(aProp) {
- ok(obj.hasOwnProperty(aProp), `expect to have property ${aProp}`);
- };
-}
-
-add_task(function* test_search() {
- ContentSearch.init();
- let observerPromise = new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
- if (aData === "init-complete" && aTopic === "browser-search-service") {
- Services.obs.removeObserver(observer, "browser-search-service");
- resolve();
- }
- }, "browser-search-service", false);
- });
- Services.search.init();
- yield observerPromise;
- do_check_true(Services.search.isInitialized);
-
- // get initial state of search and check it has correct properties
- let state = yield NewTabSearchProvider.search.asyncGetState();
- let stateProps = hasProp(state);
- ["engines", "currentEngine"].forEach(stateProps);
-
- // check that the current engine is correct and has correct properties
- let {currentEngine} = state;
- equal(currentEngine.name, Services.search.currentEngine.name, "Current engine has been correctly set");
- var engineProps = hasProp(currentEngine);
- ["name", "placeholder", "iconBuffer"].forEach(engineProps);
-
- // create dummy test engines to test observer
- Services.search.addEngineWithDetails("TestSearch1", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
- Services.search.addEngineWithDetails("TestSearch2", "", "", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // set one of the dummy test engines to the default engine
- Services.search.defaultEngine = Services.search.getEngineByName("TestSearch1");
-
- // test that the event emitter is working by setting a new current engine "TestSearch2"
- let engineName = "TestSearch2";
- NewTabSearchProvider.search.init();
-
- // event emitter will fire when current engine is changed
- let promise = new Promise(resolve => {
- NewTabSearchProvider.search.once("browser-search-engine-modified", (name, data) => { // jshint ignore:line
- resolve([name, data.name]);
- });
- });
-
- // set a new current engine
- Services.search.currentEngine = Services.search.getEngineByName(engineName);
- let expectedEngineName = Services.search.currentEngine.name;
-
- // emitter should fire and return the new engine
- let [eventName, actualEngineName] = yield promise;
- equal(eventName, "browser-search-engine-modified", `emitter sent the correct event ${eventName}`);
- equal(expectedEngineName, actualEngineName, `emitter set the correct engine ${expectedEngineName}`);
- NewTabSearchProvider.search.uninit();
-});
diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabURL.js b/browser/components/newtab/tests/xpcshell/test_NewTabURL.js
deleted file mode 100644
index 1505e638c..000000000
--- a/browser/components/newtab/tests/xpcshell/test_NewTabURL.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-/* globals Services, NewTabURL, XPCOMUtils, aboutNewTabService, NewTabPrefsProvider */
-"use strict";
-
-const {utils: Cu} = Components;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource:///modules/NewTabURL.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
- "resource:///modules/NewTabPrefsProvider.jsm");
-XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
- "@mozilla.org/browser/aboutnewtab-service;1",
- "nsIAboutNewTabService");
-
-add_task(function*() {
- let defaultURL = aboutNewTabService.newTabURL;
- Services.prefs.setBoolPref("browser.newtabpage.remote", false);
-
- Assert.equal(NewTabURL.get(), defaultURL, `Default newtab URL should be ${defaultURL}`);
- let url = "http://example.com/";
- let notificationPromise = promiseNewtabURLNotification(url);
- NewTabURL.override(url);
- yield notificationPromise;
- Assert.ok(NewTabURL.overridden, "Newtab URL should be overridden");
- Assert.equal(NewTabURL.get(), url, "Newtab URL should be the custom URL");
-
- notificationPromise = promiseNewtabURLNotification(defaultURL);
- NewTabURL.reset();
- yield notificationPromise;
- Assert.ok(!NewTabURL.overridden, "Newtab URL should not be overridden");
- Assert.equal(NewTabURL.get(), defaultURL, "Newtab URL should be the default");
-
- // change newtab page to remote
- NewTabPrefsProvider.prefs.init();
- Services.prefs.setBoolPref("browser.newtabpage.remote", true);
- Assert.equal(NewTabURL.get(), "about:newtab", `Newtab URL should be about:newtab`);
- Assert.ok(!NewTabURL.overridden, "Newtab URL should not be overridden");
- NewTabPrefsProvider.prefs.uninit();
-});
-
-function promiseNewtabURLNotification(aNewURL) {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) { // jshint ignore:line
- Services.obs.removeObserver(observer, aTopic);
- Assert.equal(aData, aNewURL, "Data for newtab-url-changed notification should be new URL.");
- resolve();
- }, "newtab-url-changed", false);
- });
-}
diff --git a/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js b/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js
deleted file mode 100644
index 22815741b..000000000
--- a/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js
+++ /dev/null
@@ -1,358 +0,0 @@
-"use strict";
-
-/* global XPCOMUtils, PlacesUtils, PlacesTestUtils, PlacesProvider, NetUtil */
-/* global do_get_profile, run_next_test, add_task */
-/* global equal, ok */
-
-const {
- utils: Cu,
- interfaces: Ci,
-} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesProvider",
- "resource:///modules/PlacesProvider.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-
-// ensure a profile exists
-do_get_profile();
-
-function run_test() {
- PlacesProvider.links.init();
- run_next_test();
-}
-
-// url prefix for test history population
-const TEST_URL = "https://mozilla.com/";
-// time when the test starts execution
-const TIME_NOW = (new Date()).getTime();
-
-// utility function to compute past timestap
-function timeDaysAgo(numDays) {
- return TIME_NOW - (numDays * 24 * 60 * 60 * 1000);
-}
-
-// utility function to make a visit for insetion into places db
-function makeVisit(index, daysAgo, isTyped, domain=TEST_URL) {
- let {
- TRANSITION_TYPED,
- TRANSITION_LINK
- } = PlacesUtils.history;
-
- return {
- uri: NetUtil.newURI(`${domain}${index}`),
- visitDate: timeDaysAgo(daysAgo),
- transition: (isTyped) ? TRANSITION_TYPED : TRANSITION_LINK,
- };
-}
-
-/** Test LinkChecker **/
-
-add_task(function test_LinkChecker_securityCheck() {
-
- let urls = [
- {url: "javascript:alert('hello')", expected: false}, // jshint ignore:line
- {url: "data:image/png;base64,XXX", expected: false},
- {url: "about:newtab", expected: true},
- {url: "https://example.com", expected: true},
- {url: "ftp://example.com", expected: true},
- {url: "file://home/file/image.png", expected: true},
- {url: "resource:///modules/PlacesProvider.jsm", expected: true},
- ];
- for (let {url, expected} of urls) {
- let observed = PlacesProvider.LinkChecker.checkLoadURI(url);
- equal(observed, expected, `can load "${url}"?`);
- }
-});
-
-/** Test Provider **/
-
-add_task(function* test_Links_getLinks() {
- yield PlacesTestUtils.clearHistory();
- let provider = PlacesProvider.links;
-
- let links = yield provider.getLinks();
- equal(links.length, 0, "empty history yields empty links");
-
- // add a visit
- let testURI = NetUtil.newURI("http://mozilla.com");
- yield PlacesTestUtils.addVisits(testURI);
-
- links = yield provider.getLinks();
- equal(links.length, 1, "adding a visit yields a link");
- equal(links[0].url, testURI.spec, "added visit corresponds to added url");
-});
-
-add_task(function* test_Links_getLinks_Order() {
- yield PlacesTestUtils.clearHistory();
- let provider = PlacesProvider.links;
-
- // all four visits must come from different domains to avoid deduplication
- let visits = [
- makeVisit(0, 0, true, "http://bar.com/"), // frecency 200, today
- makeVisit(1, 0, true, "http://foo.com/"), // frecency 200, today
- makeVisit(2, 2, true, "http://buz.com/"), // frecency 200, 2 days ago
- makeVisit(3, 2, false, "http://aaa.com/"), // frecency 10, 2 days ago, transition
- ];
-
- let links = yield provider.getLinks();
- equal(links.length, 0, "empty history yields empty links");
- yield PlacesTestUtils.addVisits(visits);
-
- links = yield provider.getLinks();
- equal(links.length, visits.length, "number of links added is the same as obtain by getLinks");
- for (let i = 0; i < links.length; i++) {
- equal(links[i].url, visits[i].uri.spec, "links are obtained in the expected order");
- }
-});
-
-add_task(function* test_Links_getLinks_Deduplication() {
- yield PlacesTestUtils.clearHistory();
- let provider = PlacesProvider.links;
-
- // all for visits must come from different domains to avoid deduplication
- let visits = [
- makeVisit(0, 2, true, "http://bar.com/"), // frecency 200, 2 days ago
- makeVisit(1, 0, true, "http://bar.com/"), // frecency 200, today
- makeVisit(2, 0, false, "http://foo.com/"), // frecency 10, today
- makeVisit(3, 0, true, "http://foo.com/"), // frecency 200, today
- ];
-
- let links = yield provider.getLinks();
- equal(links.length, 0, "empty history yields empty links");
- yield PlacesTestUtils.addVisits(visits);
-
- links = yield provider.getLinks();
- equal(links.length, 2, "only two links must be left after deduplication");
- equal(links[0].url, visits[1].uri.spec, "earliest link is present");
- equal(links[1].url, visits[3].uri.spec, "most fresent link is present");
-});
-
-add_task(function* test_Links_onLinkChanged() {
- let provider = PlacesProvider.links;
-
- let url = "https://example.com/onFrecencyChanged1";
- let linkChangedMsgCount = 0;
-
- let linkChangedPromise = new Promise(resolve => {
- let handler = (_, link) => { // jshint ignore:line
- /* There are 3 linkChanged events:
- * 1. visit insertion (-1 frecency by default)
- * 2. frecency score update (after transition type calculation etc)
- * 3. title change
- */
- if (link.url === url) {
- equal(link.url, url, `expected url on linkChanged event`);
- linkChangedMsgCount += 1;
- if (linkChangedMsgCount === 3) {
- ok(true, `all linkChanged events captured`);
- provider.off("linkChanged", this);
- resolve();
- }
- }
- };
- provider.on("linkChanged", handler);
- });
-
- // add a visit
- let testURI = NetUtil.newURI(url);
- yield PlacesTestUtils.addVisits(testURI);
- yield linkChangedPromise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_Links_onClearHistory() {
- let provider = PlacesProvider.links;
-
- let clearHistoryPromise = new Promise(resolve => {
- let handler = () => {
- ok(true, `clearHistory event captured`);
- provider.off("clearHistory", handler);
- resolve();
- };
- provider.on("clearHistory", handler);
- });
-
- // add visits
- for (let i = 0; i <= 10; i++) {
- let url = `https://example.com/onClearHistory${i}`;
- let testURI = NetUtil.newURI(url);
- yield PlacesTestUtils.addVisits(testURI);
- }
- yield PlacesTestUtils.clearHistory();
- yield clearHistoryPromise;
-});
-
-add_task(function* test_Links_onDeleteURI() {
- let provider = PlacesProvider.links;
-
- let testURL = "https://example.com/toDelete";
-
- let deleteURIPromise = new Promise(resolve => {
- let handler = (_, {url}) => { // jshint ignore:line
- equal(testURL, url, "deleted url and expected url are the same");
- provider.off("deleteURI", handler);
- resolve();
- };
-
- provider.on("deleteURI", handler);
- });
-
- let testURI = NetUtil.newURI(testURL);
- yield PlacesTestUtils.addVisits(testURI);
- yield PlacesUtils.history.remove(testURL);
- yield deleteURIPromise;
-});
-
-add_task(function* test_Links_onManyLinksChanged() {
- let provider = PlacesProvider.links;
-
- let promise = new Promise(resolve => {
- let handler = () => {
- ok(true);
- provider.off("manyLinksChanged", handler);
- resolve();
- };
-
- provider.on("manyLinksChanged", handler);
- });
-
- let testURL = "https://example.com/toDelete";
- let testURI = NetUtil.newURI(testURL);
- yield PlacesTestUtils.addVisits(testURI);
-
- // trigger DecayFrecency
- PlacesUtils.history.QueryInterface(Ci.nsIObserver).
- observe(null, "idle-daily", "");
-
- yield promise;
-});
-
-add_task(function* test_Links_execute_query() {
- yield PlacesTestUtils.clearHistory();
- let provider = PlacesProvider.links;
-
- let visits = [
- makeVisit(0, 0, true), // frecency 200, today
- makeVisit(1, 0, true), // frecency 200, today
- makeVisit(2, 2, true), // frecency 200, 2 days ago
- makeVisit(3, 2, false), // frecency 10, 2 days ago, transition
- ];
-
- yield PlacesTestUtils.addVisits(visits);
-
- function testItemValue(results, index, value) {
- equal(results[index][0], `${TEST_URL}${value}`, "raw url");
- equal(results[index][1], `test visit for ${TEST_URL}${value}`, "raw title");
- }
-
- function testItemObject(results, index, columnValues) {
- Object.keys(columnValues).forEach(name => {
- equal(results[index][name], columnValues[name], "object name " + name);
- });
- }
-
- // select all 4 records
- let results = yield provider.executePlacesQuery("select url, title from moz_places");
- equal(results.length, 4, "expect 4 items");
- // check for insert order sequence
- for (let i = 0; i < results.length; i++) {
- testItemValue(results, i, i);
- }
-
- // test parameter passing
- results = yield provider.executePlacesQuery(
- "select url, title from moz_places limit :limit",
- {params: {limit: 2}}
- );
- equal(results.length, 2, "expect 2 items");
- for (let i = 0; i < results.length; i++) {
- testItemValue(results, i, i);
- }
-
- // test extracting items by name
- results = yield provider.executePlacesQuery(
- "select url, title from moz_places limit :limit",
- {columns: ["url", "title"], params: {limit: 4}}
- );
- equal(results.length, 4, "expect 4 items");
- for (let i = 0; i < results.length; i++) {
- testItemObject(results, i, {
- "url": `${TEST_URL}${i}`,
- "title": `test visit for ${TEST_URL}${i}`,
- });
- }
-
- // test ordering
- results = yield provider.executePlacesQuery(
- "select url, title, last_visit_date, frecency from moz_places " +
- "order by frecency DESC, last_visit_date DESC, url DESC limit :limit",
- {columns: ["url", "title", "last_visit_date", "frecency"], params: {limit: 4}}
- );
- equal(results.length, 4, "expect 4 items");
- testItemObject(results, 0, {url: `${TEST_URL}1`});
- testItemObject(results, 1, {url: `${TEST_URL}0`});
- testItemObject(results, 2, {url: `${TEST_URL}2`});
- testItemObject(results, 3, {url: `${TEST_URL}3`});
-
- // test callback passing
- results = [];
- function handleRow(aRow) {
- results.push({
- url: aRow.getResultByName("url"),
- title: aRow.getResultByName("title"),
- last_visit_date: aRow.getResultByName("last_visit_date"),
- frecency: aRow.getResultByName("frecency")
- });
- }
- yield provider.executePlacesQuery(
- "select url, title, last_visit_date, frecency from moz_places " +
- "order by frecency DESC, last_visit_date DESC, url DESC",
- {callback: handleRow}
- );
- equal(results.length, 4, "expect 4 items");
- testItemObject(results, 0, {url: `${TEST_URL}1`});
- testItemObject(results, 1, {url: `${TEST_URL}0`});
- testItemObject(results, 2, {url: `${TEST_URL}2`});
- testItemObject(results, 3, {url: `${TEST_URL}3`});
-
- // negative test cases
- // bad sql
- try {
- yield provider.executePlacesQuery("select from moz");
- do_throw("bad sql should've thrown");
- }
- catch (e) {
- do_check_true("expected failure - bad sql");
- }
- // missing bindings
- try {
- yield provider.executePlacesQuery("select * from moz_places limit :limit");
- do_throw("bad sql should've thrown");
- }
- catch (e) {
- do_check_true("expected failure - missing bidning");
- }
- // non-existent column name
- try {
- yield provider.executePlacesQuery("select * from moz_places limit :limit",
- {columns: ["no-such-column"], params: {limit: 4}});
- do_throw("bad sql should've thrown");
- }
- catch (e) {
- do_check_true("expected failure - wrong column name");
- }
-
- // cleanup
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/browser/components/newtab/tests/xpcshell/xpcshell.ini b/browser/components/newtab/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index c249ee3e2..000000000
--- a/browser/components/newtab/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head =
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_AboutNewTabService.js]
-[test_NewTabPrefsProvider.js]
-[test_NewTabSearchProvider.js]
-[test_NewTabURL.js]
-[test_PlacesProvider.js]
diff --git a/browser/components/originattributes/moz.build b/browser/components/originattributes/moz.build
deleted file mode 100644
index ea5943ea1..000000000
--- a/browser/components/originattributes/moz.build
+++ /dev/null
@@ -1,16 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# 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/.
-
-BROWSER_CHROME_MANIFESTS += [
- 'test/browser/browser.ini',
-]
-
-MOCHITEST_MANIFESTS += [
- 'test/mochitest/mochitest.ini'
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Firefox', 'OriginAttributes')
diff --git a/browser/components/originattributes/test/browser/.eslintrc.js b/browser/components/originattributes/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/originattributes/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/originattributes/test/browser/browser.ini b/browser/components/originattributes/test/browser/browser.ini
deleted file mode 100644
index 61f674377..000000000
--- a/browser/components/originattributes/test/browser/browser.ini
+++ /dev/null
@@ -1,64 +0,0 @@
-[DEFAULT]
-tags = usercontextid firstpartyisolation originattributes
-support-files =
- dummy.html
- file_broadcastChannel.html
- file_broadcastChanneliFrame.html
- file_cache.html
- file_favicon.html
- file_favicon.png
- file_favicon.png^headers^
- file_favicon_cache.html
- file_favicon_cache.png
- file_favicon_thirdParty.html
- file_firstPartyBasic.html
- file_sharedworker.html
- file_sharedworker.js
- file_thirdPartyChild.audio.ogg
- file_thirdPartyChild.embed.png
- file_thirdPartyChild.fetch.html
- file_thirdPartyChild.iframe.html
- file_thirdPartyChild.img.png
- file_thirdPartyChild.import.js
- file_thirdPartyChild.link.css
- file_thirdPartyChild.object.png
- file_thirdPartyChild.request.html
- file_thirdPartyChild.script.js
- file_thirdPartyChild.sharedworker.js
- file_thirdPartyChild.track.vtt
- file_thirdPartyChild.video.ogv
- file_thirdPartyChild.worker.fetch.html
- file_thirdPartyChild.worker.js
- file_thirdPartyChild.worker.request.html
- file_thirdPartyChild.worker.xhr.html
- file_thirdPartyChild.xhr.html
- head.js
- test.js
- test.js^headers^
- test.html
- test2.html
- test2.js
- test2.js^headers^
- test_firstParty.html
- test_firstParty_cookie.html
- test_firstParty_html_redirect.html
- test_firstParty_http_redirect.html
- test_firstParty_http_redirect.html^headers^
- test_firstParty_iframe_http_redirect.html
- test_firstParty_postMessage.html
- window.html
- worker_blobify.js
- worker_deblobify.js
-
-[browser_broadcastChannel.js]
-[browser_cache.js]
-[browser_cookieIsolation.js]
-[browser_favicon_firstParty.js]
-[browser_favicon_userContextId.js]
-[browser_firstPartyIsolation.js]
-[browser_localStorageIsolation.js]
-[browser_blobURLIsolation.js]
-[browser_imageCacheIsolation.js]
-[browser_sharedworker.js]
-[browser_httpauth.js]
-[browser_clientAuth.js]
diff --git a/browser/components/originattributes/test/browser/browser_blobURLIsolation.js b/browser/components/originattributes/test/browser/browser_blobURLIsolation.js
deleted file mode 100644
index 1d1b7c8e1..000000000
--- a/browser/components/originattributes/test/browser/browser_blobURLIsolation.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * Bug 1264573 - A test case for blob url isolation.
- */
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" +
- "originattributes/test/browser/file_firstPartyBasic.html";
-const SCRIPT_WORKER_BLOBIFY = "worker_blobify.js";
-const SCRIPT_WORKER_DEBLOBIFY = "worker_deblobify.js";
-
-function page_blobify(browser, input) {
- return ContentTask.spawn(browser, input, function(input) {
- return { blobURL: content.URL.createObjectURL(new content.Blob([input])) };
- });
-}
-
-function page_deblobify(browser, blobURL) {
- return ContentTask.spawn(browser, blobURL, function* (blobURL) {
- if ("error" in blobURL) {
- return blobURL;
- }
- blobURL = blobURL.blobURL;
-
- function blobURLtoBlob(blobURL) {
- return new content.Promise(function (resolve) {
- let xhr = new content.XMLHttpRequest();
- xhr.open("GET", blobURL, true);
- xhr.onload = function () {
- resolve(xhr.response);
- };
- xhr.onerror = function () {
- resolve("xhr error");
- };
- xhr.responseType = "blob";
- xhr.send();
- });
- }
-
- function blobToString(blob) {
- return new content.Promise(function (resolve) {
- let fileReader = new content.FileReader();
- fileReader.onload = function () {
- resolve(fileReader.result);
- };
- fileReader.readAsText(blob);
- });
- }
-
- let blob = yield blobURLtoBlob(blobURL);
- if (blob == "xhr error") {
- return "xhr error";
- }
-
- return yield blobToString(blob);
- });
-}
-
-function workerIO(browser, scriptFile, message) {
- return ContentTask.spawn(browser, {scriptFile, message}, function* (args) {
- let worker = new content.Worker(args.scriptFile);
- let promise = new content.Promise(function(resolve) {
- let listenFunction = function(event) {
- worker.removeEventListener("message", listenFunction, false);
- worker.terminate();
- resolve(event.data);
- };
- worker.addEventListener("message", listenFunction, false);
- });
- worker.postMessage(args.message);
- return yield promise;
- });
-}
-
-let worker_blobify = (browser, input) => workerIO(browser, SCRIPT_WORKER_BLOBIFY, input);
-let worker_deblobify = (browser, blobURL) => workerIO(browser, SCRIPT_WORKER_DEBLOBIFY, blobURL);
-
-function doTest(blobify, deblobify) {
- let blobURL = null;
- return function* (browser) {
- if (blobURL === null) {
- let input = Math.random().toString();
- blobURL = yield blobify(browser, input);
- return input;
- }
- let result = yield deblobify(browser, blobURL);
- blobURL = null;
- return result;
- }
-}
-
-let tests = [];
-for (let blobify of [page_blobify, worker_blobify]) {
- for (let deblobify of [page_deblobify, worker_deblobify]) {
- tests.push(doTest(blobify, deblobify));
- }
-}
-
-IsolationTestTools.runTests(TEST_PAGE, tests);
diff --git a/browser/components/originattributes/test/browser/browser_broadcastChannel.js b/browser/components/originattributes/test/browser/browser_broadcastChannel.js
deleted file mode 100644
index 3a2bd7405..000000000
--- a/browser/components/originattributes/test/browser/browser_broadcastChannel.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Bug 1264571 - A test case of broadcast channels for first party isolation.
- */
-
-const TEST_DOMAIN = "http://example.net/";
-const TEST_PATH = TEST_DOMAIN + "browser/browser/components/originattributes/test/browser/";
-const TEST_PAGE = TEST_PATH + "file_broadcastChannel.html";
-
-function* doTest(aBrowser) {
- let response = yield ContentTask.spawn(aBrowser, null, function* () {
-
- let displayItem = content.document.getElementById("display");
-
- // If there is nothing in the 'display', we will try to send a message to
- // the broadcast channel and wait until this message has been delivered.
- // The way that how we make sure the message is delivered is based on an
- // iframe which will reply everything it receives from the broadcast channel
- // to the current window through the postMessage. So, we can know that the
- // boradcast message is sent successfully when the window receives a message
- // from the iframe.
- if (displayItem.innerHTML === "") {
- let data = Math.random().toString();
-
- let receivedData = yield new Promise(resolve => {
- let listenFunc = event => {
- content.removeEventListener("message", listenFunc);
- resolve(event.data);
- };
-
- let bc = new content.BroadcastChannel("testBroadcastChannel");
-
- content.addEventListener("message", listenFunc, false);
- bc.postMessage(data);
- });
-
- is(receivedData, data, "The value should be the same.");
-
- return receivedData;
- }
-
- return displayItem.innerHTML;
- });
-
- return response;
-}
-
-IsolationTestTools.runTests(TEST_PAGE, doTest);
diff --git a/browser/components/originattributes/test/browser/browser_cache.js b/browser/components/originattributes/test/browser/browser_cache.js
deleted file mode 100644
index d5f3a8f58..000000000
--- a/browser/components/originattributes/test/browser/browser_cache.js
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Bug 1264577 - A test case for testing caches of various submodules.
- * This test case will load two pages that each page loads various resources
- * within the same third party domain for the same originAttributes or different
- * originAttributes. And then, it verifies the number of cache entries and
- * the originAttributes of loading channels. If these two pages belong to
- * the same originAttributes, the number of cache entries for a certain
- * resource would be one. Otherwise, it would be two.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-let {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
-let protocolProxyService = Cc["@mozilla.org/network/protocol-proxy-service;1"]
- .getService(Ci.nsIProtocolProxyService);
-
-const TEST_DOMAIN = "http://example.net";
-const TEST_PATH = "/browser/browser/components/originattributes/test/browser/";
-const TEST_PAGE = TEST_DOMAIN + TEST_PATH + "file_cache.html";
-
-let suffixes = ["iframe.html", "link.css", "script.js", "img.png", "object.png",
- "embed.png", "xhr.html", "worker.xhr.html", "audio.ogg",
- "video.ogv", "track.vtt",
- "fetch.html", "worker.fetch.html",
- "request.html", "worker.request.html",
- "import.js", "worker.js", "sharedworker.js"];
-
-// A random value for isolating video/audio elements across different tests.
-let randomSuffix;
-
-function clearAllImageCaches() {
- let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"]
- .getService(SpecialPowers.Ci.imgITools);
- let imageCache = tools.getImgCacheForDocument(window.document);
- imageCache.clearCache(true); // true=chrome
- imageCache.clearCache(false); // false=content
-}
-
-function cacheDataForContext(loadContextInfo) {
- return new Promise(resolve => {
- let cacheEntries = [];
- let cacheVisitor = {
- onCacheStorageInfo(num, consumption) {},
- onCacheEntryInfo(uri, idEnhance) {
- cacheEntries.push({ uri: uri,
- idEnhance: idEnhance });
- },
- onCacheEntryVisitCompleted() {
- resolve(cacheEntries);
- },
- QueryInterface(iid) {
- if (iid.equals(Ci.nsICacheStorageVisitor))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- };
- // Visiting the disk cache also visits memory storage so we do not
- // need to use Services.cache2.memoryCacheStorage() here.
- let storage = Services.cache2.diskCacheStorage(loadContextInfo, false);
- storage.asyncVisitStorage(cacheVisitor, true);
- });
-}
-
-let countMatchingCacheEntries = function (cacheEntries, domain, fileSuffix) {
- return cacheEntries.map(entry => entry.uri.asciiSpec)
- .filter(spec => spec.includes(domain))
- .filter(spec => spec.includes("file_thirdPartyChild." + fileSuffix))
- .length;
-};
-
-function observeChannels(onChannel) {
- // We use a dummy proxy filter to catch all channels, even those that do not
- // generate an "http-on-modify-request" notification, such as link preconnects.
- let proxyFilter = {
- applyFilter : function (aProxyService, aChannel, aProxy) {
- // We have the channel; provide it to the callback.
- onChannel(aChannel);
- // Pass on aProxy unmodified.
- return aProxy;
- }
- };
- protocolProxyService.registerChannelFilter(proxyFilter, 0);
- // Return the stop() function:
- return () => protocolProxyService.unregisterChannelFilter(proxyFilter);
-}
-
-function startObservingChannels(aMode) {
- let stopObservingChannels = observeChannels(function (channel) {
- let originalURISpec = channel.originalURI.spec;
- if (originalURISpec.includes("example.net")) {
- let loadInfo = channel.loadInfo;
-
- switch (aMode) {
- case TEST_MODE_FIRSTPARTY:
- ok(loadInfo.originAttributes.firstPartyDomain === "example.com" ||
- loadInfo.originAttributes.firstPartyDomain === "example.org",
- "first party for " + originalURISpec + " is " + loadInfo.originAttributes.firstPartyDomain);
- break;
-
- case TEST_MODE_NO_ISOLATION:
- ok(ChromeUtils.isOriginAttributesEqual(loadInfo.originAttributes, ChromeUtils.fillNonDefaultOriginAttributes()),
- "OriginAttributes for " + originalURISpec + " is default.");
- break;
-
- case TEST_MODE_CONTAINERS:
- ok(loadInfo.originAttributes.userContextId === 1 ||
- loadInfo.originAttributes.userContextId === 2,
- "userContextId for " + originalURISpec + " is " + loadInfo.originAttributes.userContextId);
- break;
-
- default:
- ok(false, "Unknown test mode.");
- }
- }
- });
- return stopObservingChannels;
-}
-
-let stopObservingChannels;
-
-// The init function, which clears image and network caches, and generates
-// the random value for isolating video and audio elements across different
-// test runs.
-function* doInit(aMode) {
- yield SpecialPowers.pushPrefEnv({"set": [["network.predictor.enabled", false],
- ["network.predictor.enable-prefetch", false]]});
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- randomSuffix = Math.random();
- stopObservingChannels = startObservingChannels(aMode);
-}
-
-// In the test function, we dynamically generate the video and audio element,
-// and assign a random suffix to their URL to isolate them across different
-// test runs.
-function* doTest(aBrowser) {
-
- let argObj = {
- randomSuffix: randomSuffix,
- urlPrefix: TEST_DOMAIN + TEST_PATH,
- };
-
- yield ContentTask.spawn(aBrowser, argObj, function* (arg) {
- let videoURL = arg.urlPrefix + "file_thirdPartyChild.video.ogv";
- let audioURL = arg.urlPrefix + "file_thirdPartyChild.audio.ogg";
- let trackURL = arg.urlPrefix + "file_thirdPartyChild.track.vtt";
- let URLSuffix = "?r=" + arg.randomSuffix;
-
- // Create the audio and video elements.
- let audio = content.document.createElement('audio');
- let video = content.document.createElement('video');
- let audioSource = content.document.createElement('source');
- let audioTrack = content.document.createElement('track');
-
- // Append the audio and track element into the body, and wait until they're finished.
- yield new Promise(resolve => {
- let audioLoaded = false;
- let trackLoaded = false;
-
- let audioListener = () => {
- audio.removeEventListener("canplaythrough", audioListener);
-
- audioLoaded = true;
- if (audioLoaded && trackLoaded) {
- resolve();
- }
- };
-
- let trackListener = () => {
- audioTrack.removeEventListener("load", trackListener);
-
- trackLoaded = true;
- if (audioLoaded && trackLoaded) {
- resolve();
- }
- };
-
- // Add the event listeners before everything in case we lose events.
- audioTrack.addEventListener("load", trackListener, false);
- audio.addEventListener("canplaythrough", audioListener, false);
-
- // Assign attributes for the audio element.
- audioSource.setAttribute("src", audioURL + URLSuffix);
- audioSource.setAttribute("type", "audio/ogg");
- audioTrack.setAttribute("src", trackURL);
- audioTrack.setAttribute("kind", "subtitles");
-
- audio.appendChild(audioSource);
- audio.appendChild(audioTrack);
- audio.autoplay = true;
-
- content.document.body.appendChild(audio);
- });
-
- // Append the video element into the body, and wait until it's finished.
- yield new Promise(resolve => {
- let listener = () => {
- video.removeEventListener("canplaythrough", listener);
- resolve();
- };
-
- // Add the event listener before everything in case we lose the event.
- video.addEventListener("canplaythrough", listener, false);
-
- // Assign attributes for the video element.
- video.setAttribute("src", videoURL + URLSuffix);
- video.setAttribute("type", "video/ogg");
-
- content.document.body.appendChild(video);
- });
- });
-
- return 0;
-}
-
-// The check function, which checks the number of cache entries.
-function* doCheck(aShouldIsolate, aInputA, aInputB) {
- let expectedEntryCount = 1;
- let data = [];
- data = data.concat(yield cacheDataForContext(LoadContextInfo.default));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.private));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, {})));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { userContextId: 1 })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { userContextId: 1 })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { userContextId: 2 })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { userContextId: 2 })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { firstPartyDomain: "example.com" })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { firstPartyDomain: "example.com" })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { firstPartyDomain: "example.org" })));
- data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { firstPartyDomain: "example.org" })));
-
- if (aShouldIsolate) {
- expectedEntryCount = 2;
- }
-
- for (let suffix of suffixes) {
- let foundEntryCount = countMatchingCacheEntries(data, "example.net", suffix);
- let result = (expectedEntryCount === foundEntryCount);
- ok(result, "Cache entries expected for " + suffix + ": " + expectedEntryCount +
- ", and found " + foundEntryCount);
- }
-
- stopObservingChannels();
- stopObservingChannels = undefined;
- return true;
-}
-
-let testArgs = {
- url: TEST_PAGE,
- firstFrameSetting: DEFAULT_FRAME_SETTING,
- secondFrameSetting: [TEST_TYPE_FRAME],
-};
-
-IsolationTestTools.runTests(testArgs, doTest, doCheck, doInit);
diff --git a/browser/components/originattributes/test/browser/browser_clientAuth.js b/browser/components/originattributes/test/browser/browser_clientAuth.js
deleted file mode 100644
index 48961dce0..000000000
--- a/browser/components/originattributes/test/browser/browser_clientAuth.js
+++ /dev/null
@@ -1,44 +0,0 @@
-let certCached = true;
-let secondTabStarted = false;
-
-function onCertDialogLoaded(subject) {
- certCached = false;
- // Click OK.
- subject.acceptDialog();
-}
-
-Services.obs.addObserver(onCertDialogLoaded, "cert-dialog-loaded", false);
-
-registerCleanupFunction(() => {
- Services.obs.removeObserver(onCertDialogLoaded, "cert-dialog-loaded");
-});
-
-function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["security.default_personal_cert", "Ask Every Time"]]
- });
-}
-
-function getResult() {
- // The first tab always returns true.
- if (!secondTabStarted) {
- certCached = true;
- secondTabStarted = true;
- return true;
- }
-
- // The second tab returns true if the cert is cached, so it will be different
- // from the result of the first tab, and considered isolated.
- let ret = certCached;
- certCached = true;
- secondTabStarted = false;
- return ret;
-}
-
-// aGetResultImmediately must be true because we need to get the result before
-// the next tab is opened.
-IsolationTestTools.runTests("https://requireclientcert.example.com",
- getResult,
- null, // aCompareResultFunc
- setup, // aBeginFunc
- true); // aGetResultImmediately
diff --git a/browser/components/originattributes/test/browser/browser_cookieIsolation.js b/browser/components/originattributes/test/browser/browser_cookieIsolation.js
deleted file mode 100644
index 6259723ba..000000000
--- a/browser/components/originattributes/test/browser/browser_cookieIsolation.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Bug 1312541 - A test case for document.cookie isolation.
- */
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" +
- "originattributes/test/browser/file_firstPartyBasic.html";
-
-// Use a random key so we don't access it in later tests.
-const key = "key" + Math.random().toString();
-const re = new RegExp(key + "=([0-9\.]+)");
-
-// Define the testing function
-function* doTest(aBrowser) {
- return yield ContentTask.spawn(aBrowser, {key, re},
- function ({key, re}) {
- let result = re.exec(content.document.cookie);
- if (result) {
- return result[1];
- }
- // No value is found, so we create one.
- let value = Math.random().toString();
- content.document.cookie = key + "=" + value;
- return value;
- });
-}
-
-registerCleanupFunction(() => {
- Services.cookies.removeAll();
-});
-
-IsolationTestTools.runTests(TEST_PAGE, doTest);
diff --git a/browser/components/originattributes/test/browser/browser_favicon_firstParty.js b/browser/components/originattributes/test/browser/browser_favicon_firstParty.js
deleted file mode 100644
index b3a18947b..000000000
--- a/browser/components/originattributes/test/browser/browser_favicon_firstParty.js
+++ /dev/null
@@ -1,343 +0,0 @@
-/**
- * Bug 1277803 - A test case for testing favicon loading across different first party domains.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-const FIRST_PARTY_ONE = "example.com";
-const FIRST_PARTY_TWO = "example.org";
-const THIRD_PARTY = "mochi.test:8888";
-
-const TEST_SITE_ONE = "http://" + FIRST_PARTY_ONE;
-const TEST_SITE_TWO = "http://" + FIRST_PARTY_TWO;
-const THIRD_PARTY_SITE = "http://" + THIRD_PARTY;
-const TEST_DIRECTORY = "/browser/browser/components/originattributes/test/browser/";
-
-const TEST_PAGE = TEST_DIRECTORY + "file_favicon.html";
-const TEST_THIRD_PARTY_PAGE = TEST_DIRECTORY + "file_favicon_thirdParty.html";
-const TEST_CACHE_PAGE = TEST_DIRECTORY + "file_favicon_cache.html";
-
-const FAVICON_URI = TEST_DIRECTORY + "file_favicon.png";
-const TEST_FAVICON_CACHE_URI = TEST_DIRECTORY + "file_favicon_cache.png";
-
-let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
-let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI;
-
-function clearAllImageCaches() {
- let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"]
- .getService(SpecialPowers.Ci.imgITools);
- let imageCache = tools.getImgCacheForDocument(window.document);
- imageCache.clearCache(true); // true=chrome
- imageCache.clearCache(false); // false=content
-}
-
-function clearAllPlacesFavicons() {
- let faviconService = Cc["@mozilla.org/browser/favicon-service;1"]
- .getService(Ci.nsIFaviconService);
-
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- if (aTopic === "places-favicons-expired") {
- resolve();
- Services.obs.removeObserver(observer, "places-favicons-expired", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "places-favicons-expired", false);
- faviconService.expireAllFavicons();
- });
-}
-
-function observeFavicon(aFirstPartyDomain, aExpectedCookie, aPageURI) {
- let faviconReqXUL = false;
- let faviconReqPlaces = false;
- let expectedPrincipal = Services.scriptSecurityManager
- .createCodebasePrincipal(aPageURI, { firstPartyDomain: aFirstPartyDomain });
-
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- // Make sure that the topic is 'http-on-modify-request'.
- if (aTopic === "http-on-modify-request") {
- // We check the firstPartyDomain for the originAttributes of the loading
- // channel. All requests for the favicon should contain the correct
- // firstPartyDomain. There are two requests for a favicon loading, one
- // from the Places library and one from the XUL image. The difference
- // of them is the loading principal. The Places will use the content
- // principal and the XUL image will use the system principal.
-
- let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
- let reqLoadInfo = httpChannel.loadInfo;
- let loadingPrincipal = reqLoadInfo.loadingPrincipal;
- let triggeringPrincipal = reqLoadInfo.triggeringPrincipal;
-
- // Make sure this is a favicon request.
- if (!httpChannel.URI.spec.endsWith(FAVICON_URI)) {
- return;
- }
-
- // Check the first party domain.
- is(reqLoadInfo.originAttributes.firstPartyDomain, aFirstPartyDomain,
- "The loadInfo has correct first party domain");
-
- if (loadingPrincipal.equals(systemPrincipal)) {
- faviconReqXUL = true;
- ok(triggeringPrincipal.equals(expectedPrincipal),
- "The triggeringPrincipal of favicon loading from XUL should be the content principal.");
- } else {
- faviconReqPlaces = true;
- ok(loadingPrincipal.equals(expectedPrincipal),
- "The loadingPrincipal of favicon loading from Places should be the content prinicpal");
- }
-
- let faviconCookie = httpChannel.getRequestHeader("cookie");
-
- is(faviconCookie, aExpectedCookie, "The cookie of the favicon loading is correct.");
- } else {
- ok(false, "Received unexpected topic: ", aTopic);
- }
-
- if (faviconReqXUL && faviconReqPlaces) {
- Services.obs.removeObserver(observer, "http-on-modify-request", false);
- resolve();
- }
- }
- };
-
- Services.obs.addObserver(observer, "http-on-modify-request", false);
- });
-}
-
-function waitOnFaviconResponse(aFaviconURL) {
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- if (aTopic === "http-on-examine-response" ||
- aTopic === "http-on-examine-cached-response") {
-
- let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
- let loadInfo = httpChannel.loadInfo;
-
- if (httpChannel.URI.spec !== aFaviconURL) {
- return;
- }
-
- let result = {
- topic: aTopic,
- firstPartyDomain: loadInfo.originAttributes.firstPartyDomain
- };
-
- resolve(result);
- Services.obs.removeObserver(observer, "http-on-examine-response", false);
- Services.obs.removeObserver(observer, "http-on-examine-cached-response", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "http-on-examine-response", false);
- Services.obs.addObserver(observer, "http-on-examine-cached-response", false);
- });
-}
-
-function waitOnFaviconLoaded(aFaviconURL) {
- return new Promise(resolve => {
- let observer = {
- onPageChanged(uri, attr, value, id) {
-
- if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON &&
- value === aFaviconURL) {
- resolve();
- PlacesUtils.history.removeObserver(observer, false);
- }
- },
- };
-
- PlacesUtils.history.addObserver(observer, false);
- });
-}
-
-function* openTab(aURL) {
- let tab = gBrowser.addTab(aURL);
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-function* assignCookiesUnderFirstParty(aURL, aFirstParty, aCookieValue) {
- // Open a tab under the given aFirstParty, and this tab will have an
- // iframe which loads the aURL.
- let tabInfo = yield openTabInFirstParty(aURL, aFirstParty);
-
- // Add cookies into the iframe.
- yield ContentTask.spawn(tabInfo.browser, aCookieValue, function* (value) {
- content.document.cookie = value;
- });
-
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-}
-
-function* generateCookies(aThirdParty) {
- // we generate two different cookies for two first party domains.
- let cookies = [];
- cookies.push(Math.random().toString());
- cookies.push(Math.random().toString());
-
- let firstSiteURL;
- let secondSiteURL;
-
- if (aThirdParty) {
- // Add cookies into the third party site with different first party domain.
- firstSiteURL = THIRD_PARTY_SITE;
- secondSiteURL = THIRD_PARTY_SITE;
- } else {
- // Add cookies into sites.
- firstSiteURL = TEST_SITE_ONE;
- secondSiteURL = TEST_SITE_TWO;
- }
-
- yield assignCookiesUnderFirstParty(firstSiteURL, TEST_SITE_ONE, cookies[0]);
- yield assignCookiesUnderFirstParty(secondSiteURL, TEST_SITE_TWO, cookies[1]);
-
- return cookies;
-}
-
-function* doTest(aTestPage, aExpectedCookies, aFaviconURL) {
- let firstPageURI = makeURI(TEST_SITE_ONE + aTestPage);
- let secondPageURI = makeURI(TEST_SITE_TWO + aTestPage);
-
- // Start to observe the event of that favicon has been fully loaded.
- let promiseFaviconLoaded = waitOnFaviconLoaded(aFaviconURL);
-
- // Start to observe the favicon requests earlier in case we miss it.
- let promiseObserveFavicon = observeFavicon(FIRST_PARTY_ONE, aExpectedCookies[0], firstPageURI);
-
- // Open the tab for the first site.
- let tabInfo = yield openTab(TEST_SITE_ONE + aTestPage);
-
- // Waiting until favicon requests are all made.
- yield promiseObserveFavicon;
-
- // Waiting until favicon loaded.
- yield promiseFaviconLoaded;
-
- // Close the tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-
- // Start to observe the favicon requests earlier in case we miss it.
- promiseObserveFavicon = observeFavicon(FIRST_PARTY_TWO, aExpectedCookies[1], secondPageURI);
-
- // Open the tab for the second site.
- tabInfo = yield openTab(TEST_SITE_TWO + aTestPage);
-
- // Waiting until favicon requests are all made.
- yield promiseObserveFavicon;
-
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-}
-
-add_task(function* setup() {
- // Make sure first party isolation is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- ["privacy.firstparty.isolate", true]
- ]});
-});
-
-// A clean up function to prevent affecting other tests.
-registerCleanupFunction(() => {
- // Clear all cookies.
- let cookieMgr = Cc["@mozilla.org/cookiemanager;1"]
- .getService(Ci.nsICookieManager);
- cookieMgr.removeAll();
-
- // Clear all image caches and network caches.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-});
-
-add_task(function* test_favicon_firstParty() {
- for (let testThirdParty of [false, true]) {
- // Clear all image caches and network caches before running the test.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Clear Places favicon caches.
- yield clearAllPlacesFavicons();
-
- let cookies = yield generateCookies(testThirdParty);
-
- if (testThirdParty) {
- yield doTest(TEST_THIRD_PARTY_PAGE, cookies, THIRD_PARTY_SITE + FAVICON_URI);
- } else {
- yield doTest(TEST_PAGE, cookies, TEST_SITE_ONE + FAVICON_URI);
- }
- }
-});
-
-add_task(function* test_favicon_cache_firstParty() {
- // Clear all image caches and network caches before running the test.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Start to observer the event of that favicon has been fully loaded and cached.
- let promiseForFaviconLoaded = waitOnFaviconLoaded(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI);
-
- // Start to observer for the favicon response of the first tab.
- let responsePromise = waitOnFaviconResponse(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI);
-
- // Open the tab for the first site.
- let tabInfoA = yield openTab(TEST_SITE_ONE + TEST_CACHE_PAGE);
-
- // Waiting for the favicon response.
- let response = yield responsePromise;
-
- // Make sure the favicon is loaded through the network and its first party domain is correct.
- is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network.");
- is(response.firstPartyDomain, FIRST_PARTY_ONE, "We should only observe the network response for the first first party.");
-
- // Waiting until the favicon has been loaded and cached.
- yield promiseForFaviconLoaded;
-
- // Open the tab again for checking the image cache is working correctly.
- let tabInfoB = yield openTab(TEST_SITE_ONE + TEST_CACHE_PAGE);
-
- // Start to observe the favicon response, the second tab actually will not
- // make any network request since the favicon will be loaded by the cache for
- // both Places and XUL image. So here, we are going to observe the favicon
- // response for the third tab which opens with the second first party.
- let promiseForFaviconResponse = waitOnFaviconResponse(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI);
-
- // Open the tab for the second site.
- let tabInfoC = yield openTab(TEST_SITE_TWO + TEST_CACHE_PAGE);
-
- // Wait for the favicon response. In this case, we suppose to catch the
- // response for the third tab but not the second tab since it will not
- // go through the network.
- response = yield promiseForFaviconResponse;
-
- // Check that the favicon response has came from the network and it has the
- // correct first party domain.
- is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network again.");
- is(response.firstPartyDomain, FIRST_PARTY_TWO, "We should only observe the network response for the second first party.");
-
- yield BrowserTestUtils.removeTab(tabInfoA.tab);
- yield BrowserTestUtils.removeTab(tabInfoB.tab);
- yield BrowserTestUtils.removeTab(tabInfoC.tab);
-});
diff --git a/browser/components/originattributes/test/browser/browser_favicon_userContextId.js b/browser/components/originattributes/test/browser/browser_favicon_userContextId.js
deleted file mode 100644
index 507e0a6d4..000000000
--- a/browser/components/originattributes/test/browser/browser_favicon_userContextId.js
+++ /dev/null
@@ -1,257 +0,0 @@
-/**
- * Bug 1277803 - A test caes for testing favicon loading across different userContextId.
- */
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-
-const TEST_SITE = "http://example.net";
-const TEST_THIRD_PARTY_SITE = "http://mochi.test:8888";
-
-const TEST_PAGE = TEST_SITE + "/browser/browser/components/originattributes/" +
- "test/browser/file_favicon.html";
-const FAVICON_URI = TEST_SITE + "/browser/browser/components/originattributes/" +
- "test/browser/file_favicon.png";
-const TEST_THIRD_PARTY_PAGE = "http://example.com/browser/browser/components/" +
- "originattributes/test/browser/file_favicon_thirdParty.html";
-const THIRD_PARTY_FAVICON_URI = TEST_THIRD_PARTY_SITE + "/browser/browser/components/" +
- "originattributes/test/browser/file_favicon.png";
-
-const USER_CONTEXT_ID_PERSONAL = 1;
-const USER_CONTEXT_ID_WORK = 2;
-
-let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
-let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI;
-
-function clearAllImageCaches() {
- var tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"]
- .getService(SpecialPowers.Ci.imgITools);
- var imageCache = tools.getImgCacheForDocument(window.document);
- imageCache.clearCache(true); // true=chrome
- imageCache.clearCache(false); // false=content
-}
-
-function clearAllPlacesFavicons() {
- let faviconService = Cc["@mozilla.org/browser/favicon-service;1"]
- .getService(Ci.nsIFaviconService);
-
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- if (aTopic === "places-favicons-expired") {
- resolve();
- Services.obs.removeObserver(observer, "places-favicons-expired", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "places-favicons-expired", false);
- faviconService.expireAllFavicons();
- });
-}
-
-function FaviconObserver(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL) {
- this.reset(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL);
-}
-
-FaviconObserver.prototype = {
- observe(aSubject, aTopic, aData) {
- // Make sure that the topic is 'http-on-modify-request'.
- if (aTopic === "http-on-modify-request") {
- // We check the userContextId for the originAttributes of the loading
- // channel. All requests for the favicon should contain the correct
- // userContextId. There are two requests for a favicon loading, one
- // from the Places library and one from the XUL image. The difference
- // of them is the loading principal. The Places will use the content
- // principal and the XUL image will use the system principal.
-
- let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
- let reqLoadInfo = httpChannel.loadInfo;
- let loadingPrincipal;
- let triggeringPrincipal;
-
- // Make sure this is a favicon request.
- if (httpChannel.URI.spec !== this._faviconURL) {
- return;
- }
-
- if (reqLoadInfo) {
- loadingPrincipal = reqLoadInfo.loadingPrincipal;
- triggeringPrincipal = reqLoadInfo.triggeringPrincipal;
- }
-
- // Check the userContextId.
- is(reqLoadInfo.originAttributes.userContextId, this._curUserContextId,
- "The loadInfo has correct userContextId");
-
- if (loadingPrincipal.equals(systemPrincipal)) {
- this._faviconReqXUL = true;
- ok(triggeringPrincipal.equals(this._expectedPrincipal),
- "The triggeringPrincipal of favicon loading from XUL should be the content principal.");
- } else {
- this._faviconReqPlaces = true;
- ok(loadingPrincipal.equals(this._expectedPrincipal),
- "The loadingPrincipal of favicon loading from Places should be the content prinicpal");
- }
-
- let faviconCookie = httpChannel.getRequestHeader("cookie");
-
- is(faviconCookie, this._expectedCookie, "The cookie of the favicon loading is correct.");
- } else {
- ok(false, "Received unexpected topic: ", aTopic);
- }
-
- if (this._faviconReqXUL && this._faviconReqPlaces) {
- this._faviconLoaded.resolve();
- }
- },
-
- reset(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL) {
- this._curUserContextId = aUserContextId;
- this._expectedCookie = aExpectedCookie;
- this._expectedPrincipal = Services.scriptSecurityManager
- .createCodebasePrincipal(aPageURI, { userContextId: aUserContextId });
- this._faviconReqXUL = false;
- this._faviconReqPlaces = false;
- this._faviconURL = aFaviconURL;
- this._faviconLoaded = new Promise.defer();
- },
-
- get promise() {
- return this._faviconLoaded.promise;
- }
-};
-
-function waitOnFaviconLoaded(aFaviconURL) {
- return new Promise(resolve => {
- let observer = {
- onPageChanged(uri, attr, value, id) {
-
- if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON &&
- value === aFaviconURL) {
- resolve();
- PlacesUtils.history.removeObserver(observer, false);
- }
- },
- };
-
- PlacesUtils.history.addObserver(observer, false);
- });
-}
-
-function* generateCookies(aHost) {
- // we generate two different cookies for two userContextIds.
- let cookies = [];
- cookies.push(Math.random().toString());
- cookies.push(Math.random().toString());
-
- // Then, we add cookies into the site for 'personal' and 'work'.
- let tabInfoA = yield openTabInUserContext(aHost, USER_CONTEXT_ID_PERSONAL);
- let tabInfoB = yield openTabInUserContext(aHost, USER_CONTEXT_ID_WORK);
-
- yield ContentTask.spawn(tabInfoA.browser, cookies[0], function* (value) {
- content.document.cookie = value;
- });
-
- yield ContentTask.spawn(tabInfoB.browser, cookies[1], function* (value) {
- content.document.cookie = value;
- });
-
- yield BrowserTestUtils.removeTab(tabInfoA.tab);
- yield BrowserTestUtils.removeTab(tabInfoB.tab);
-
- return cookies;
-}
-
-function* doTest(aTestPage, aFaviconHost, aFaviconURL) {
- let cookies = yield generateCookies(aFaviconHost);
- let pageURI = makeURI(aTestPage);
-
- // Create the observer object for observing request channels of the personal
- // container.
- let observer = new FaviconObserver(USER_CONTEXT_ID_PERSONAL, cookies[0], pageURI, aFaviconURL);
-
- // Add the observer earlier in case we miss it.
- let promiseWaitOnFaviconLoaded = waitOnFaviconLoaded(aFaviconURL);
-
- Services.obs.addObserver(observer, "http-on-modify-request", false);
-
- // Open the tab with the personal container.
- let tabInfo = yield openTabInUserContext(aTestPage, USER_CONTEXT_ID_PERSONAL);
-
- // Waiting for favicon requests are all made.
- yield observer.promise;
- // Waiting for favicon loaded.
- yield promiseWaitOnFaviconLoaded;
-
- // Close the tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-
- // Reset the observer for observing requests for the work container.
- observer.reset(USER_CONTEXT_ID_WORK, cookies[1], pageURI, aFaviconURL);
- tabInfo = yield openTabInUserContext(aTestPage, USER_CONTEXT_ID_WORK);
-
- // Waiting for favicon requests are all made.
- yield observer.promise;
-
- Services.obs.removeObserver(observer, "http-on-modify-request", false);
-
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-}
-
-add_task(function* setup() {
- // Make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({"set": [
- ["privacy.userContext.enabled", true]
- ]});
-});
-
-// A clean up function to prevent affecting other tests.
-registerCleanupFunction(() => {
- // Clear all cookies.
- let cookieMgr = Cc["@mozilla.org/cookiemanager;1"]
- .getService(Ci.nsICookieManager);
- cookieMgr.removeAll();
-
- // Clear all image caches and network caches.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Clear Places favicon caches.
- clearAllPlacesFavicons();
-});
-
-add_task(function* test_favicon_userContextId() {
- // Clear all image caches before running the test.
- clearAllImageCaches();
-
- // Clear all network caches.
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Clear Places favicon caches.
- yield clearAllPlacesFavicons();
-
- yield doTest(TEST_PAGE, TEST_SITE, FAVICON_URI);
-});
-
-add_task(function* test_thirdPartyFavicon_userContextId() {
- // Clear all image caches before running the test.
- clearAllImageCaches();
-
- // Clear all network caches.
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Clear Places favicon caches.
- yield clearAllPlacesFavicons();
-
- yield doTest(TEST_THIRD_PARTY_PAGE, TEST_THIRD_PARTY_SITE, THIRD_PARTY_FAVICON_URI);
-});
diff --git a/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js b/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js
deleted file mode 100644
index ddda6afae..000000000
--- a/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js
+++ /dev/null
@@ -1,174 +0,0 @@
-const BASE_URL = "http://mochi.test:8888/browser/browser/components/originattributes/test/browser/";
-const BASE_DOMAIN = "mochi.test";
-
-add_task(function* setup() {
- Services.prefs.setBoolPref("privacy.firstparty.isolate", true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("privacy.firstparty.isolate");
- });
-});
-
-/**
- * Test for the top-level document and child iframes should have the
- * firstPartyDomain attribute.
- */
-add_task(function* principal_test() {
- let tab = gBrowser.addTab(BASE_URL + "test_firstParty.html");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) {
- return url == BASE_URL + "test_firstParty.html";
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: BASE_DOMAIN }, function* (attrs) {
- info("document principal: " + content.document.nodePrincipal.origin);
- Assert.equal(docShell.getOriginAttributes().firstPartyDomain, "",
- "top-level docShell shouldn't have firstPartyDomain attribute.");
- Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "The document should have firstPartyDomain");
-
- for (let i = 1; i < 4; i++) {
- let iframe = content.document.getElementById("iframe" + i);
- info("iframe principal: " + iframe.contentDocument.nodePrincipal.origin);
- Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain,
- attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain");
- Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "iframe should have firstPartyDomain");
- }
- });
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * Test for the cookie jars of the top-level document and child iframe should be
- * isolated by firstPartyDomain.
- */
-add_task(function* cookie_test() {
- let tab = gBrowser.addTab(BASE_URL + "test_firstParty_cookie.html");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true);
-
- let iter = Services.cookies.enumerator;
- let count = 0;
- while (iter.hasMoreElements()) {
- count++;
- let cookie = iter.getNext().QueryInterface(Ci.nsICookie2);
- Assert.equal(cookie.value, "foo", "Cookie value should be foo");
- Assert.equal(cookie.originAttributes.firstPartyDomain, BASE_DOMAIN, "Cookie's origin attributes should be " + BASE_DOMAIN);
- }
-
- // one cookie is from requesting test.js from top-level doc, and the other from
- // requesting test2.js from iframe test2.html.
- Assert.equal(count, 2, "Should have two cookies");
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * Test for after redirect, the top-level document should update the firstPartyDomain
- * attribute. However if the redirect is happening on the iframe, the attribute
- * should remain the same.
- */
-add_task(function* redirect_test() {
- let tab = gBrowser.addTab(BASE_URL + "test_firstParty_http_redirect.html");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) {
- info("document principal: " + content.document.nodePrincipal.origin);
- info("document uri: " + content.document.documentURI);
-
- Assert.equal(content.document.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html",
- "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html");
- Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "The document should have firstPartyDomain");
- });
-
- // Since this is a HTML redirect, we wait until the final page is loaded.
- let tab2 = gBrowser.addTab(BASE_URL + "test_firstParty_html_redirect.html");
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser, false, function(url) {
- return url == "http://example.com/";
- });
-
- yield ContentTask.spawn(tab2.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) {
- info("2nd tab document principal: " + content.document.nodePrincipal.origin);
- info("2nd tab document uri: " + content.document.documentURI);
- Assert.equal(content.document.documentURI, "http://example.com/",
- "The page should have been redirected to http://example.com");
- Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "The document should have firstPartyDomain");
- });
-
- let tab3 = gBrowser.addTab(BASE_URL + "test_firstParty_iframe_http_redirect.html");
- yield BrowserTestUtils.browserLoaded(tab3.linkedBrowser, true, function(url) {
- return url == (BASE_URL + "test_firstParty_iframe_http_redirect.html");
- });
-
- // This redirect happens on the iframe, so unlike the two redirect tests above,
- // the firstPartyDomain should still stick to the current top-level document,
- // which is mochi.test.
- yield ContentTask.spawn(tab3.linkedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) {
- let iframe = content.document.getElementById("iframe1");
- info("iframe document principal: " + iframe.contentDocument.nodePrincipal.origin);
- info("iframe document uri: " + iframe.contentDocument.documentURI);
-
- Assert.equal(iframe.contentDocument.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html",
- "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html");
- Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "The iframe should have firstPartyDomain: " + attrs.firstPartyDomain);
- });
-
- gBrowser.removeTab(tab);
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab3);
-});
-
-/**
- * Test for postMessage between document and iframe.
- */
-add_task(function* postMessage_test() {
- let tab = gBrowser.addTab(BASE_URL + "test_firstParty_postMessage.html");
-
- // The top-level page will post a message to its child iframe, and wait for
- // another message from the iframe, once it receives the message, it will
- // create another iframe, dummy.html.
- // So we wait until dummy.html is loaded
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) {
- return url == BASE_URL + "dummy.html";
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, {}, function* () {
- info("document principal: " + content.document.nodePrincipal.origin);
- let value = content.document.getElementById("message").textContent;
- Assert.equal(value, "OK");
- });
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * When the web page calls window.open, the new window should have the same
- * firstPartyDomain attribute.
- */
-add_task(function* openWindow_test() {
- Services.prefs.setIntPref("browser.link.open_newwindow", 2);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.link.open_newwindow");
- });
-
- let tab = gBrowser.addTab(BASE_URL + "window.html");
- let win = yield BrowserTestUtils.waitForNewWindow();
-
- yield ContentTask.spawn(win.gBrowser.selectedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) {
- Assert.equal(docShell.getOriginAttributes().firstPartyDomain, attrs.firstPartyDomain,
- "window.open() should have firstPartyDomain attribute");
- Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "The document should have firstPartyDomain");
-
- let iframe = content.document.getElementById("iframe1");
- Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain,
- attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain");
- Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
- attrs.firstPartyDomain, "iframe should have firstPartyDomain");
- });
-
- gBrowser.removeTab(tab);
- yield BrowserTestUtils.closeWindow(win);
-});
-
diff --git a/browser/components/originattributes/test/browser/browser_httpauth.js b/browser/components/originattributes/test/browser/browser_httpauth.js
deleted file mode 100644
index 0b7b1540e..000000000
--- a/browser/components/originattributes/test/browser/browser_httpauth.js
+++ /dev/null
@@ -1,54 +0,0 @@
-let Cu = Components.utils;
-let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
-
-let server = new HttpServer();
-server.registerPathHandler('/file.html', fileHandler);
-server.start(-1);
-
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let FILE_URI = BASE_URI + '/file.html';
-
-let credentialQueue = [];
-
-// Ask the user agent for authorization.
-function fileHandler(metadata, response) {
- if (!metadata.hasHeader("Authorization")) {
- response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
- response.setHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
- return;
- }
-
- // This will be "account:password" encoded in base64.
- credentialQueue.push(metadata.getHeader("Authorization"));
-
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "text/html", false);
- let body = "<html><body></body></html>";
- response.bodyOutputStream.write(body, body.length);
-}
-
-function onCommonDialogLoaded(subject) {
- // Submit random account and password
- let dialog = subject.Dialog;
- dialog.ui.loginTextbox.setAttribute("value", Math.random());
- dialog.ui.password1Textbox.setAttribute("value", Math.random());
- dialog.ui.button0.click();
-}
-
-Services.obs.addObserver(onCommonDialogLoaded, "common-dialog-loaded", false);
-
-registerCleanupFunction(() => {
- Services.obs.removeObserver(onCommonDialogLoaded, "common-dialog-loaded");
- server.stop(() => {
- server = null;
- });
-});
-
-function getResult() {
- // If two targets are isolated, they should get different credentials.
- // Otherwise, the credentials will be cached and therefore the same.
- return credentialQueue.shift();
-}
-
-IsolationTestTools.runTests(FILE_URI, getResult);
-
diff --git a/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js b/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js
deleted file mode 100644
index a24cec9ac..000000000
--- a/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Bug 1264572 - A test case for image cache isolation.
- */
-
-requestLongerTimeout(2);
-
-let Cu = Components.utils;
-let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
-
-const NUM_ISOLATION_LOADS = 2;
-const NUM_CACHED_LOADS = 1;
-
-let gHits = 0;
-
-let server = new HttpServer();
-server.registerPathHandler('/image.png', imageHandler);
-server.registerPathHandler('/file.html', fileHandler);
-server.start(-1);
-
-registerCleanupFunction(() => {
- server.stop(() => {
- server = null;
- });
-});
-
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let IMAGE_URI = BASE_URI + '/image.png';
-let FILE_URI = BASE_URI + '/file.html';
-
-function imageHandler(metadata, response) {
- info('XXX: loading image from server');
- gHits++;
- response.setHeader("Cache-Control", "max-age=10000", false);
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "image/png", false);
- var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII=";
- response.bodyOutputStream.write(body, body.length);
-}
-
-function fileHandler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "text/html", false);
- let body = `<html><body><image src=${IMAGE_URI}></body></html>`;
- response.bodyOutputStream.write(body, body.length);
-}
-
-function doBefore() {
- // reset hit counter
- info('XXX resetting gHits');
- gHits = 0;
- info('XXX clearing image cache');
- let imageCache = Cc["@mozilla.org/image/tools;1"]
- .getService(Ci.imgITools)
- .getImgCacheForDocument(null);
- imageCache.clearCache(true);
- imageCache.clearCache(false);
- info('XXX clearning network cache');
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-}
-
-// the test function does nothing on purpose.
-function doTest(aBrowser) {
- return 0;
-}
-
-// the check function
-function doCheck(shouldIsolate, a, b) {
- // if we're doing first party isolation and the image cache isolation is
- // working, then gHits should be 2 because the image would have been loaded
- // one per first party domain. if first party isolation is disabled, then
- // gHits should be 1 since there would be one image load from the server and
- // one load from the image cache.
- info(`XXX check: gHits == ${gHits}, shouldIsolate == ${shouldIsolate}`);
- return shouldIsolate ? gHits == NUM_ISOLATION_LOADS
- : gHits == NUM_CACHED_LOADS;
-}
-
-IsolationTestTools.runTests(FILE_URI, doTest, doCheck, doBefore);
diff --git a/browser/components/originattributes/test/browser/browser_localStorageIsolation.js b/browser/components/originattributes/test/browser/browser_localStorageIsolation.js
deleted file mode 100644
index 41bde80e4..000000000
--- a/browser/components/originattributes/test/browser/browser_localStorageIsolation.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Bug 1264567 - A test case for localStorage isolation.
- */
-
-const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" +
- "originattributes/test/browser/file_firstPartyBasic.html";
-
-// Use a random key so we don't access it in later tests.
-const key = Math.random().toString();
-
-// Define the testing function
-function* doTest(aBrowser) {
- return yield ContentTask.spawn(aBrowser, key, function (key) {
- let value = content.localStorage.getItem(key);
- if (value === null) {
- // No value is found, so we create one.
- value = Math.random().toString();
- content.localStorage.setItem(key, value);
- }
- return value;
- });
-}
-
-IsolationTestTools.runTests(TEST_PAGE, doTest);
diff --git a/browser/components/originattributes/test/browser/browser_sharedworker.js b/browser/components/originattributes/test/browser/browser_sharedworker.js
deleted file mode 100644
index 7049407f6..000000000
--- a/browser/components/originattributes/test/browser/browser_sharedworker.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Bug 1264593 - A test case for the shared worker by first party isolation.
- */
-
-const TEST_DOMAIN = "http://example.net/";
-const TEST_PATH = TEST_DOMAIN + "browser/browser/components/originattributes/test/browser/";
-const TEST_PAGE = TEST_PATH + "file_sharedworker.html";
-
-function* getResultFromSharedworker(aBrowser) {
- let response = yield ContentTask.spawn(aBrowser, null, function* () {
- let worker = new content.SharedWorker("file_sharedworker.js", "isolationSharedWorkerTest");
-
- let result = yield new Promise(resolve => {
- worker.port.onmessage = function (e) {
- content.document.getElementById("display").innerHTML = e.data;
- resolve(e.data);
- };
- });
-
- return result;
- });
-
- return response;
-}
-
-IsolationTestTools.runTests(TEST_PAGE, getResultFromSharedworker);
diff --git a/browser/components/originattributes/test/browser/dummy.html b/browser/components/originattributes/test/browser/dummy.html
deleted file mode 100644
index 1a87e2840..000000000
--- a/browser/components/originattributes/test/browser/dummy.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Dummy test page</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Dummy test page</p>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_broadcastChannel.html b/browser/components/originattributes/test/browser/file_broadcastChannel.html
deleted file mode 100644
index 14bd7a022..000000000
--- a/browser/components/originattributes/test/browser/file_broadcastChannel.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title>Page broadcast channel creator for first party isolation</title>
-</head>
-<body>
- <div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div>
- <iframe id="iframe" src="file_broadcastChanneliFrame.html"></iframe>>
-<script type="text/javascript;version=1.7">
-let bc = new BroadcastChannel("testBroadcastChannel");
-bc.onmessage = function (e) {
- document.getElementById("display").innerHTML = e.data;
-};
-</script>
-</body>
diff --git a/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html b/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html
deleted file mode 100644
index a2140e617..000000000
--- a/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title>Page broadcast channel responder for first party isolation</title>
-</head>
-<body>
- <div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div>
-<script type="text/javascript;version=1.7">
-let bc = new BroadcastChannel("testBroadcastChannel");
-bc.onmessage = function (e) {
- window.parent.postMessage(e.data, "*");
-};
-</script>
-</body>
diff --git a/browser/components/originattributes/test/browser/file_cache.html b/browser/components/originattributes/test/browser/file_cache.html
deleted file mode 100644
index 788ec899d..000000000
--- a/browser/components/originattributes/test/browser/file_cache.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<head>
- <link rel="stylesheet" type="text/css"
- href="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css">
- <link rel="preconnect" href="http://example.net">
-</head>
-<body>
-<div>file_cache.html</div>
-
-<iframe src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html">
-</iframe>
-
-<script src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js">
-</script>
-
-<img src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png">
-
-<embed src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png">
-
-<object data="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png"
- type="image/png"></object>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_favicon.html b/browser/components/originattributes/test/browser/file_favicon.html
deleted file mode 100644
index b571134e1..000000000
--- a/browser/components/originattributes/test/browser/file_favicon.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <meta charset='utf-8'>
- <title>Favicon Test for originAttributes</title>
- <link rel="icon" type="image/png" href="file_favicon.png" />
- </head>
- <body>
- Favicon!!
- </body>
-</html> \ No newline at end of file
diff --git a/browser/components/originattributes/test/browser/file_favicon.png b/browser/components/originattributes/test/browser/file_favicon.png
deleted file mode 100644
index 5535363c9..000000000
--- a/browser/components/originattributes/test/browser/file_favicon.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_favicon.png^headers^ b/browser/components/originattributes/test/browser/file_favicon.png^headers^
deleted file mode 100644
index 9e23c73b7..000000000
--- a/browser/components/originattributes/test/browser/file_favicon.png^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Cache-Control: no-cache
diff --git a/browser/components/originattributes/test/browser/file_favicon_cache.html b/browser/components/originattributes/test/browser/file_favicon_cache.html
deleted file mode 100644
index 2a7343b8e..000000000
--- a/browser/components/originattributes/test/browser/file_favicon_cache.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <meta charset='utf-8'>
- <title>Favicon Test for originAttributes</title>
- <link rel="icon" type="image/png" href="http://mochi.test:8888/browser/browser/components/originattributes/test/browser/file_favicon_cache.png" />
- </head>
- <body>
- Third Party Favicon!!
- </body>
-</html> \ No newline at end of file
diff --git a/browser/components/originattributes/test/browser/file_favicon_cache.png b/browser/components/originattributes/test/browser/file_favicon_cache.png
deleted file mode 100644
index 5535363c9..000000000
--- a/browser/components/originattributes/test/browser/file_favicon_cache.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_favicon_thirdParty.html b/browser/components/originattributes/test/browser/file_favicon_thirdParty.html
deleted file mode 100644
index 4a2dd680a..000000000
--- a/browser/components/originattributes/test/browser/file_favicon_thirdParty.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <meta charset='utf-8'>
- <title>Favicon Test for originAttributes</title>
- <link rel="icon" type="image/png" href="http://mochi.test:8888/browser/browser/components/originattributes/test/browser/file_favicon.png" />
- </head>
- <body>
- Third Party Favicon!!
- </body>
-</html> \ No newline at end of file
diff --git a/browser/components/originattributes/test/browser/file_firstPartyBasic.html b/browser/components/originattributes/test/browser/file_firstPartyBasic.html
deleted file mode 100644
index 713187fb2..000000000
--- a/browser/components/originattributes/test/browser/file_firstPartyBasic.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
- <head>
- <meta charset="UTF-8">
- <title>First Party Isolation Tests</title>
- </head>
- <body>
- </body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_sharedworker.html b/browser/components/originattributes/test/browser/file_sharedworker.html
deleted file mode 100644
index b9ff793bd..000000000
--- a/browser/components/originattributes/test/browser/file_sharedworker.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title>Page SharedWorker creator for first party isolation</title>
-</head>
-<body>
-<div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_sharedworker.js b/browser/components/originattributes/test/browser/file_sharedworker.js
deleted file mode 100644
index 82f075a37..000000000
--- a/browser/components/originattributes/test/browser/file_sharedworker.js
+++ /dev/null
@@ -1,9 +0,0 @@
-self.randomValue = Math.random();
-
-/* global onconnect:true */
-
-onconnect = function (e) {
- let port = e.ports[0];
- port.postMessage(self.randomValue);
- port.start();
-};
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg b/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg
deleted file mode 100644
index edda4e912..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png
deleted file mode 100644
index c5916f289..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html
deleted file mode 100644
index 037901ad0..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.fetch.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html
deleted file mode 100644
index b047d5b41..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.html</div>
-<script>
- var xhr = new XMLHttpRequest();
- xhr.open("GET", "http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html", true);
- xhr.send();
- var worker = new Worker("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js");
- var sharedWorker = new SharedWorker("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js");
-
- fetch("file_thirdPartyChild.fetch.html", {cache: "force-cache"} );
- fetch(new Request("file_thirdPartyChild.request.html"), {cache: "force-cache"} );
-</script>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png
deleted file mode 100644
index c5916f289..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js
deleted file mode 100644
index dbf8f8376..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js
+++ /dev/null
@@ -1 +0,0 @@
-// dummy script, to be called by self.importScripts(...)
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css b/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css
deleted file mode 100644
index 06d6e2672..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css
+++ /dev/null
@@ -1 +0,0 @@
-/* Dummy CSS file, used by browser_cache.js. */ \ No newline at end of file
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png
deleted file mode 100644
index c5916f289..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html
deleted file mode 100644
index 108ed2ffa..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.request.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js
deleted file mode 100644
index 6ddf436c0..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js
+++ /dev/null
@@ -1 +0,0 @@
-// Dummy child script, used by browser_cache.js
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js
deleted file mode 100644
index b262fa10a..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js
+++ /dev/null
@@ -1 +0,0 @@
-// dummy file
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt b/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt
deleted file mode 100644
index b37cb40e4..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt
+++ /dev/null
@@ -1,13 +0,0 @@
-WEBVTT FILE
-
-1
-00:00:00.500 --> 00:00:02.000 D:vertical A:start
-blah blah blah
-
-2
-00:00:02.500 --> 00:00:04.300
-this is a test
-
-3
-00:00:05.000 --> 00:00:07.000
-one more line
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv b/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv
deleted file mode 100644
index 68dee3cf2..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv
+++ /dev/null
Binary files differ
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html
deleted file mode 100644
index 47e42d1e5..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.worker.fetch.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js
deleted file mode 100644
index b04e2c7de..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js
+++ /dev/null
@@ -1,9 +0,0 @@
-var xhr = new XMLHttpRequest();
-xhr.open("GET", "http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html", true);
-xhr.send();
-
-fetch("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html", {cache: "force-cache"} );
-var myRequest = new Request("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html");
-fetch(myRequest, {cache: "force-cache"} );
-
-self.importScripts("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js");
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html
deleted file mode 100644
index 5b5c55bfe..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.worker.request.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html
deleted file mode 100644
index 9fc107f37..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.worker.xhr.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html
deleted file mode 100644
index f56e7b3c1..000000000
--- a/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
-<!-- The child page, used by browser_cache.js -->
-<body>
-<div>thirdPartyChild.html</div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/head.js b/browser/components/originattributes/test/browser/head.js
deleted file mode 100644
index 96559a10d..000000000
--- a/browser/components/originattributes/test/browser/head.js
+++ /dev/null
@@ -1,365 +0,0 @@
-/* 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/. */
-
-'use strict';
-
-const TEST_URL_PATH = "/browser/browser/components/originattributes/test/browser/";
-
-// The flags of test modes.
-const TEST_MODE_FIRSTPARTY = 0;
-const TEST_MODE_NO_ISOLATION = 1;
-const TEST_MODE_CONTAINERS = 2;
-
-// The name of each mode.
-const TEST_MODE_NAMES = [ "first party isolation",
- "no isolation",
- "containers" ];
-
-// The frame types.
-const TEST_TYPE_FRAME = 0;
-const TEST_TYPE_IFRAME = 1;
-
-// The default frame setting.
-const DEFAULT_FRAME_SETTING = [ TEST_TYPE_IFRAME ];
-
-let gFirstPartyBasicPage = TEST_URL_PATH + "file_firstPartyBasic.html";
-
-/**
- * Add a tab for the given url with the specific user context id.
- *
- * @param aURL
- * The url of the page.
- * @param aUserContextId
- * The user context id for this tab.
- *
- * @return tab - The tab object of this tab.
- * browser - The browser object of this tab.
- */
-function* openTabInUserContext(aURL, aUserContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab(aURL, {userContextId: aUserContextId});
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-/**
- * Add a tab for a page with the given first party domain. This page will have
- * an iframe which is loaded with the given url by default or you could specify
- * a frame setting to create nested frames. And this function will also modify
- * the 'content' in the ContentTask to the target frame's window object.
- *
- * @param aURL
- * The url of the iframe.
- * @param aFirstPartyDomain
- * The first party domain.
- * @param aFrameSetting
- * This setting controls how frames are organized within the page. The
- * setting is an array of frame types, the first item indicates the
- * frame type (iframe or frame) of the first layer of the frame structure,
- * and the second item indicates the second layer, and so on. The aURL will
- * be loaded at the deepest layer. This is optional.
- *
- * @return tab - The tab object of this tab.
- * browser - The browser object of this tab.
- */
-function* openTabInFirstParty(aURL, aFirstPartyDomain,
- aFrameSetting = DEFAULT_FRAME_SETTING) {
-
- // If the first party domain ends with '/', we remove it.
- if (aFirstPartyDomain.endsWith('/')) {
- aFirstPartyDomain = aFirstPartyDomain.slice(0, -1);
- }
-
- let basicPageURL = aFirstPartyDomain + gFirstPartyBasicPage;
-
- // Open the tab for the basic first party page.
- let tab = gBrowser.addTab(basicPageURL);
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
-
- let pageArgs = { url: aURL,
- frames: aFrameSetting,
- typeFrame: TEST_TYPE_FRAME,
- typeIFrame: TEST_TYPE_IFRAME,
- basicFrameSrc: basicPageURL};
-
- // Create the frame structure.
- yield ContentTask.spawn(browser, pageArgs, function* (arg) {
- let typeFrame = arg.typeFrame;
- let typeIFrame = arg.typeIFrame;
-
- // Redefine the 'content' for allowing us to change its target, and making
- // ContentTask.spawn can directly work on the frame element.
- this.frameWindow = content;
-
- Object.defineProperty(this, "content", {
- get: () => this.frameWindow
- });
-
- let frameElement;
- let numOfLayers = 0;
-
- for (let type of arg.frames) {
- let document = content.document;
- numOfLayers++;
-
- if (type === typeFrame) {
- // Add a frameset which carries the frame element.
- let frameSet = document.createElement('frameset');
- frameSet.cols = "50%,50%";
-
- let frame = document.createElement('frame');
- let dummyFrame = document.createElement('frame');
-
- frameSet.appendChild(frame);
- frameSet.appendChild(dummyFrame);
-
- document.body.appendChild(frameSet);
-
- frameElement = frame;
- } else if (type === typeIFrame) {
- // Add an iframe.
- let iframe = document.createElement('iframe');
- document.body.appendChild(iframe);
-
- frameElement = iframe;
- } else {
- ok(false, "Invalid frame type.");
- break;
- }
-
- // Wait for the frame to be loaded.
- yield new Promise(done => {
- frameElement.addEventListener("load", function loadEnd() {
- frameElement.removeEventListener("load", loadEnd, true);
- done();
- }, true);
-
- // If it is the deepest layer, we load the target URL. Otherwise, we
- // load a basic page.
- if (numOfLayers === arg.frames.length) {
- frameElement.setAttribute("src", arg.url);
- } else {
- frameElement.setAttribute("src", arg.basicFrameSrc);
- }
- });
-
- // Redirect the 'content' to the frame's window.
- this.frameWindow = frameElement.contentWindow;
- }
- });
-
- return {tab, browser};
-}
-
-this.IsolationTestTools = {
- /**
- * Adds isolation tests for first party isolation, no isolation
- * and containers respectively.
- *
- * @param aTask
- * The testing task which will be run in different settings.
- */
- _add_task(aTask) {
- add_task(function* addTaskForIsolationTests() {
- let testSettings = [
- { mode: TEST_MODE_FIRSTPARTY,
- skip: false,
- prefs: [["privacy.firstparty.isolate", true]]
- },
- { mode: TEST_MODE_NO_ISOLATION,
- skip: false,
- prefs: [["privacy.firstparty.isolate", false]]
- },
- { mode: TEST_MODE_CONTAINERS,
- skip: false,
- prefs: [["privacy.userContext.enabled", true]]
- },
- ];
-
- // Add test tasks.
- for (let testSetting of testSettings) {
- IsolationTestTools._addTaskForMode(testSetting.mode,
- testSetting.prefs,
- testSetting.skip,
- aTask);
- }
- });
- },
-
- _addTaskForMode(aMode, aPref, aSkip, aTask) {
- if (aSkip) {
- return;
- }
-
- add_task(function* () {
- info("Starting the test for " + TEST_MODE_NAMES[aMode]);
-
- // Before run this task, reset the preferences first.
- yield SpecialPowers.flushPrefEnv();
-
- // Make sure preferences are set properly.
- yield SpecialPowers.pushPrefEnv({"set": aPref});
-
- yield SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", 1]]});
-
- yield aTask(aMode);
- });
- },
-
- /**
- * Add a tab with the given tab setting, this will open different types of
- * tabs according to the given test mode. A tab setting means a isolation
- * target in different test mode; a tab setting indicates a first party
- * domain when testing the first party isolation, it is a user context
- * id when testing containers.
- *
- * @param aMode
- * The test mode which decides what type of tabs will be opened.
- * @param aURL
- * The url which is going to open.
- * @param aTabSettingObj
- * The tab setting object includes 'firstPartyDomain' for the first party
- * domain and 'userContextId' for Containers.
- * @param aFrameSetting
- * This setting controls how frames are organized within the page. The
- * setting is an array of frame types, the first item indicates the
- * frame type (iframe or frame) of the first layer of the frame structure,
- * and the second item indicates the second layer, and so on. The aURL
- * will be loaded at the deepest layer. This is optional.
- *
- * @return tab - The tab object of this tab.
- * browser - The browser object of this tab.
- */
- _addTab(aMode, aURL, aTabSettingObj, aFrameSetting) {
- if (aMode === TEST_MODE_CONTAINERS) {
- return openTabInUserContext(aURL, aTabSettingObj.userContextId);
- }
-
- return openTabInFirstParty(aURL, aTabSettingObj.firstPartyDomain,
- aFrameSetting);
-
- },
-
- /**
- * Run isolation tests. The framework will run tests with standard combinations
- * of prefs and tab settings, and checks whether the isolation is working.
- *
- * @param aURL
- * The URL of the page that will be tested or an object contains 'url',
- * the tested page, 'firstFrameSetting' for the frame setting of the first
- * tab, and 'secondFrameSetting' for the second tab.
- * @param aGetResultFuncs
- * An array of functions or a single function which are responsible for
- * returning the isolation result back to the framework for further checking.
- * Each of these functions will be provided the browser object of the tab,
- * that allows modifying or fetchings results from the page content.
- * @param aCompareResultFunc
- * An optional function which allows modifying the way how does framework
- * check results. This function will be provided a boolean to indicate
- * the isolation is no or off and two results. This function should return
- * a boolean to tell that whether isolation is working. If this function
- * is not given, the framework will take case checking by itself.
- * @param aBeforeFunc
- * An optional function which is called before any tabs are created so
- * that the test case can set up/reset local state.
- * @param aGetResultImmediately
- * An optional boolean to ensure we get results before the next tab is opened.
- */
- runTests(aURL, aGetResultFuncs, aCompareResultFunc, aBeforeFunc,
- aGetResultImmediately) {
- let pageURL;
- let firstFrameSetting;
- let secondFrameSetting;
-
- // Request a longer timeout since the test will run a test for three times
- // with different settings. Thus, one test here represents three tests.
- // For this reason, we triple the timeout.
- requestLongerTimeout(3);
-
- if (typeof aURL === "string") {
- pageURL = aURL;
- } else if (typeof aURL === "object") {
- pageURL = aURL.url;
- firstFrameSetting = aURL.firstFrameSetting;
- secondFrameSetting = aURL.secondFrameSetting;
- }
-
- if (!Array.isArray(aGetResultFuncs)) {
- aGetResultFuncs = [aGetResultFuncs];
- }
-
- let tabSettings = [
- { firstPartyDomain: "http://example.com", userContextId: 1},
- { firstPartyDomain: "http://example.org", userContextId: 2}
- ];
-
- this._add_task(function* (aMode) {
- let tabSettingA = 0;
-
- for (let tabSettingB of [0, 1]) {
- // Give the test a chance to set up before each case is run.
- if (aBeforeFunc) {
- yield aBeforeFunc(aMode);
- }
-
- // Create Tabs.
- let tabInfoA = yield IsolationTestTools._addTab(aMode,
- pageURL,
- tabSettings[tabSettingA],
- firstFrameSetting);
- let resultsA = [];
- if (aGetResultImmediately) {
- for (let getResultFunc of aGetResultFuncs) {
- resultsA.push(yield getResultFunc(tabInfoA.browser));
- }
- }
- let tabInfoB = yield IsolationTestTools._addTab(aMode,
- pageURL,
- tabSettings[tabSettingB],
- secondFrameSetting);
- let i = 0;
- for (let getResultFunc of aGetResultFuncs) {
- // Fetch results from tabs.
- let resultA = aGetResultImmediately ? resultsA[i++] :
- yield getResultFunc(tabInfoA.browser);
- let resultB = yield getResultFunc(tabInfoB.browser);
-
- // Compare results.
- let result = false;
- let shouldIsolate = (aMode !== TEST_MODE_NO_ISOLATION) &&
- tabSettingA !== tabSettingB;
- if (aCompareResultFunc) {
- result = yield aCompareResultFunc(shouldIsolate, resultA, resultB);
- } else {
- result = shouldIsolate ? resultA !== resultB :
- resultA === resultB;
- }
-
- let msg = `Testing ${TEST_MODE_NAMES[aMode]} for ` +
- `isolation ${shouldIsolate ? "on" : "off"} with TabSettingA ` +
- `${tabSettingA} and tabSettingB ${tabSettingB}` +
- `, resultA = ${resultA}, resultB = ${resultB}`;
-
- ok(result, msg);
- }
-
- // Close Tabs.
- yield BrowserTestUtils.removeTab(tabInfoA.tab);
- yield BrowserTestUtils.removeTab(tabInfoB.tab);
- }
- });
- }
-};
diff --git a/browser/components/originattributes/test/browser/test.html b/browser/components/originattributes/test/browser/test.html
deleted file mode 100644
index 214daa4b7..000000000
--- a/browser/components/originattributes/test/browser/test.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <script>
- window.onmessage = function (evt) {
- if (evt.data != "HI") {
- return;
- }
-
- window.parent.postMessage("OK", "http://mochi.test:8888");
- };
- </script>
-</head>
-<body>
- Hello World.
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test.js b/browser/components/originattributes/test/browser/test.js
deleted file mode 100644
index d290af9b0..000000000
--- a/browser/components/originattributes/test/browser/test.js
+++ /dev/null
@@ -1 +0,0 @@
-var i = 1;
diff --git a/browser/components/originattributes/test/browser/test.js^headers^ b/browser/components/originattributes/test/browser/test.js^headers^
deleted file mode 100644
index 881f5bff0..000000000
--- a/browser/components/originattributes/test/browser/test.js^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Set-Cookie: test=foo
diff --git a/browser/components/originattributes/test/browser/test2.html b/browser/components/originattributes/test/browser/test2.html
deleted file mode 100644
index 370be1560..000000000
--- a/browser/components/originattributes/test/browser/test2.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <script src="test2.js"></script>
-</head>
-<body>
- Hello World.
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test2.js b/browser/components/originattributes/test/browser/test2.js
deleted file mode 100644
index d290af9b0..000000000
--- a/browser/components/originattributes/test/browser/test2.js
+++ /dev/null
@@ -1 +0,0 @@
-var i = 1;
diff --git a/browser/components/originattributes/test/browser/test2.js^headers^ b/browser/components/originattributes/test/browser/test2.js^headers^
deleted file mode 100644
index 43604be7f..000000000
--- a/browser/components/originattributes/test/browser/test2.js^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Set-Cookie: test2=foo
diff --git a/browser/components/originattributes/test/browser/test_firstParty.html b/browser/components/originattributes/test/browser/test_firstParty.html
deleted file mode 100644
index a90e01c4c..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8"/>
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
- <div>
- <iframe id="iframe1" src="http://example.com"></iframe>
- <iframe id="iframe2" sandbox="" src="http://example.com"></iframe>
- <iframe id="iframe3" sandbox="allow-same-origin" src="http://example.com"></iframe>
- </div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test_firstParty_cookie.html b/browser/components/originattributes/test/browser/test_firstParty_cookie.html
deleted file mode 100644
index 44547c0d7..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_cookie.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <script src="test.js"></script>
-</head>
-<body>
- Hello World.
- <iframe id="iframe1" src="test2.html"></iframe>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html
deleted file mode 100644
index 3c52d4f8c..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf8" http-equiv="refresh" content="0; url=http://example.com/"/>
- <title>Test for Bug 1260931</title>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html
deleted file mode 100644
index 7b794a011..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8"/>
- <title>Test for Bug 1260931</title>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^ b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^
deleted file mode 100644
index c6d2757aa..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^
+++ /dev/null
@@ -1,2 +0,0 @@
-HTTP 302 Found
-Location: http://example.com/browser/browser/components/originattributes/test/browser/dummy.html
diff --git a/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html
deleted file mode 100644
index fd7df46c1..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8"/>
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
- <div>
- <iframe id="iframe1" src="test_firstParty_http_redirect.html"></iframe>
- </div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/test_firstParty_postMessage.html b/browser/components/originattributes/test/browser/test_firstParty_postMessage.html
deleted file mode 100644
index 5df8a5950..000000000
--- a/browser/components/originattributes/test/browser/test_firstParty_postMessage.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8"/>
- <title>Test for Bug 1260931</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<script>
-function onload() {
- let iframe1 = document.getElementById("iframe1");
- iframe1.contentWindow.postMessage("HI", "http://mochi.test:8888");
-}
-
-window.onmessage = function (evt) {
- document.getElementById("message").textContent = evt.data;
-
- let iframe2 = document.createElement("iframe");
- iframe2.src = "dummy.html";
- document.body.appendChild(iframe2);
-};
-</script>
-<body onload="onload()">
- <div>
- <iframe id="iframe1" src="test.html"></iframe>
- <span id="message"></span>
- </div>
-</body>
-</html>
diff --git a/browser/components/originattributes/test/browser/window.html b/browser/components/originattributes/test/browser/window.html
deleted file mode 100644
index 34216030c..000000000
--- a/browser/components/originattributes/test/browser/window.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <meta charset="utf8">
- <title>Page creating a popup</title>
- </head>
- <body>
- <script type="text/javascript">
- var w = window.open();
- w.document.body.innerHTML = "<iframe id='iframe1' src='data:text/plain,test2'></iframe>";
- </script>
- </body>
-</html>
diff --git a/browser/components/originattributes/test/browser/worker_blobify.js b/browser/components/originattributes/test/browser/worker_blobify.js
deleted file mode 100644
index 56c0996a3..000000000
--- a/browser/components/originattributes/test/browser/worker_blobify.js
+++ /dev/null
@@ -1,11 +0,0 @@
-// Wait for a string to be posted to this worker.
-// Create a blob containing this string, and then
-// post back a blob URL pointing to the blob.
-self.addEventListener("message", function (e) {
- try {
- var blobURL = URL.createObjectURL(new Blob([e.data]));
- postMessage({ blobURL });
- } catch (e) {
- postMessage({ error: e.message });
- }
-}, false);
diff --git a/browser/components/originattributes/test/browser/worker_deblobify.js b/browser/components/originattributes/test/browser/worker_deblobify.js
deleted file mode 100644
index 1d6511a20..000000000
--- a/browser/components/originattributes/test/browser/worker_deblobify.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// Wait for a blob URL to be posted to this worker.
-// Obtain the blob, and read the string contained in it.
-// Post back the string.
-
-var postStringInBlob = function (blobObject) {
- var fileReader = new FileReaderSync();
- var result = fileReader.readAsText(blobObject);
- postMessage(result);
-};
-
-self.addEventListener("message", function (e) {
- if ("error" in e.data) {
- postMessage(e.data);
- return;
- }
- var blobURL = e.data.blobURL,
- xhr = new XMLHttpRequest();
- try {
- xhr.open("GET", blobURL, true);
- xhr.onload = function () {
- postStringInBlob(xhr.response);
- };
- xhr.onerror = function () {
- postMessage({ error: "xhr error" });
- };
- xhr.responseType = "blob";
- xhr.send();
- } catch (e) {
- postMessage({ error: e.message });
- }
-}, false);
diff --git a/browser/components/originattributes/test/mochitest/file_empty.html b/browser/components/originattributes/test/mochitest/file_empty.html
deleted file mode 100644
index bc98b4d2e..000000000
--- a/browser/components/originattributes/test/mochitest/file_empty.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<h1>I'm just a support file</h1>
-<p>I get loaded to do permission testing.</p> \ No newline at end of file
diff --git a/browser/components/originattributes/test/mochitest/mochitest.ini b/browser/components/originattributes/test/mochitest/mochitest.ini
deleted file mode 100644
index 5df9998ca..000000000
--- a/browser/components/originattributes/test/mochitest/mochitest.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[DEFAULT]
-support-files =
- file_empty.html
-
-[test_permissions_api.html]
diff --git a/browser/components/originattributes/test/mochitest/test_permissions_api.html b/browser/components/originattributes/test/mochitest/test_permissions_api.html
deleted file mode 100644
index 63c74d1fe..000000000
--- a/browser/components/originattributes/test/mochitest/test_permissions_api.html
+++ /dev/null
@@ -1,207 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<!DOCTYPE HTML>
-<html>
-
-<head>
- <meta charset="utf-8">
- <title>Test for Permissions API</title>
- <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" href="/tests/SimpleTest/test.css">
-</head>
-
-<body>
- <pre id="test"></pre>
- <script type="application/javascript;version=1.8">
- /*globals SpecialPowers, SimpleTest, is, ok, */
- 'use strict';
-
- const {
- UNKNOWN_ACTION,
- PROMPT_ACTION,
- ALLOW_ACTION,
- DENY_ACTION
- } = SpecialPowers.Ci.nsIPermissionManager;
-
- SimpleTest.waitForExplicitFinish();
-
- const PERMISSIONS = [{
- name: 'geolocation',
- type: 'geo'
- }, {
- name: 'notifications',
- type: 'desktop-notification'
- }, {
- name: 'push',
- type: 'desktop-notification'
- }, ];
-
- const UNSUPPORTED_PERMISSIONS = [
- 'foobarbaz', // Not in spec, for testing only.
- 'midi',
- ];
-
- // Create a closure, so that tests are run on the correct window object.
- function createPermissionTester(aWindow) {
- return {
- setPermissions(allow) {
- const permissions = PERMISSIONS.map(({ type }) => {
- return {
- type,
- allow,
- 'context': aWindow.document
- };
- });
- return new Promise((resolve) => {
- SpecialPowers.popPermissions(() => {
- SpecialPowers.pushPermissions(permissions, resolve);
- });
- });
- },
- revokePermissions() {
- const promisesToRevoke = PERMISSIONS.map(({ name }) => {
- return aWindow.navigator.permissions
- .revoke({ name })
- .then(
- ({ state }) => is(state, 'prompt', `correct state for '${name}'`),
- () => ok(false, `revoke should not have rejected for '${name}'`)
- );
- });
- return Promise.all(promisesToRevoke);
- },
- revokeUnsupportedPermissions() {
- const promisesToRevoke = UNSUPPORTED_PERMISSIONS.map(({ name }) => {
- return aWindow.navigator.permissions
- .revoke({ name })
- .then(
- () => ok(false, `revoke should not have resolved for '${name}'`),
- error => is(error.name, 'TypeError', `revoke should have thrown TypeError for '${name}'`)
- );
- });
- return Promise.all(promisesToRevoke);
- },
- checkPermissions(state) {
- const promisesToQuery = PERMISSIONS.map(({ name }) => {
- return aWindow.navigator.permissions
- .query({ name })
- .then(
- () => is(state, state, `correct state for '${name}'`),
- () => ok(false, `query should not have rejected for '${name}'`)
- );
- });
- return Promise.all(promisesToQuery);
- },
- checkUnsupportedPermissions() {
- const promisesToQuery = UNSUPPORTED_PERMISSIONS.map(({ name }) => {
- return aWindow.navigator.permissions
- .query({ name })
- .then(
- () => ok(false, `query should not have resolved for '${name}'`),
- error => {
- is(error.name, 'TypeError',
- `query should have thrown TypeError for '${name}'`);
- }
- );
- });
- return Promise.all(promisesToQuery);
- },
- promiseStateChanged(name, state) {
- return aWindow.navigator.permissions
- .query({ name })
- .then(status => {
- return new Promise( resolve => {
- status.onchange = () => {
- status.onchange = null;
- is(status.state, state, `state changed for '${name}'`);
- resolve();
- };
- });
- },
- () => ok(false, `query should not have rejected for '${name}'`));
- },
- testStatusOnChange() {
- return new Promise((resolve) => {
- SpecialPowers.popPermissions(() => {
- const permission = 'geolocation';
- const promiseGranted = this.promiseStateChanged(permission, 'granted');
- this.setPermissions(ALLOW_ACTION);
- promiseGranted.then(() => {
- const promisePrompt = this.promiseStateChanged(permission, 'prompt');
- SpecialPowers.popPermissions();
- return promisePrompt;
- }).then(resolve);
- });
- });
- },
- testInvalidQuery() {
- return aWindow.navigator.permissions
- .query({ name: 'invalid' })
- .then(
- () => ok(false, 'invalid query should not have resolved'),
- () => ok(true, 'invalid query should have rejected')
- );
- },
- testInvalidRevoke() {
- return aWindow.navigator.permissions
- .revoke({ name: 'invalid' })
- .then(
- () => ok(false, 'invalid revoke should not have resolved'),
- () => ok(true, 'invalid revoke should have rejected')
- );
- },
- };
- }
-
- function enablePrefs() {
- const ops = {
- 'set': [
- ['dom.permissions.revoke.enable', true],
- ['privacy.firstparty.isolate', true],
- ],
- };
- return SpecialPowers.pushPrefEnv(ops);
- }
-
- function createIframe() {
- return new Promise((resolve) => {
- const iframe = document.createElement('iframe');
- iframe.src = 'file_empty.html';
- iframe.onload = () => resolve(iframe.contentWindow);
- document.body.appendChild(iframe);
- });
- }
- debugger;
- window.onload = () => {
- enablePrefs()
- .then(createIframe)
- .then(createPermissionTester)
- .then((tester) => {
- return tester
- .checkUnsupportedPermissions()
- .then(() => tester.setPermissions(UNKNOWN_ACTION))
- .then(() => tester.checkPermissions('prompt'))
- .then(() => tester.setPermissions(PROMPT_ACTION))
- .then(() => tester.checkPermissions('prompt'))
- .then(() => tester.setPermissions(ALLOW_ACTION))
- .then(() => tester.checkPermissions('granted'))
- .then(() => tester.setPermissions(DENY_ACTION))
- .then(() => tester.checkPermissions('denied'))
- .then(() => tester.testStatusOnChange())
- .then(() => tester.testInvalidQuery())
- .then(() => tester.revokeUnsupportedPermissions())
- .then(() => tester.revokePermissions())
- .then(() => tester.checkPermissions('prompt'))
- .then(() => tester.testInvalidRevoke());
- })
- .then(SimpleTest.finish)
- .catch((e) => {
- ok(false, `Unexpected error ${e}`);
- SimpleTest.finish();
- });
- };
- </script>
-</body>
-
-</html>
diff --git a/browser/components/places/tests/browser/.eslintrc.js b/browser/components/places/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/places/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/places/tests/browser/bookmark_dummy_1.html b/browser/components/places/tests/browser/bookmark_dummy_1.html
deleted file mode 100644
index c03e0c18c..000000000
--- a/browser/components/places/tests/browser/bookmark_dummy_1.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Bookmark Dummy 1</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Bookmark Dummy 1</p>
-</body>
-</html>
diff --git a/browser/components/places/tests/browser/bookmark_dummy_2.html b/browser/components/places/tests/browser/bookmark_dummy_2.html
deleted file mode 100644
index 229a730b3..000000000
--- a/browser/components/places/tests/browser/bookmark_dummy_2.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
-<title>Bookmark Dummy 2</title>
-<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
-</head>
-<body>
-<p>Bookmark Dummy 2</p>
-</body>
-</html>
diff --git a/browser/components/places/tests/browser/browser.ini b/browser/components/places/tests/browser/browser.ini
deleted file mode 100644
index 5dce31653..000000000
--- a/browser/components/places/tests/browser/browser.ini
+++ /dev/null
@@ -1,58 +0,0 @@
-# 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/.
-
-[DEFAULT]
-support-files =
- head.js
- framedPage.html
- frameLeft.html
- frameRight.html
- sidebarpanels_click_test_page.html
- keyword_form.html
-
-[browser_0_library_left_pane_migration.js]
-[browser_410196_paste_into_tags.js]
-subsuite = clipboard
-[browser_416459_cut.js]
-subsuite = clipboard
-[browser_423515.js]
-[browser_425884.js]
-[browser_435851_copy_query.js]
-subsuite = clipboard
-[browser_475045.js]
-[browser_555547.js]
-[browser_bookmarklet_windowOpen.js]
-support-files =
- pageopeningwindow.html
-[browser_bookmarkProperties_addFolderDefaultButton.js]
-[browser_bookmarkProperties_addKeywordForThisSearch.js]
-[browser_bookmarkProperties_addLivemark.js]
-[browser_bookmarkProperties_editTagContainer.js]
-[browser_bookmarkProperties_readOnlyRoot.js]
-[browser_bookmarksProperties.js]
-[browser_drag_bookmarks_on_toolbar.js]
-[browser_forgetthissite_single.js]
-[browser_history_sidebar_search.js]
-[browser_library_batch_delete.js]
-[browser_library_commands.js]
-[browser_library_downloads.js]
-[browser_library_infoBox.js]
-[browser_library_left_pane_fixnames.js]
-[browser_library_left_pane_select_hierarchy.js]
-[browser_library_middleclick.js]
-[browser_library_open_leak.js]
-[browser_library_openFlatContainer.js]
-[browser_library_panel_leak.js]
-[browser_library_search.js]
-[browser_library_views_liveupdate.js]
-[browser_markPageAsFollowedLink.js]
-[browser_sidebarpanels_click.js]
-skip-if = true # temporarily disabled for breaking the treeview - bug 658744
-[browser_sort_in_library.js]
-[browser_toolbarbutton_menu_context.js]
-[browser_views_liveupdate.js]
-[browser_bookmark_all_tabs.js]
-support-files =
- bookmark_dummy_1.html
- bookmark_dummy_2.html
diff --git a/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js b/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js
deleted file mode 100644
index a7089b497..000000000
--- a/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-"use strict";
-
-/**
- * Test we correctly migrate Library left pane to the latest version.
- * Note: this test MUST be the first between browser chrome tests, or results
- * of next tests could be unexpected due to PlacesUIUtils getters.
- */
-
-const TEST_URI = "http://www.mozilla.org/";
-
-add_task(function* () {
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils is running in chrome context");
- ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context");
- ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0,
- "Left pane version in chrome context, current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION );
-
- // Check if we have any left pane folder already set, remove it eventually.
- let leftPaneItems = PlacesUtils.annotations
- .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- if (leftPaneItems.length > 0) {
- // The left pane has already been created, touching it now would cause
- // next tests to rely on wrong values (and possibly crash)
- is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder");
- // Check version.
- let version = PlacesUtils.annotations.getItemAnnotation(leftPaneItems[0],
- PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, "Left pane version is actual");
- ok(true, "left pane has already been created, skipping test");
- return;
- }
-
- // Create a fake left pane folder with an old version (current version - 1).
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.rootGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: ""
- });
-
- let folderId = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations.setItemAnnotation(folderId,
- PlacesUIUtils.ORGANIZER_FOLDER_ANNO,
- PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION - 1,
- 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- // Check fake left pane root has been correctly created.
- leftPaneItems =
- PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder");
- is(leftPaneItems[0], folderId, "left pane root itemId is correct");
-
- // Check version.
- let version = PlacesUtils.annotations.getItemAnnotation(folderId,
- PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION - 1, "Left pane version correctly set");
-
- // Open Library, this will upgrade our left pane version.
- let organizer = yield promiseLibrary();
-
- // Check left pane.
- ok(PlacesUIUtils.leftPaneFolderId > 0, "Left pane folder correctly created");
- leftPaneItems =
- PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder");
- let leftPaneRoot = leftPaneItems[0];
- is(leftPaneRoot, PlacesUIUtils.leftPaneFolderId,
- "leftPaneFolderId getter has correct value");
-
- // Check version has been upgraded.
- version = PlacesUtils.annotations.getItemAnnotation(leftPaneRoot,
- PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION,
- "Left pane version has been correctly upgraded");
-
- // Check left pane is populated.
- organizer.PlacesOrganizer.selectLeftPaneQuery("History");
- is(organizer.PlacesOrganizer._places.selectedNode.itemId,
- PlacesUIUtils.leftPaneQueries["History"],
- "Library left pane is populated and working");
-
- yield promiseLibraryClosed(organizer);
-});
diff --git a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
deleted file mode 100644
index 2acb1d9b7..000000000
--- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-"use strict";
-
-const TEST_URL = Services.io.newURI("http://example.com/", null, null);
-const MOZURISPEC = Services.io.newURI("http://mozilla.com/", null, null);
-
-add_task(function* () {
- let organizer = yield promiseLibrary();
-
- ok(PlacesUtils, "PlacesUtils in scope");
- ok(PlacesUIUtils, "PlacesUIUtils in scope");
-
- let PlacesOrganizer = organizer.PlacesOrganizer;
- ok(PlacesOrganizer, "Places organizer in scope");
-
- let ContentTree = organizer.ContentTree;
- ok(ContentTree, "ContentTree is in scope");
-
- let visits = {uri: MOZURISPEC, transition: PlacesUtils.history.TRANSITION_TYPED};
- yield PlacesTestUtils.addVisits(visits);
-
- // create an initial tag to work with
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- title: "bookmark/" + TEST_URL.spec,
- url: TEST_URL
- });
-
- ok(bm, "A bookmark was added");
- PlacesUtils.tagging.tagURI(TEST_URL, ["foo"]);
- let tags = PlacesUtils.tagging.getTagsForURI(TEST_URL);
- is(tags[0], "foo", "tag is foo");
-
- // focus the new tag
- focusTag(PlacesOrganizer);
-
- let populate = () => copyHistNode(PlacesOrganizer, ContentTree);
- yield promiseClipboard(populate, PlacesUtils.TYPE_X_MOZ_PLACE);
-
- focusTag(PlacesOrganizer);
- PlacesOrganizer._places.controller.paste();
-
- // re-focus the history again
- PlacesOrganizer.selectLeftPaneQuery("History");
- let histContainer = PlacesOrganizer._places.selectedNode;
- PlacesUtils.asContainer(histContainer);
- histContainer.containerOpen = true;
- PlacesOrganizer._places.selectNode(histContainer.getChild(0));
- let histNode = ContentTree.view.view.nodeForTreeIndex(0);
- ok(histNode, "histNode exists: " + histNode.title);
-
- // check to see if the history node is tagged!
- tags = PlacesUtils.tagging.getTagsForURI(MOZURISPEC);
- ok(tags.length == 1, "history node is tagged: " + tags.length);
-
- // check if a bookmark was created
- let bookmarks = [];
- yield PlacesUtils.bookmarks.fetch({url: MOZURISPEC}, bm => {
- bookmarks.push(bm);
- });
- ok(bookmarks.length > 0, "bookmark exists for the tagged history item");
-
- // is the bookmark visible in the UI?
- // get the Unsorted Bookmarks node
- PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
-
- // now we can see what is in the ContentTree tree
- let unsortedNode = ContentTree.view.view.nodeForTreeIndex(1);
- ok(unsortedNode, "unsortedNode is not null: " + unsortedNode.uri);
- is(unsortedNode.uri, MOZURISPEC.spec, "node uri's are the same");
-
- yield promiseLibraryClosed(organizer);
-
- // Remove new Places data we created.
- PlacesUtils.tagging.untagURI(MOZURISPEC, ["foo"]);
- PlacesUtils.tagging.untagURI(TEST_URL, ["foo"]);
- tags = PlacesUtils.tagging.getTagsForURI(TEST_URL);
- is(tags.length, 0, "tags are gone");
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-function focusTag(PlacesOrganizer) {
- PlacesOrganizer.selectLeftPaneQuery("Tags");
- let tags = PlacesOrganizer._places.selectedNode;
- tags.containerOpen = true;
- let fooTag = tags.getChild(0);
- let tagNode = fooTag;
- PlacesOrganizer._places.selectNode(fooTag);
- is(tagNode.title, 'foo', "tagNode title is foo");
- let ip = PlacesOrganizer._places.insertionPoint;
- ok(ip.isTag, "IP is a tag");
-}
-
-function copyHistNode(PlacesOrganizer, ContentTree) {
- // focus the history object
- PlacesOrganizer.selectLeftPaneQuery("History");
- let histContainer = PlacesOrganizer._places.selectedNode;
- PlacesUtils.asContainer(histContainer);
- histContainer.containerOpen = true;
- PlacesOrganizer._places.selectNode(histContainer.getChild(0));
- let histNode = ContentTree.view.view.nodeForTreeIndex(0);
- ContentTree.view.selectNode(histNode);
- is(histNode.uri, MOZURISPEC.spec,
- "historyNode exists: " + histNode.uri);
- // copy the history node
- ContentTree.view.controller.copy();
-}
diff --git a/browser/components/places/tests/browser/browser_416459_cut.js b/browser/components/places/tests/browser/browser_416459_cut.js
deleted file mode 100644
index 6f3f8cdd5..000000000
--- a/browser/components/places/tests/browser/browser_416459_cut.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const TEST_URL = "http://example.com/";
-
-add_task(function* () {
- yield PlacesUtils.bookmarks.eraseEverything();
- let organizer = yield promiseLibrary();
-
- registerCleanupFunction(function* () {
- yield promiseLibraryClosed(organizer);
- yield PlacesUtils.bookmarks.eraseEverything();
- });
-
- let PlacesOrganizer = organizer.PlacesOrganizer;
- let ContentTree = organizer.ContentTree;
-
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils in scope");
- ok(PlacesUIUtils, "PlacesUIUtils in scope");
- ok(PlacesOrganizer, "PlacesOrganizer in scope");
- ok(ContentTree, "ContentTree is in scope");
-
- // Test with multiple entries to ensure they retain their order.
- let bookmarks = [];
- bookmarks.push(yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: TEST_URL,
- title: "0"
- }));
- bookmarks.push(yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: TEST_URL,
- title: "1"
- }));
- bookmarks.push(yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: TEST_URL,
- title: "2"
- }));
-
- yield selectBookmarksIn(organizer, bookmarks, "BookmarksToolbar");
-
- yield promiseClipboard(() => {
- info("Cutting selection");
- ContentTree.view.controller.cut();
- }, PlacesUtils.TYPE_X_MOZ_PLACE);
-
- info("Selecting UnfiledBookmarks in the left pane");
- PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- info("Pasting clipboard");
- ContentTree.view.controller.paste();
-
- yield selectBookmarksIn(organizer, bookmarks, "UnfiledBookmarks");
-});
-
-var selectBookmarksIn = Task.async(function* (organizer, bookmarks, aLeftPaneQuery) {
- let PlacesOrganizer = organizer.PlacesOrganizer;
- let ContentTree = organizer.ContentTree;
- info("Selecting " + aLeftPaneQuery + " in the left pane");
- PlacesOrganizer.selectLeftPaneQuery(aLeftPaneQuery);
-
- let ids = [];
- for (let {guid} of bookmarks) {
- let bookmark = yield PlacesUtils.bookmarks.fetch(guid);
- is (bookmark.parentGuid, PlacesOrganizer._places.selectedNode.targetFolderGuid,
- "Bookmark has the right parent");
- ids.push(yield PlacesUtils.promiseItemId(bookmark.guid));
- }
-
- info("Selecting the bookmarks in the right pane");
- ContentTree.view.selectItems(ids);
-
- for (let node of ContentTree.view.selectedNodes) {
- is(node.bookmarkIndex, node.title,
- "Found the expected bookmark in the expected position");
- }
-});
diff --git a/browser/components/places/tests/browser/browser_423515.js b/browser/components/places/tests/browser/browser_423515.js
deleted file mode 100644
index 4d3da8fc1..000000000
--- a/browser/components/places/tests/browser/browser_423515.js
+++ /dev/null
@@ -1,173 +0,0 @@
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-function test() {
- // sanity check
- ok(PlacesUtils, "checking PlacesUtils, running in chrome context?");
- ok(PlacesUIUtils, "checking PlacesUIUtils, running in chrome context?");
- ok(PlacesControllerDragHelper, "checking PlacesControllerDragHelper, running in chrome context?");
-
- const IDX = PlacesUtils.bookmarks.DEFAULT_INDEX;
-
- // setup
- var rootId = PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId, "", IDX);
- var rootNode = PlacesUtils.getFolderContents(rootId, false, true).root;
- is(rootNode.childCount, 0, "confirm test root is empty");
-
- var tests = [];
-
- // add a regular folder, should be moveable
- tests.push({
- populate: function() {
- this.id =
- PlacesUtils.bookmarks.createFolder(rootId, "", IDX);
- },
- validate: function() {
- is(rootNode.childCount, 1,
- "populate added data to the test root");
- is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)),
- true, "can move regular folder node");
- }
- });
-
- // add a regular folder shortcut, should be moveable
- tests.push({
- populate: function() {
- this.folderId =
- PlacesUtils.bookmarks.createFolder(rootId, "foo", IDX);
- this.shortcutId =
- PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder="+this.folderId), IDX, "bar");
- },
- validate: function() {
- is(rootNode.childCount, 2,
- "populated data to the test root");
-
- var folderNode = rootNode.getChild(0);
- is(folderNode.type, 6, "node is folder");
- is(this.folderId, folderNode.itemId, "folder id and folder node item id match");
-
- var shortcutNode = rootNode.getChild(1);
- is(shortcutNode.type, 9, "node is folder shortcut");
- is(this.shortcutId, shortcutNode.itemId, "shortcut id and shortcut node item id match");
-
- var concreteId = PlacesUtils.getConcreteItemId(shortcutNode);
- is(concreteId, folderNode.itemId, "shortcut node id and concrete id match");
-
- is(PlacesControllerDragHelper.canMoveNode(shortcutNode),
- true, "can move folder shortcut node");
- }
- });
-
- // add a regular query, should be moveable
- tests.push({
- populate: function() {
- this.bookmarkId =
- PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("http://foo.com"), IDX, "foo");
- this.queryId =
- PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:terms=foo"), IDX, "bar");
- },
- validate: function() {
- is(rootNode.childCount, 2,
- "populated data to the test root");
-
- var bmNode = rootNode.getChild(0);
- is(bmNode.itemId, this.bookmarkId, "bookmark id and bookmark node item id match");
-
- var queryNode = rootNode.getChild(1);
- is(queryNode.itemId, this.queryId, "query id and query node item id match");
-
- is(PlacesControllerDragHelper.canMoveNode(queryNode),
- true, "can move query node");
- }
- });
-
- // test that special folders cannot be moved
- // test that special folders shortcuts can be moved
- tests.push({
- folders: [PlacesUtils.bookmarksMenuFolderId,
- PlacesUtils.tagsFolderId, PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.toolbarFolderId],
- shortcuts: {},
- populate: function() {
- for (var i = 0; i < this.folders.length; i++) {
- var id = this.folders[i];
- this.shortcuts[id] =
- PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + id), IDX, "");
- }
- },
- validate: function() {
- // test toolbar shortcut node
- is(rootNode.childCount, this.folders.length,
- "populated data to the test root");
-
- function getRootChildNode(aId) {
- var node = PlacesUtils.getFolderContents(PlacesUtils.placesRootId, false, true).root;
- for (var i = 0; i < node.childCount; i++) {
- var child = node.getChild(i);
- if (child.itemId == aId) {
- node.containerOpen = false;
- return child;
- }
- }
- node.containerOpen = false;
- ok(false, "Unable to find child node");
- return null;
- }
-
- for (var i = 0; i < this.folders.length; i++) {
- var id = this.folders[i];
-
- var node = getRootChildNode(id);
- isnot(node, null, "Node found");
- is(PlacesControllerDragHelper.canMoveNode(node),
- false, "shouldn't be able to move special folder node");
-
- var shortcutId = this.shortcuts[id];
- var shortcutNode = rootNode.getChild(i);
-
- is(shortcutNode.itemId, shortcutId, "shortcut id and shortcut node item id match");
-
- dump("can move shortcut node?\n");
- is(PlacesControllerDragHelper.canMoveNode(shortcutNode),
- true, "should be able to move special folder shortcut node");
- }
- }
- });
-
- // test that a tag container cannot be moved
- tests.push({
- populate: function() {
- // tag a uri
- this.uri = makeURI("http://foo.com");
- PlacesUtils.tagging.tagURI(this.uri, ["bar"]);
- registerCleanupFunction(() => PlacesUtils.tagging.untagURI(this.uri, ["bar"]));
- },
- validate: function() {
- // get tag root
- var query = PlacesUtils.history.getNewQuery();
- var options = PlacesUtils.history.getNewQueryOptions();
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY;
- var tagsNode = PlacesUtils.history.executeQuery(query, options).root;
-
- tagsNode.containerOpen = true;
- is(tagsNode.childCount, 1, "has new tag");
-
- var tagNode = tagsNode.getChild(0);
-
- is(PlacesControllerDragHelper.canMoveNode(tagNode),
- false, "should not be able to move tag container node");
- tagsNode.containerOpen = false;
- }
- });
-
- tests.forEach(function(aTest) {
- PlacesUtils.bookmarks.removeFolderChildren(rootId);
- aTest.populate();
- aTest.validate();
- });
-
- rootNode.containerOpen = false;
- PlacesUtils.bookmarks.removeItem(rootId);
-}
diff --git a/browser/components/places/tests/browser/browser_425884.js b/browser/components/places/tests/browser/browser_425884.js
deleted file mode 100644
index 655eb1ffd..000000000
--- a/browser/components/places/tests/browser/browser_425884.js
+++ /dev/null
@@ -1,127 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/*
- Deep copy of bookmark data, using the front-end codepath:
-
- - create test folder A
- - add a subfolder to folder A, and add items to it
- - validate folder A (sanity check)
- - copy folder A, creating new folder B, using the front-end path
- - validate folder B
- - undo copy transaction
- - validate folder B (empty)
- - redo copy transaction
- - validate folder B's contents
-*/
-
-add_task(function* () {
- // sanity check
- ok(PlacesUtils, "checking PlacesUtils, running in chrome context?");
- ok(PlacesUIUtils, "checking PlacesUIUtils, running in chrome context?");
-
- let toolbarId = PlacesUtils.toolbarFolderId;
- let toolbarNode = PlacesUtils.getFolderContents(toolbarId).root;
-
- let oldCount = toolbarNode.childCount;
- let testRoot = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "test root"
- });
- is(toolbarNode.childCount, oldCount+1, "confirm test root node is a container, and is empty");
-
- let testRootNode = toolbarNode.getChild(toolbarNode.childCount-1);
- testRootNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- testRootNode.containerOpen = true;
- is(testRootNode.childCount, 0, "confirm test root node is a container, and is empty");
-
- // create folder A, fill it, validate its contents
- let folderA = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: testRoot.guid,
- title: "A"
- });
-
- yield populate(folderA);
-
- let folderAId = yield PlacesUtils.promiseItemId(folderA.guid);
- let folderANode = PlacesUtils.getFolderContents(folderAId).root;
- validate(folderANode);
- is(testRootNode.childCount, 1, "create test folder");
-
- // copy it, using the front-end helper functions
- let serializedNode = PlacesUtils.wrapNode(folderANode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER);
- let rawNode = PlacesUtils.unwrapNodes(serializedNode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER).shift();
- // confirm serialization
- ok(rawNode.type, "confirm json node");
- folderANode.containerOpen = false;
-
- let testRootId = yield PlacesUtils.promiseItemId(testRoot.guid);
- let transaction = PlacesUIUtils.makeTransaction(rawNode,
- PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
- testRootId,
- -1,
- true);
- ok(transaction, "create transaction");
- PlacesUtils.transactionManager.doTransaction(transaction);
- // confirm copy
- is(testRootNode.childCount, 2, "create test folder via copy");
-
- // validate the copy
- let folderBNode = testRootNode.getChild(1);
- validate(folderBNode);
-
- // undo the transaction, confirm the removal
- PlacesUtils.transactionManager.undoTransaction();
- is(testRootNode.childCount, 1, "confirm undo removed the copied folder");
-
- // redo the transaction
- PlacesUtils.transactionManager.redoTransaction();
- is(testRootNode.childCount, 2, "confirm redo re-copied the folder");
- folderBNode = testRootNode.getChild(1);
- validate(folderBNode);
-
- // Close containers, cleaning up their observers.
- testRootNode.containerOpen = false;
- toolbarNode.containerOpen = false;
-
- // clean up
- PlacesUtils.transactionManager.undoTransaction();
- yield PlacesUtils.bookmarks.remove(folderA.guid);
-});
-
-var populate = Task.async(function* (parentFolder) {
- let folder = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: parentFolder.guid,
- title: "test folder"
- });
-
- yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: folder.guid,
- title: "test bookmark",
- url: "http://foo"
- });
-
- yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: folder.guid
- });
-});
-
-function validate(aNode) {
- PlacesUtils.asContainer(aNode);
- aNode.containerOpen = true;
- is(aNode.childCount, 1, "confirm child count match");
- var folderNode = aNode.getChild(0);
- is(folderNode.title, "test folder", "confirm folder title");
- PlacesUtils.asContainer(folderNode);
- folderNode.containerOpen = true;
- is(folderNode.childCount, 2, "confirm child count match");
- folderNode.containerOpen = false;
- aNode.containerOpen = false;
-}
diff --git a/browser/components/places/tests/browser/browser_435851_copy_query.js b/browser/components/places/tests/browser/browser_435851_copy_query.js
deleted file mode 100644
index 92f818b41..000000000
--- a/browser/components/places/tests/browser/browser_435851_copy_query.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-/* test that copying a non movable query or folder shortcut makes a new query with the same url, not a deep copy */
-
-const SHORTCUT_URL = "place:folder=2";
-const QUERY_URL = "place:sort=8&maxResults=10";
-
-add_task(function* copy_toolbar_shortcut() {
- let library = yield promiseLibrary();
-
- registerCleanupFunction(function () {
- library.close();
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- });
-
- library.PlacesOrganizer.selectLeftPaneQuery("BookmarksToolbar");
-
- yield promiseClipboard(function () { library.PlacesOrganizer._places.controller.copy(); },
- PlacesUtils.TYPE_X_MOZ_PLACE);
-
- library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- library.ContentTree.view.controller.paste();
-
- let toolbarCopyNode = library.ContentTree.view.view.nodeForTreeIndex(0);
- is(toolbarCopyNode.type,
- Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT,
- "copy is still a folder shortcut");
-
- PlacesUtils.bookmarks.removeItem(toolbarCopyNode.itemId);
- library.PlacesOrganizer.selectLeftPaneQuery("BookmarksToolbar");
- is(library.PlacesOrganizer._places.selectedNode.type,
- Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT,
- "original is still a folder shortcut");
-});
-
-add_task(function* copy_history_query() {
- let library = yield promiseLibrary();
-
- library.PlacesOrganizer.selectLeftPaneQuery("History");
-
- yield promiseClipboard(function () { library.PlacesOrganizer._places.controller.copy(); },
- PlacesUtils.TYPE_X_MOZ_PLACE);
-
- library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- library.ContentTree.view.controller.paste();
-
- let historyCopyNode = library.ContentTree.view.view.nodeForTreeIndex(0);
- is(historyCopyNode.type,
- Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY,
- "copy is still a query");
-
- PlacesUtils.bookmarks.removeItem(historyCopyNode.itemId);
- library.PlacesOrganizer.selectLeftPaneQuery("History");
- is(library.PlacesOrganizer._places.selectedNode.type,
- Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY,
- "original is still a query");
-});
diff --git a/browser/components/places/tests/browser/browser_475045.js b/browser/components/places/tests/browser/browser_475045.js
deleted file mode 100644
index 7d562349b..000000000
--- a/browser/components/places/tests/browser/browser_475045.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-// Instead of loading EventUtils.js into the test scope in browser-test.js for all tests,
-// we only need EventUtils.js for a few files which is why we are using loadSubScript.
-var EventUtils = {};
-this._scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
-add_task(function* test() {
- // Make sure the bookmarks bar is visible and restore its state on cleanup.
- let toolbar = document.getElementById("PersonalToolbar");
- ok(toolbar, "PersonalToolbar should not be null");
-
- if (toolbar.collapsed) {
- yield promiseSetToolbarVisibility(toolbar, true);
- registerCleanupFunction(function() {
- return promiseSetToolbarVisibility(toolbar, false);
- });
- }
-
- // Setup the node we will use to be dropped. The actual node used does not
- // matter because we will set its data, effect, and mimeType manually.
- let placesItems = document.getElementById("PlacesToolbarItems");
- ok(placesItems, "PlacesToolbarItems should not be null");
- ok(placesItems.localName == "scrollbox", "PlacesToolbarItems should not be null");
- ok(placesItems.childNodes[0], "PlacesToolbarItems must have at least one child");
-
- /**
- * Simulates a drop of a URI onto the bookmarks bar.
- *
- * @param aEffect
- * The effect to use for the drop operation: move, copy, or link.
- * @param aMimeType
- * The mime type to use for the drop operation.
- */
- let simulateDragDrop = function(aEffect, aMimeType) {
- const uriSpec = "http://www.mozilla.org/D1995729-A152-4e30-8329-469B01F30AA7";
- let uri = makeURI(uriSpec);
- EventUtils.synthesizeDrop(placesItems.childNodes[0],
- placesItems,
- [[{type: aMimeType,
- data: uriSpec}]],
- aEffect, window);
-
- // Verify that the drop produces exactly one bookmark.
- let bookmarkIds = PlacesUtils.bookmarks
- .getBookmarkIdsForURI(uri);
- ok(bookmarkIds.length == 1, "There should be exactly one bookmark");
-
- PlacesUtils.bookmarks.removeItem(bookmarkIds[0]);
-
- // Verify that we removed the bookmark successfully.
- ok(!PlacesUtils.bookmarks.isBookmarked(uri), "URI should be removed");
- }
-
- // Simulate a bookmark drop for all of the mime types and effects.
- let mimeTypes = ["text/plain", "text/unicode", "text/x-moz-url"];
- let effects = ["move", "copy", "link"];
- effects.forEach(function (effect) {
- mimeTypes.forEach(function (mimeType) {
- simulateDragDrop(effect, mimeType);
- });
- });
-});
diff --git a/browser/components/places/tests/browser/browser_555547.js b/browser/components/places/tests/browser/browser_555547.js
deleted file mode 100644
index 0654139cb..000000000
--- a/browser/components/places/tests/browser/browser_555547.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-"use strict";
-
-add_task(function* test() {
- let sidebarBox = document.getElementById("sidebar-box");
- is(sidebarBox.hidden, true, "The sidebar should be hidden");
-
- // Uncollapse the personal toolbar if needed.
- let toolbar = document.getElementById("PersonalToolbar");
- let wasCollapsed = toolbar.collapsed;
- if (wasCollapsed) {
- yield promiseSetToolbarVisibility(toolbar, true);
- }
-
- let sidebar = yield promiseLoadedSidebar("viewBookmarksSidebar");
- registerCleanupFunction(() => {
- SidebarUI.hide();
- });
-
- // Focus the tree and check if its controller is returned.
- let tree = sidebar.contentDocument.getElementById("bookmarks-view");
- tree.focus();
-
- let controller = doGetPlacesControllerForCommand("placesCmd_copy");
- let treeController = tree.controllers
- .getControllerForCommand("placesCmd_copy");
- ok(controller == treeController, "tree controller was returned");
-
- // Open the context menu for a toolbar item, and check if the toolbar's
- // controller is returned.
- let toolbarItems = document.getElementById("PlacesToolbarItems");
- EventUtils.synthesizeMouse(toolbarItems.childNodes[0],
- 4, 4, { type: "contextmenu", button: 2 },
- window);
- controller = doGetPlacesControllerForCommand("placesCmd_copy");
- let toolbarController = document.getElementById("PlacesToolbar")
- .controllers
- .getControllerForCommand("placesCmd_copy");
- ok(controller == toolbarController, "the toolbar controller was returned");
-
- document.getElementById("placesContext").hidePopup();
-
- // Now that the context menu is closed, try to get the tree controller again.
- tree.focus();
- controller = doGetPlacesControllerForCommand("placesCmd_copy");
- ok(controller == treeController, "tree controller was returned");
-
- if (wasCollapsed) {
- yield promiseSetToolbarVisibility(toolbar, false);
- }
-});
-
-function promiseLoadedSidebar(cmd) {
- return new Promise(resolve => {
- let sidebar = document.getElementById("sidebar");
- sidebar.addEventListener("load", function onLoad() {
- sidebar.removeEventListener("load", onLoad, true);
- resolve(sidebar);
- }, true);
-
- SidebarUI.show(cmd);
- });
-}
diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js
deleted file mode 100644
index a1f091ebe..000000000
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js
+++ /dev/null
@@ -1,53 +0,0 @@
-"use strict"
-
-add_task(function* () {
- info("Bug 475529 - Add is the default button for the new folder dialog + " +
- "Bug 1206376 - Changing properties of a new bookmark while adding it " +
- "acts on the last bookmark in the current container");
-
- // Add a new bookmark at index 0 in the unfiled folder.
- let insertionIndex = 0;
- let newBookmark = yield PlacesUtils.bookmarks.insert({
- index: insertionIndex,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- });
- let newBookmarkId = yield PlacesUtils.promiseItemId(newBookmark.guid);
-
- yield withSidebarTree("bookmarks", function* (tree) {
- // Select the new bookmark in the sidebar.
- tree.selectItems([newBookmarkId]);
- ok(tree.controller.isCommandEnabled("placesCmd_new:folder"),
- "'placesCmd_new:folder' on current selected node is enabled");
-
- // Create a new folder. Since the new bookmark is selected, and new items
- // are inserted at the index of the currently selected item, the new folder
- // will be inserted at index 0.
- yield withBookmarksDialog(
- false,
- function openDialog() {
- tree.controller.doCommand("placesCmd_new:folder");
- },
- function* test(dialogWin) {
- let promiseTitleChangeNotification = promiseBookmarksNotification(
- "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val =="n");
-
- fillBookmarkTextField("editBMPanel_namePicker", "n", dialogWin, false);
-
- // Confirm and close the dialog.
- EventUtils.synthesizeKey("VK_RETURN", {}, dialogWin);
- yield promiseTitleChangeNotification;
-
- let newFolder = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: insertionIndex,
- });
-
- is(newFolder.title, "n", "folder name has been edited");
- yield PlacesUtils.bookmarks.remove(newFolder);
- yield PlacesUtils.bookmarks.remove(newBookmark);
- }
- );
- });
-});
diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js
deleted file mode 100644
index 5283a1610..000000000
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js
+++ /dev/null
@@ -1,110 +0,0 @@
-"use strict"
-
-const TEST_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser/keyword_form.html";
-
-add_task(function* () {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_URL,
- }, function* (browser) {
- // We must wait for the context menu code to build metadata.
- yield openContextMenuForContentSelector(browser, '#form1 > input[name="search"]');
-
- yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) {
- let acceptBtn = dialogWin.document.documentElement.getButton("accept");
- ok(acceptBtn.disabled, "Accept button is disabled");
-
- let promiseKeywordNotification = promiseBookmarksNotification(
- "onItemChanged", (itemId, prop, isAnno, val) => prop == "keyword" && val =="kw");
-
- fillBookmarkTextField("editBMPanel_keywordField", "kw", dialogWin);
-
- ok(!acceptBtn.disabled, "Accept button is enabled");
-
- // The dialog is instant apply.
- yield promiseKeywordNotification;
-
- // After the notification, the keywords cache will update asynchronously.
- info("Check the keyword entry has been created");
- let entry;
- yield waitForCondition(function* () {
- entry = yield PlacesUtils.keywords.fetch("kw");
- return !!entry;
- }, "Unable to find the expected keyword");
- is(entry.keyword, "kw", "keyword is correct");
- is(entry.url.href, TEST_URL, "URL is correct");
- is(entry.postData, "accenti%3D%E0%E8%EC%F2%F9&search%3D%25s", "POST data is correct");
-
- info("Check the charset has been saved");
- let charset = yield PlacesUtils.getCharsetForURI(NetUtil.newURI(TEST_URL));
- is(charset, "windows-1252", "charset is correct");
-
- // Now check getShortcutOrURI.
- let data = yield getShortcutOrURIAndPostData("kw test");
- is(getPostDataString(data.postData), "accenti=\u00E0\u00E8\u00EC\u00F2\u00F9&search=test", "getShortcutOrURI POST data is correct");
- is(data.url, TEST_URL, "getShortcutOrURI URL is correct");
- });
- });
-});
-
-add_task(function* reopen_same_field() {
- yield PlacesUtils.keywords.insert({
- url: TEST_URL,
- keyword: "kw",
- postData: "accenti%3D%E0%E8%EC%F2%F9&search%3D%25s"
- });
- registerCleanupFunction(function* () {
- yield PlacesUtils.keywords.remove("kw");
- });
- // Reopening on the same input field should show the existing keyword.
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_URL,
- }, function* (browser) {
- // We must wait for the context menu code to build metadata.
- yield openContextMenuForContentSelector(browser, '#form1 > input[name="search"]');
-
- yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) {
- let acceptBtn = dialogWin.document.documentElement.getButton("accept");
- ok(acceptBtn.disabled, "Accept button is disabled");
-
- let elt = dialogWin.document.getElementById("editBMPanel_keywordField");
- is(elt.value, "kw");
- });
- });
-});
-
-add_task(function* open_other_field() {
- yield PlacesUtils.keywords.insert({
- url: TEST_URL,
- keyword: "kw2",
- postData: "search%3D%25s"
- });
- registerCleanupFunction(function* () {
- yield PlacesUtils.keywords.remove("kw2");
- });
- // Reopening on another field of the same page that has different postData
- // should not show the existing keyword.
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_URL,
- }, function* (browser) {
- // We must wait for the context menu code to build metadata.
- yield openContextMenuForContentSelector(browser, '#form2 > input[name="search"]');
-
- yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) {
- let acceptBtn = dialogWin.document.documentElement.getButton("accept");
- ok(acceptBtn.disabled, "Accept button is disabled");
-
- let elt = dialogWin.document.getElementById("editBMPanel_keywordField");
- is(elt.value, "");
- });
- });
-});
-
-function getPostDataString(stream) {
- let sis = Cc["@mozilla.org/scriptableinputstream;1"]
- .createInstance(Ci.nsIScriptableInputStream);
- sis.init(stream);
- return sis.read(stream.available()).split("\n").pop();
-}
diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js
deleted file mode 100644
index d9f4c07d7..000000000
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict"
-
-add_task(function* () {
- info("Add a live bookmark editing its data");
-
- yield withSidebarTree("bookmarks", function* (tree) {
- let itemId = PlacesUIUtils.leftPaneQueries["UnfiledBookmarks"];
- tree.selectItems([itemId]);
-
- yield withBookmarksDialog(
- true,
- function openDialog() {
- PlacesCommandHook.addLiveBookmark("http://livemark.com/",
- "livemark", "description");
- },
- function* test(dialogWin) {
- let promiseTitleChangeNotification = promiseBookmarksNotification(
- "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val == "modified");
-
- fillBookmarkTextField("editBMPanel_namePicker", "modified", dialogWin);
-
- yield promiseTitleChangeNotification;
-
- let bookmark = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
-
- is(bookmark.title, "modified", "folder name has been edited");
-
- let livemark = yield PlacesUtils.livemarks.getLivemark({
- guid: bookmark.guid
- });
- is(livemark.feedURI.spec, "http://livemark.com/", "livemark has the correct url");
- is(livemark.title, "modified", "livemark has the correct title");
- }
- );
- });
-});
diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js b/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js
deleted file mode 100644
index fde9ea272..000000000
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js
+++ /dev/null
@@ -1,71 +0,0 @@
-"use strict"
-
-add_task(function* () {
- info("Bug 479348 - Properties on a root should be read-only.");
- let uri = NetUtil.newURI("http://example.com/");
- let bm = yield PlacesUtils.bookmarks.insert({
- url: uri.spec,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
- registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.remove(bm);
- });
-
- PlacesUtils.tagging.tagURI(uri, ["tag1"]);
-
- let library = yield promiseLibrary();
- let PlacesOrganizer = library.PlacesOrganizer;
- registerCleanupFunction(function* () {
- yield promiseLibraryClosed(library);
- });
-
- PlacesOrganizer.selectLeftPaneQuery("Tags");
- let tree = PlacesOrganizer._places;
- let tagsContainer = tree.selectedNode;
- tagsContainer.containerOpen = true;
- let fooTag = tagsContainer.getChild(0);
- let tagNode = fooTag;
- tree.selectNode(fooTag);
- is(tagNode.title, 'tag1', "tagNode title is correct");
-
- ok(tree.controller.isCommandEnabled("placesCmd_show:info"),
- "'placesCmd_show:info' on current selected node is enabled");
-
- yield withBookmarksDialog(
- true,
- function openDialog() {
- tree.controller.doCommand("placesCmd_show:info");
- },
- function* test(dialogWin) {
- // Check that the dialog is not read-only.
- ok(!dialogWin.gEditItemOverlay.readOnly, "Dialog should not be read-only");
-
- // Check that name picker is not read only
- let namepicker = dialogWin.document.getElementById("editBMPanel_namePicker");
- ok(!namepicker.readOnly, "Name field should not be read-only");
- is(namepicker.value, "tag1", "Node title is correct");
-
- let promiseTitleChangeNotification = promiseBookmarksNotification(
- "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val == "tag2");
-
- fillBookmarkTextField("editBMPanel_namePicker", "tag2", dialogWin);
-
- yield promiseTitleChangeNotification;
-
- is(namepicker.value, "tag2", "Node title has been properly edited");
-
- // Check the shortcut's title.
- is(tree.selectedNode.title, "tag2", "The node has the correct title");
-
- // Check the tags have been edited.
- let tags = PlacesUtils.tagging.getTagsForURI(uri);
- is(tags.length, 1, "Found the right number of tags");
- ok(tags.includes("tag2"), "Found the expected tag");
- }
- );
-
- // Check the tag change has been reverted.
- let tags = PlacesUtils.tagging.getTagsForURI(uri);
- is(tags.length, 1, "Found the right number of tags");
- ok(tags.includes("tag1"), "Found the expected tag");
-});
diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js b/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js
deleted file mode 100644
index 6f499888c..000000000
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js
+++ /dev/null
@@ -1,42 +0,0 @@
-"use strict"
-
-add_task(function* () {
- info("Bug 479348 - Properties on a root should be read-only.");
-
- yield withSidebarTree("bookmarks", function* (tree) {
- let itemId = PlacesUIUtils.leftPaneQueries["UnfiledBookmarks"];
- tree.selectItems([itemId]);
- ok(tree.controller.isCommandEnabled("placesCmd_show:info"),
- "'placesCmd_show:info' on current selected node is enabled");
-
- yield withBookmarksDialog(
- true,
- function openDialog() {
- tree.controller.doCommand("placesCmd_show:info");
- },
- function* test(dialogWin) {
- // Check that the dialog is read-only.
- ok(dialogWin.gEditItemOverlay.readOnly, "Dialog is read-only");
- // Check that accept button is disabled
- let acceptButton = dialogWin.document.documentElement.getButton("accept");
- ok(acceptButton.disabled, "Accept button is disabled");
-
- // Check that name picker is read only
- let namepicker = dialogWin.document.getElementById("editBMPanel_namePicker");
- ok(namepicker.readOnly, "Name field is read-only");
- is(namepicker.value,
- PlacesUtils.bookmarks.getItemTitle(PlacesUtils.unfiledBookmarksFolderId),
- "Node title is correct");
- // Blur the field and ensure root's name has not been changed.
- namepicker.blur();
- is(namepicker.value,
- PlacesUtils.bookmarks.getItemTitle(PlacesUtils.unfiledBookmarksFolderId),
- "Root title is correct");
- // Check the shortcut's title.
- let bookmark = yield PlacesUtils.bookmarks.fetch(tree.selectedNode.bookmarkGuid);
- is(bookmark.title, null,
- "Shortcut title is null");
- }
- );
- });
-});
diff --git a/browser/components/places/tests/browser/browser_bookmark_all_tabs.js b/browser/components/places/tests/browser/browser_bookmark_all_tabs.js
deleted file mode 100644
index afd32b78a..000000000
--- a/browser/components/places/tests/browser/browser_bookmark_all_tabs.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Test for Bug 446171 - Name field of bookmarks saved via 'Bookmark All Tabs'
- * has '(null)' value if history is disabled or just in private browsing mode
- */
-"use strict"
-
-add_task(function* () {
- const BASE_URL = "http://example.org/browser/browser/components/places/tests/browser/";
- const TEST_PAGES = [
- BASE_URL + "bookmark_dummy_1.html",
- BASE_URL + "bookmark_dummy_2.html",
- BASE_URL + "bookmark_dummy_1.html"
- ];
-
- function promiseAddTab(url) {
- return BrowserTestUtils.openNewForegroundTab(gBrowser, url);
- }
-
- let tabs = yield Promise.all(TEST_PAGES.map(promiseAddTab));
-
- let URIs = PlacesCommandHook.uniqueCurrentPages;
- is(URIs.length, 3, "Only unique pages are returned");
-
- Assert.deepEqual(URIs.map(URI => URI.uri.spec), [
- "about:blank",
- BASE_URL + "bookmark_dummy_1.html",
- BASE_URL + "bookmark_dummy_2.html"
- ], "Correct URIs are returned");
-
- Assert.deepEqual(URIs.map(URI => URI.title), [
- "New Tab", "Bookmark Dummy 1", "Bookmark Dummy 2"
- ], "Correct titles are returned");
-
- registerCleanupFunction(function* () {
- yield Promise.all(tabs.map(BrowserTestUtils.removeTab));
- });
-});
diff --git a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js
deleted file mode 100644
index 85ce25311..000000000
--- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js
+++ /dev/null
@@ -1,61 +0,0 @@
-"use strict";
-
-const TEST_URL = 'http://example.com/browser/browser/components/places/tests/browser/pageopeningwindow.html';
-
-function makeBookmarkFor(url, keyword) {
- return Promise.all([
- PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmarklet",
- url: url }),
- PlacesUtils.keywords.insert({url: url,
- keyword: keyword})
- ]);
-
-}
-
-add_task(function* openKeywordBookmarkWithWindowOpen() {
- // This is the current default, but let's not assume that...
- yield new Promise((resolve, reject) => {
- SpecialPowers.pushPrefEnv({ 'set': [[ 'browser.link.open_newwindow', 3 ],
- [ 'dom.disable_open_during_load', true ]] },
- resolve);
- });
-
- let moztab;
- let tabOpened = BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla")
- .then((tab) => { moztab = tab; });
- let keywordForBM = "openmeatab";
-
- let bookmarkInfo;
- let bookmarkCreated =
- makeBookmarkFor("javascript:void open('" + TEST_URL + "')", keywordForBM)
- .then((values) => {
- bookmarkInfo = values[0];
- });
- yield Promise.all([tabOpened, bookmarkCreated]);
-
- registerCleanupFunction(function() {
- return Promise.all([
- PlacesUtils.bookmarks.remove(bookmarkInfo),
- PlacesUtils.keywords.remove(keywordForBM)
- ]);
- });
- gURLBar.value = keywordForBM;
- gURLBar.focus();
-
- let tabCreatedPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
- EventUtils.synthesizeKey("VK_RETURN", {});
-
- info("Waiting for tab being created");
- let {target: tab} = yield tabCreatedPromise;
- info("Got tab");
- let browser = tab.linkedBrowser;
- if (!browser.currentURI || browser.currentURI.spec != TEST_URL) {
- info("Waiting for browser load");
- yield BrowserTestUtils.browserLoaded(browser);
- }
- is(browser.currentURI && browser.currentURI.spec, TEST_URL, "Tab with expected URL loaded.");
- info("Waiting to remove tab");
- yield Promise.all([ BrowserTestUtils.removeTab(tab),
- BrowserTestUtils.removeTab(moztab) ]);
-});
diff --git a/browser/components/places/tests/browser/browser_bookmarksProperties.js b/browser/components/places/tests/browser/browser_bookmarksProperties.js
deleted file mode 100644
index f7f9f4762..000000000
--- a/browser/components/places/tests/browser/browser_bookmarksProperties.js
+++ /dev/null
@@ -1,450 +0,0 @@
-/* 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/. */
-
-/**
- * Tests the bookmarks Properties dialog.
- */
-
-// DOM ids of Places sidebar trees.
-const SIDEBAR_HISTORY_TREE_ID = "historyTree";
-const SIDEBAR_BOOKMARKS_TREE_ID = "bookmarks-view";
-
-const SIDEBAR_HISTORY_ID = "viewHistorySidebar";
-const SIDEBAR_BOOKMARKS_ID = "viewBookmarksSidebar";
-
-// For history sidebar.
-const SIDEBAR_HISTORY_BYLASTVISITED_VIEW = "bylastvisited";
-const SIDEBAR_HISTORY_BYMOSTVISITED_VIEW = "byvisited";
-const SIDEBAR_HISTORY_BYDATE_VIEW = "byday";
-const SIDEBAR_HISTORY_BYSITE_VIEW = "bysite";
-const SIDEBAR_HISTORY_BYDATEANDSITE_VIEW = "bydateandsite";
-
-// Action to execute on the current node.
-const ACTION_EDIT = 0;
-const ACTION_ADD = 1;
-
-// If action is ACTION_ADD, set type to one of those, to define what do you
-// want to create.
-const TYPE_FOLDER = 0;
-const TYPE_BOOKMARK = 1;
-
-const TEST_URL = "http://www.example.com/";
-
-const DIALOG_URL = "chrome://browser/content/places/bookmarkProperties.xul";
-const DIALOG_URL_MINIMAL_UI = "chrome://browser/content/places/bookmarkProperties2.xul";
-
-Cu.import("resource:///modules/RecentWindow.jsm");
-var win = RecentWindow.getMostRecentBrowserWindow();
-var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
- getService(Ci.nsIWindowWatcher);
-
-function add_bookmark(aURI) {
- var bId = PlacesUtils.bookmarks
- .insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark/" + aURI.spec);
- return bId;
-}
-
-// Each test is an obj w/ a desc property and run method.
-var gTests = [];
-var gCurrentTest = null;
-
-// ------------------------------------------------------------------------------
-// Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog
-gTests.push({
- desc: "Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog",
- sidebar: SIDEBAR_BOOKMARKS_ID,
- action: ACTION_EDIT,
- itemType: null,
- window: null,
- _itemId: null,
- _cleanShutdown: false,
-
- setup: function(aCallback) {
- // Add a bookmark in unsorted bookmarks folder.
- this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL));
- ok(this._itemId > 0, "Correctly added a bookmark");
- // Add a tag to this bookmark.
- PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL),
- ["testTag"]);
- var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL));
- is(tags[0], "testTag", "Correctly added a tag");
- aCallback();
- },
-
- selectNode: function(tree) {
- tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]);
- PlacesUtils.asContainer(tree.selectedNode).containerOpen = true;
- tree.selectItems([this._itemId]);
- is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected");
- },
-
- run: function() {
- // open tags autocomplete and press enter
- var tagsField = this.window.document.getElementById("editBMPanel_tagsField");
- var self = this;
-
- this.window.addEventListener("unload", function(event) {
- self.window.removeEventListener("unload", arguments.callee, true);
- tagsField.popup.removeEventListener("popuphidden", popupListener, true);
- ok(self._cleanShutdown, "Dialog window should not be closed by pressing Enter on the autocomplete popup");
- executeSoon(function () {
- self.finish();
- });
- }, true);
-
- var popupListener = {
- handleEvent: function(aEvent) {
- switch (aEvent.type) {
- case "popuphidden":
- // Everything worked fine, we can stop observing the window.
- self._cleanShutdown = true;
- self.window.document.documentElement.cancelDialog();
- break;
- case "popupshown":
- tagsField.popup.removeEventListener("popupshown", this, true);
- // In case this test fails the window will close, the test will fail
- // since we didn't set _cleanShutdown.
- var tree = tagsField.popup.tree;
- // Focus and select first result.
- isnot(tree, null, "Autocomplete results tree exists");
- is(tree.view.rowCount, 1, "We have 1 autocomplete result");
- tagsField.popup.selectedIndex = 0;
- is(tree.view.selection.count, 1,
- "We have selected a tag from the autocomplete popup");
- info("About to focus the autocomplete results tree");
- tree.focus();
- EventUtils.synthesizeKey("VK_RETURN", {}, self.window);
- break;
- default:
- ok(false, "unknown event: " + aEvent.type);
- return;
- }
- }
- };
- tagsField.popup.addEventListener("popupshown", popupListener, true);
- tagsField.popup.addEventListener("popuphidden", popupListener, true);
-
- // Open tags autocomplete popup.
- info("About to focus the tagsField");
- executeSoon(() => {
- tagsField.focus();
- tagsField.value = "";
- EventUtils.synthesizeKey("t", {}, this.window);
- });
- },
-
- finish: function() {
- SidebarUI.hide();
- runNextTest();
- },
-
- cleanup: function() {
- // Check tags have not changed.
- var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL));
- is(tags[0], "testTag", "Tag on node has not changed");
-
- // Cleanup.
- PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL), ["testTag"]);
- PlacesUtils.bookmarks.removeItem(this._itemId);
- }
-});
-
-// ------------------------------------------------------------------------------
-// Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel
-
-gTests.push({
- desc: "Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel",
- sidebar: SIDEBAR_BOOKMARKS_ID,
- action: ACTION_EDIT,
- itemType: null,
- window: null,
- _itemId: null,
- _cleanShutdown: false,
-
- setup: function(aCallback) {
- // Add a bookmark in unsorted bookmarks folder.
- this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL));
- ok(this._itemId > 0, "Correctly added a bookmark");
- // Add a tag to this bookmark.
- PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL),
- ["testTag"]);
- var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL));
- is(tags[0], "testTag", "Correctly added a tag");
- aCallback();
- },
-
- selectNode: function(tree) {
- tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]);
- PlacesUtils.asContainer(tree.selectedNode).containerOpen = true;
- tree.selectItems([this._itemId]);
- is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected");
- },
-
- run: function() {
- // open tags autocomplete and press enter
- var tagsField = this.window.document.getElementById("editBMPanel_tagsField");
- var self = this;
-
- this.window.addEventListener("unload", function(event) {
- self.window.removeEventListener("unload", arguments.callee, true);
- tagsField.popup.removeEventListener("popuphidden", popupListener, true);
- ok(self._cleanShutdown, "Dialog window should not be closed by pressing Escape on the autocomplete popup");
- executeSoon(function () {
- self.finish();
- });
- }, true);
-
- var popupListener = {
- handleEvent: function(aEvent) {
- switch (aEvent.type) {
- case "popuphidden":
- // Everything worked fine.
- self._cleanShutdown = true;
- self.window.document.documentElement.cancelDialog();
- break;
- case "popupshown":
- tagsField.popup.removeEventListener("popupshown", this, true);
- // In case this test fails the window will close, the test will fail
- // since we didn't set _cleanShutdown.
- var tree = tagsField.popup.tree;
- // Focus and select first result.
- isnot(tree, null, "Autocomplete results tree exists");
- is(tree.view.rowCount, 1, "We have 1 autocomplete result");
- tagsField.popup.selectedIndex = 0;
- is(tree.view.selection.count, 1,
- "We have selected a tag from the autocomplete popup");
- info("About to focus the autocomplete results tree");
- tree.focus();
- EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window);
- break;
- default:
- ok(false, "unknown event: " + aEvent.type);
- return;
- }
- }
- };
- tagsField.popup.addEventListener("popupshown", popupListener, true);
- tagsField.popup.addEventListener("popuphidden", popupListener, true);
-
- // Open tags autocomplete popup.
- info("About to focus the tagsField");
- tagsField.focus();
- tagsField.value = "";
- EventUtils.synthesizeKey("t", {}, this.window);
- },
-
- finish: function() {
- SidebarUI.hide();
- runNextTest();
- },
-
- cleanup: function() {
- // Check tags have not changed.
- var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL));
- is(tags[0], "testTag", "Tag on node has not changed");
-
- // Cleanup.
- PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL),
- ["testTag"]);
- PlacesUtils.bookmarks.removeItem(this._itemId);
- }
-});
-
-// ------------------------------------------------------------------------------
-// Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog
-
-gTests.push({
- desc: " Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog",
- sidebar: SIDEBAR_HISTORY_ID,
- action: ACTION_ADD,
- historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW,
- window: null,
-
- setup: function(aCallback) {
- // Add a visit.
- PlacesTestUtils.addVisits(
- {uri: PlacesUtils._uri(TEST_URL),
- transition: PlacesUtils.history.TRANSITION_TYPED}
- ).then(aCallback);
- },
-
- selectNode: function(tree) {
- var visitNode = tree.view.nodeForTreeIndex(0);
- tree.selectNode(visitNode);
- is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected");
- is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked");
- },
-
- run: function() {
- // Open folder selector.
- var foldersExpander = this.window.document.getElementById("editBMPanel_foldersExpander");
- var folderTree = this.window.document.getElementById("editBMPanel_folderTree");
- var self = this;
-
- this.window.addEventListener("unload", function(event) {
- self.window.removeEventListener("unload", arguments.callee, true);
- ok(self._cleanShutdown, "Dialog window should not be closed by pressing ESC in folder name textbox");
- executeSoon(function () {
- self.finish();
- });
- }, true);
-
- folderTree.addEventListener("DOMAttrModified", function onDOMAttrModified(event) {
- if (event.attrName != "place")
- return;
- folderTree.removeEventListener("DOMAttrModified", arguments.callee, false);
- executeSoon(function () {
- // Create a new folder.
- var newFolderButton = self.window.document.getElementById("editBMPanel_newFolderButton");
- newFolderButton.doCommand();
- ok(folderTree.hasAttribute("editing"),
- "We are editing new folder name in folder tree");
-
- // Press Escape to discard editing new folder name.
- EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window);
- ok(!folderTree.hasAttribute("editing"),
- "We have finished editing folder name in folder tree");
- self._cleanShutdown = true;
- self.window.document.documentElement.cancelDialog();
- });
- }, false);
- foldersExpander.doCommand();
- },
-
- finish: function() {
- SidebarUI.hide();
- runNextTest();
- },
-
- cleanup: function() {
- return PlacesTestUtils.clearHistory();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-function test() {
- waitForExplicitFinish();
- // This test can take some time, if we timeout too early it could run
- // in the middle of other tests, or hang them.
- requestLongerTimeout(2);
-
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils in context");
- ok(PlacesUIUtils, "PlacesUIUtils in context");
-
- // kick off tests
- runNextTest();
-}
-
-function runNextTest() {
- // Cleanup from previous test.
- if (gCurrentTest) {
- Promise.resolve(gCurrentTest.cleanup()).then(() => {
- info("End of test: " + gCurrentTest.desc);
- gCurrentTest = null;
- waitForAsyncUpdates(runNextTest);
- });
- return;
- }
-
- if (gTests.length > 0) {
- // Goto next tests.
- gCurrentTest = gTests.shift();
- info("Start of test: " + gCurrentTest.desc);
- gCurrentTest.setup(function() {
- execute_test_in_sidebar();
- });
- }
- else {
- // Finished all tests.
- finish();
- }
-}
-
-/**
- * Global functions to run a test in Properties dialog context.
- */
-
-function execute_test_in_sidebar() {
- var sidebar = document.getElementById("sidebar");
- sidebar.addEventListener("load", function() {
- sidebar.removeEventListener("load", arguments.callee, true);
- // Need to executeSoon since the tree is initialized on sidebar load.
- executeSoon(open_properties_dialog);
- }, true);
- SidebarUI.show(gCurrentTest.sidebar);
-}
-
-function open_properties_dialog() {
- var sidebar = document.getElementById("sidebar");
-
- // If this is history sidebar, set the required view.
- if (gCurrentTest.sidebar == SIDEBAR_HISTORY_ID)
- sidebar.contentDocument.getElementById(gCurrentTest.historyView).doCommand();
-
- // Get sidebar's Places tree.
- var sidebarTreeID = gCurrentTest.sidebar == SIDEBAR_BOOKMARKS_ID ?
- SIDEBAR_BOOKMARKS_TREE_ID :
- SIDEBAR_HISTORY_TREE_ID;
- var tree = sidebar.contentDocument.getElementById(sidebarTreeID);
- ok(tree, "Sidebar tree has been loaded");
-
- // Ask current test to select the node to edit.
- gCurrentTest.selectNode(tree);
- ok(tree.selectedNode,
- "We have a places node selected: " + tree.selectedNode.title);
-
- // Wait for the Properties dialog.
- function windowObserver(aSubject, aTopic, aData) {
- if (aTopic != "domwindowopened")
- return;
- ww.unregisterNotification(windowObserver);
- let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
- waitForFocus(() => {
- // Windows has been loaded, execute our test now.
- executeSoon(function () {
- // Ensure overlay is loaded
- ok(win.gEditItemOverlay.initialized, "EditItemOverlay is initialized");
- gCurrentTest.window = win;
- try {
- gCurrentTest.run();
- } catch (ex) {
- ok(false, "An error occured during test run: " + ex.message);
- }
- });
- }, win);
- }
- ww.registerNotification(windowObserver);
-
- var command = null;
- switch (gCurrentTest.action) {
- case ACTION_EDIT:
- command = "placesCmd_show:info";
- break;
- case ACTION_ADD:
- if (gCurrentTest.sidebar == SIDEBAR_BOOKMARKS_ID) {
- if (gCurrentTest.itemType == TYPE_FOLDER)
- command = "placesCmd_new:folder";
- else if (gCurrentTest.itemType == TYPE_BOOKMARK)
- command = "placesCmd_new:bookmark";
- else
- ok(false, "You didn't set a valid itemType for adding an item");
- }
- else
- command = "placesCmd_createBookmark";
- break;
- default:
- ok(false, "You didn't set a valid action for this test");
- }
- // Ensure command is enabled for this node.
- ok(tree.controller.isCommandEnabled(command),
- " command '" + command + "' on current selected node is enabled");
-
- // This will open the dialog.
- tree.controller.doCommand(command);
-}
diff --git a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js
deleted file mode 100644
index 1ab9411f3..000000000
--- a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js
+++ /dev/null
@@ -1,256 +0,0 @@
-/* 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/. */
-
-const TEST_URL = "http://www.mozilla.org";
-const TEST_TITLE = "example_title";
-
-var gBookmarksToolbar = window.document.getElementById("PlacesToolbar");
-var dragDirections = { LEFT: 0, UP: 1, RIGHT: 2, DOWN: 3 };
-
-/**
- * Tests dragging on toolbar.
- *
- * We must test these 2 cases:
- * - Dragging toward left, top, right should start a drag.
- * - Dragging toward down should should open the container if the item is a
- * container, drag the item otherwise.
- *
- * @param aElement
- * DOM node element we will drag
- * @param aExpectedDragData
- * Array of flavors and values in the form:
- * [ ["text/plain: sometext", "text/html: <b>sometext</b>"], [...] ]
- * Pass an empty array to check that drag even has been canceled.
- * @param aDirection
- * Direction for the dragging gesture, see dragDirections helper object.
- */
-function synthesizeDragWithDirection(aElement, aExpectedDragData, aDirection, aCallback) {
- // Dragstart listener function.
- gBookmarksToolbar.addEventListener("dragstart", function(event)
- {
- info("A dragstart event has been trapped.");
- var dataTransfer = event.dataTransfer;
- is(dataTransfer.mozItemCount, aExpectedDragData.length,
- "Number of dragged items should be the same.");
-
- for (var t = 0; t < dataTransfer.mozItemCount; t++) {
- var types = dataTransfer.mozTypesAt(t);
- var expecteditem = aExpectedDragData[t];
- is(types.length, expecteditem.length,
- "Number of flavors for item " + t + " should be the same.");
-
- for (var f = 0; f < types.length; f++) {
- is(types[f], expecteditem[f].substring(0, types[f].length),
- "Flavor " + types[f] + " for item " + t + " should be the same.");
- is(dataTransfer.mozGetDataAt(types[f], t),
- expecteditem[f].substring(types[f].length + 2),
- "Contents for item " + t + " with flavor " + types[f] + " should be the same.");
- }
- }
-
- if (!aExpectedDragData.length)
- ok(event.defaultPrevented, "Drag has been canceled.");
-
- event.preventDefault();
- event.stopPropagation();
-
- gBookmarksToolbar.removeEventListener("dragstart", arguments.callee, false);
-
- // This is likely to cause a click event, and, in case we are dragging a
- // bookmark, an unwanted page visit. Prevent the click event.
- aElement.addEventListener("click", prevent, false);
- EventUtils.synthesizeMouse(aElement,
- startingPoint.x + xIncrement * 9,
- startingPoint.y + yIncrement * 9,
- { type: "mouseup" });
- aElement.removeEventListener("click", prevent, false);
-
- // Cleanup eventually opened menus.
- if (aElement.localName == "menu" && aElement.open)
- aElement.open = false;
- aCallback()
- }, false);
-
- var prevent = function(aEvent) { aEvent.preventDefault(); }
-
- var xIncrement = 0;
- var yIncrement = 0;
-
- switch (aDirection) {
- case dragDirections.LEFT:
- xIncrement = -1;
- break;
- case dragDirections.RIGHT:
- xIncrement = +1;
- break;
- case dragDirections.UP:
- yIncrement = -1;
- break;
- case dragDirections.DOWN:
- yIncrement = +1;
- break;
- }
-
- var rect = aElement.getBoundingClientRect();
- var startingPoint = { x: (rect.right - rect.left)/2,
- y: (rect.bottom - rect.top)/2 };
-
- EventUtils.synthesizeMouse(aElement,
- startingPoint.x,
- startingPoint.y,
- { type: "mousedown" });
- EventUtils.synthesizeMouse(aElement,
- startingPoint.x + xIncrement * 1,
- startingPoint.y + yIncrement * 1,
- { type: "mousemove" });
- EventUtils.synthesizeMouse(aElement,
- startingPoint.x + xIncrement * 9,
- startingPoint.y + yIncrement * 9,
- { type: "mousemove" });
-}
-
-function getToolbarNodeForItemId(aItemId) {
- var children = document.getElementById("PlacesToolbarItems").childNodes;
- var node = null;
- for (var i = 0; i < children.length; i++) {
- if (aItemId == children[i]._placesNode.itemId) {
- node = children[i];
- break;
- }
- }
- return node;
-}
-
-function getExpectedDataForPlacesNode(aNode) {
- var wrappedNode = [];
- var flavors = ["text/x-moz-place",
- "text/x-moz-url",
- "text/plain",
- "text/html"];
-
- flavors.forEach(function(aFlavor) {
- var wrappedFlavor = aFlavor + ": " +
- PlacesUtils.wrapNode(aNode, aFlavor);
- wrappedNode.push(wrappedFlavor);
- });
-
- return [wrappedNode];
-}
-
-var gTests = [
-
-// ------------------------------------------------------------------------------
-
- {
- desc: "Drag a folder on toolbar",
- run: function() {
- // Create a test folder to be dragged.
- var folderId = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.toolbarFolderId,
- TEST_TITLE,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- var element = getToolbarNodeForItemId(folderId);
- isnot(element, null, "Found node on toolbar");
-
- isnot(element._placesNode, null, "Toolbar node has an associated Places node.");
- var expectedData = getExpectedDataForPlacesNode(element._placesNode);
-
- info("Dragging left");
- synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT,
- function ()
- {
- info("Dragging right");
- synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT,
- function ()
- {
- info("Dragging up");
- synthesizeDragWithDirection(element, expectedData, dragDirections.UP,
- function ()
- {
- info("Dragging down");
- synthesizeDragWithDirection(element, new Array(), dragDirections.DOWN,
- function () {
- // Cleanup.
- PlacesUtils.bookmarks.removeItem(folderId);
- nextTest();
- });
- });
- });
- });
- }
- },
-
-// ------------------------------------------------------------------------------
-
- {
- desc: "Drag a bookmark on toolbar",
- run: function() {
- // Create a test bookmark to be dragged.
- var itemId = PlacesUtils.bookmarks
- .insertBookmark(PlacesUtils.toolbarFolderId,
- PlacesUtils._uri(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- TEST_TITLE);
- var element = getToolbarNodeForItemId(itemId);
- isnot(element, null, "Found node on toolbar");
-
- isnot(element._placesNode, null, "Toolbar node has an associated Places node.");
- var expectedData = getExpectedDataForPlacesNode(element._placesNode);
-
- info("Dragging left");
- synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT,
- function ()
- {
- info("Dragging right");
- synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT,
- function ()
- {
- info("Dragging up");
- synthesizeDragWithDirection(element, expectedData, dragDirections.UP,
- function ()
- {
- info("Dragging down");
- synthesizeDragWithDirection(element, expectedData, dragDirections.DOWN,
- function () {
- // Cleanup.
- PlacesUtils.bookmarks.removeItem(itemId);
- nextTest();
- });
- });
- });
- });
- }
- },
-];
-
-function nextTest() {
- if (gTests.length) {
- var test = gTests.shift();
- waitForFocus(function() {
- info("Start of test: " + test.desc);
- test.run();
- });
- }
- else if (wasCollapsed) {
- // Collapse the personal toolbar if needed.
- promiseSetToolbarVisibility(toolbar, false).then(finish);
- } else {
- finish();
- }
-}
-
-var toolbar = document.getElementById("PersonalToolbar");
-var wasCollapsed = toolbar.collapsed;
-
-function test() {
- waitForExplicitFinish();
-
- // Uncollapse the personal toolbar if needed.
- if (wasCollapsed) {
- promiseSetToolbarVisibility(toolbar, true).then(nextTest);
- } else {
- nextTest();
- }
-}
-
diff --git a/browser/components/places/tests/browser/browser_forgetthissite_single.js b/browser/components/places/tests/browser/browser_forgetthissite_single.js
deleted file mode 100644
index b1d7936e9..000000000
--- a/browser/components/places/tests/browser/browser_forgetthissite_single.js
+++ /dev/null
@@ -1,78 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_URIs = [
- "http://www.mozilla.org/test1",
- "http://www.mozilla.org/test2"
-];
-
-// This test makes sure that the Forget This Site command is hidden for multiple
-// selections.
-add_task(function* () {
- // Add a history entry.
- ok(PlacesUtils, "checking PlacesUtils, running in chrome context?");
-
- let places = [];
- let transition = PlacesUtils.history.TRANSITION_TYPED;
- TEST_URIs.forEach(uri => places.push({uri: PlacesUtils._uri(uri), transition}));
-
- yield PlacesTestUtils.addVisits(places);
- yield testForgetThisSiteVisibility(1);
- yield testForgetThisSiteVisibility(2);
-
- // Cleanup.
- yield PlacesTestUtils.clearHistory();
-});
-
-var testForgetThisSiteVisibility = Task.async(function* (selectionCount) {
- let organizer = yield promiseLibrary();
-
- // Select History in the left pane.
- organizer.PlacesOrganizer.selectLeftPaneQuery("History");
- let PO = organizer.PlacesOrganizer;
- let histContainer = PO._places.selectedNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- histContainer.containerOpen = true;
- PO._places.selectNode(histContainer.getChild(0));
-
- // Select the first history entry.
- let doc = organizer.document;
- let tree = doc.getElementById("placeContent");
- let selection = tree.view.selection;
- selection.clearSelection();
- selection.rangedSelect(0, selectionCount - 1, true);
- is(selection.count, selectionCount, "The selected range is as big as expected");
-
- // Open the context menu.
- let contextmenu = doc.getElementById("placesContext");
- let popupShown = promisePopupShown(contextmenu);
-
- // Get cell coordinates.
- let rect = tree.treeBoxObject.getCoordsForCellItem(0, tree.columns[0], "text");
- // Initiate a context menu for the selected cell.
- EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {type: "contextmenu", button: 2}, organizer);
- yield popupShown;
-
- let forgetThisSite = doc.getElementById("placesContext_deleteHost");
- let hideForgetThisSite = (selectionCount != 1);
- is(forgetThisSite.hidden, hideForgetThisSite,
- `The Forget this site menu item should ${hideForgetThisSite ? "" : "not "}` +
- ` be hidden with ${selectionCount} items selected`);
-
- // Close the context menu.
- contextmenu.hidePopup();
-
- // Close the library window.
- yield promiseLibraryClosed(organizer);
-});
-
-function promisePopupShown(popup) {
- return new Promise(resolve => {
- popup.addEventListener("popupshown", function onShown() {
- popup.removeEventListener("popupshown", onShown, true);
- resolve();
- }, true);
- });
-}
diff --git a/browser/components/places/tests/browser/browser_history_sidebar_search.js b/browser/components/places/tests/browser/browser_history_sidebar_search.js
deleted file mode 100644
index 89472c4ab..000000000
--- a/browser/components/places/tests/browser/browser_history_sidebar_search.js
+++ /dev/null
@@ -1,64 +0,0 @@
-add_task(function* test () {
- let sidebar = document.getElementById("sidebar");
-
- // Visited pages listed by descending visit date.
- let pages = [
- "http://sidebar.mozilla.org/a",
- "http://sidebar.mozilla.org/b",
- "http://sidebar.mozilla.org/c",
- "http://www.mozilla.org/d",
- ];
-
- // Number of pages that will be filtered out by the search.
- const FILTERED_COUNT = 1;
-
- yield PlacesTestUtils.clearHistory();
-
- // Add some visited page.
- let time = Date.now();
- let places = [];
- for (let i = 0; i < pages.length; i++) {
- places.push({ uri: NetUtil.newURI(pages[i]),
- visitDate: (time - i) * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED });
- }
- yield PlacesTestUtils.addVisits(places);
-
- yield withSidebarTree("history", function* () {
- info("Set 'by last visited' view");
- sidebar.contentDocument.getElementById("bylastvisited").doCommand();
- let tree = sidebar.contentDocument.getElementById("historyTree");
- check_tree_order(tree, pages);
-
- // Set a search value.
- let searchBox = sidebar.contentDocument.getElementById("search-box");
- ok(searchBox, "search box is in context");
- searchBox.value = "sidebar.mozilla";
- searchBox.doCommand();
- check_tree_order(tree, pages, -FILTERED_COUNT);
-
- info("Reset the search");
- searchBox.value = "";
- searchBox.doCommand();
- check_tree_order(tree, pages);
- });
-
- yield PlacesTestUtils.clearHistory();
-});
-
-function check_tree_order(tree, pages, aNumberOfRowsDelta = 0) {
- let treeView = tree.view;
- let columns = tree.columns;
- is(columns.count, 1, "There should be only 1 column in the sidebar");
-
- let found = 0;
- for (let i = 0; i < treeView.rowCount; i++) {
- let node = treeView.nodeForTreeIndex(i);
- // We could inherit delayed visits from previous tests, skip them.
- if (!pages.includes(node.uri))
- continue;
- is(node.uri, pages[i], "Node is in correct position based on its visit date");
- found++;
- }
- ok(found, pages.length + aNumberOfRowsDelta, "Found all expected results");
-}
diff --git a/browser/components/places/tests/browser/browser_library_batch_delete.js b/browser/components/places/tests/browser/browser_library_batch_delete.js
deleted file mode 100644
index 6a907c70f..000000000
--- a/browser/components/places/tests/browser/browser_library_batch_delete.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that Library handles correctly batch deletes.
- */
-
-const TEST_URL = "http://www.batch.delete.me/";
-
-var gTests = [];
-var gLibrary;
-
-// ------------------------------------------------------------------------------
-
-gTests.push({
- desc: "Create and batch remove bookmarks",
- run: function() {
- let testURI = makeURI(TEST_URL);
- PlacesUtils.history.runInBatchMode({
- runBatched: function (aUserData) {
- // Create a folder in unserted and populate it with bookmarks.
- let folder = PlacesUtils.bookmarks.createFolder(
- PlacesUtils.unfiledBookmarksFolderId, "deleteme",
- PlacesUtils.bookmarks.DEFAULT_INDEX
- );
- PlacesUtils.bookmarks.createFolder(
- PlacesUtils.unfiledBookmarksFolderId, "keepme",
- PlacesUtils.bookmarks.DEFAULT_INDEX
- );
- for (let i = 0; i < 10; i++) {
- PlacesUtils.bookmarks.insertBookmark(folder,
- testURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bm" + i);
- }
- }
- }, null);
-
- // Select and open the left pane "History" query.
- let PO = gLibrary.PlacesOrganizer;
- PO.selectLeftPaneQuery("UnfiledBookmarks");
- isnot(PO._places.selectedNode, null, "Selected unsorted bookmarks");
-
- let unsortedNode = PlacesUtils.asContainer(PO._places.selectedNode);
- unsortedNode.containerOpen = true;
- is(unsortedNode.childCount, 2, "Unsorted node has 2 children");
- let folderNode = unsortedNode.getChild(0);
- is(folderNode.title, "deleteme", "Folder found in unsorted bookmarks");
- // Check delete command is available.
- PO._places.selectNode(folderNode);
- is(PO._places.selectedNode.title, "deleteme", "Folder node selected");
- ok(PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
- // Execute the delete command and check bookmark has been removed.
- PO._places.controller.doCommand("cmd_delete");
- ok(!PlacesUtils.bookmarks.isBookmarked(testURI),
- "Bookmark has been correctly removed");
- // Test live update.
- is(unsortedNode.childCount, 1, "Unsorted node has 1 child");
- is(PO._places.selectedNode.title, "keepme", "Folder node selected");
- unsortedNode.containerOpen = false;
- nextTest();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-gTests.push({
- desc: "Ensure correct selection and functionality in Library",
- run: function() {
- let PO = gLibrary.PlacesOrganizer;
- let ContentTree = gLibrary.ContentTree;
- // Move selection forth and back.
- PO.selectLeftPaneQuery("History");
- PO.selectLeftPaneQuery("UnfiledBookmarks");
- // Now select the "keepme" folder in the right pane and delete it.
- ContentTree.view.selectNode(ContentTree.view.result.root.getChild(0));
- is(ContentTree.view.selectedNode.title, "keepme",
- "Found folder in content pane");
- // Test live update.
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- makeURI(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bm");
- is(ContentTree.view.result.root.childCount, 2,
- "Right pane was correctly updated");
- nextTest();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-function test() {
- waitForExplicitFinish();
- registerCleanupFunction(function () {
- PlacesUtils.bookmarks
- .removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- });
-
- gLibrary = openLibrary(nextTest);
-}
-
-function nextTest() {
- if (gTests.length) {
- var test = gTests.shift();
- info("Start of test: " + test.desc);
- test.run();
- }
- else {
- // Close Library window.
- gLibrary.close();
- finish();
- }
-}
diff --git a/browser/components/places/tests/browser/browser_library_commands.js b/browser/components/places/tests/browser/browser_library_commands.js
deleted file mode 100644
index e3bb75a34..000000000
--- a/browser/components/places/tests/browser/browser_library_commands.js
+++ /dev/null
@@ -1,235 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Test enabled commands in the left pane folder of the Library.
- */
-
-const TEST_URI = NetUtil.newURI("http://www.mozilla.org/");
-
-registerCleanupFunction(function* () {
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_date_container() {
- let library = yield promiseLibrary();
- info("Ensure date containers under History cannot be cut but can be deleted");
-
- yield PlacesTestUtils.addVisits(TEST_URI);
-
- // Select and open the left pane "History" query.
- let PO = library.PlacesOrganizer;
-
- PO.selectLeftPaneQuery('History');
- isnot(PO._places.selectedNode, null, "We correctly selected History");
-
- // Check that both delete and cut commands are disabled, cause this is
- // a child of the left pane folder.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is disabled");
- let historyNode = PlacesUtils.asContainer(PO._places.selectedNode);
- historyNode.containerOpen = true;
-
- // Check that we have a child container. It is "Today" container.
- is(historyNode.childCount, 1, "History node has one child");
- let todayNode = historyNode.getChild(0);
- let todayNodeExpectedTitle = PlacesUtils.getString("finduri-AgeInDays-is-0");
- is(todayNode.title, todayNodeExpectedTitle,
- "History child is the expected container");
-
- // Select "Today" container.
- PO._places.selectNode(todayNode);
- is(PO._places.selectedNode, todayNode,
- "We correctly selected Today container");
- // Check that delete command is enabled but cut command is disabled, cause
- // this is an history item.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
-
- // Execute the delete command and check visit has been removed.
- let promiseURIRemoved = promiseHistoryNotification("onDeleteURI",
- v => TEST_URI.equals(v));
- PO._places.controller.doCommand("cmd_delete");
- yield promiseURIRemoved;
-
- // Test live update of "History" query.
- is(historyNode.childCount, 0, "History node has no more children");
-
- historyNode.containerOpen = false;
-
- ok(!(yield promiseIsURIVisited(TEST_URI)), "Visit has been removed");
-
- library.close();
-});
-
-add_task(function* test_query_on_toolbar() {
- let library = yield promiseLibrary();
- info("Ensure queries can be cut or deleted");
-
- // Select and open the left pane "Bookmarks Toolbar" folder.
- let PO = library.PlacesOrganizer;
-
- PO.selectLeftPaneQuery('BookmarksToolbar');
- isnot(PO._places.selectedNode, null, "We have a valid selection");
- is(PlacesUtils.getConcreteItemId(PO._places.selectedNode),
- PlacesUtils.toolbarFolderId,
- "We have correctly selected bookmarks toolbar node.");
-
- // Check that both cut and delete commands are disabled, cause this is a child
- // of AllBookmarksFolderId.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is disabled");
-
- let toolbarNode = PlacesUtils.asContainer(PO._places.selectedNode);
- toolbarNode.containerOpen = true;
-
- // Add an History query to the toolbar.
- let query = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "place:sort=4",
- title: "special_query",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0 });
-
- // Get first child and check it is the just inserted query.
- ok(toolbarNode.childCount > 0, "Toolbar node has children");
- let queryNode = toolbarNode.getChild(0);
- is(queryNode.title, "special_query", "Query node is correctly selected");
-
- // Select query node.
- PO._places.selectNode(queryNode);
- is(PO._places.selectedNode, queryNode, "We correctly selected query node");
-
- // Check that both cut and delete commands are enabled.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is enabled");
- ok(PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
-
- // Execute the delete command and check bookmark has been removed.
- let promiseItemRemoved = promiseBookmarksNotification("onItemRemoved",
- (...args) => query.guid == args[5]);
- PO._places.controller.doCommand("cmd_delete");
- yield promiseItemRemoved;
-
- is((yield PlacesUtils.bookmarks.fetch(query.guid)), null,
- "Query node bookmark has been correctly removed");
-
- toolbarNode.containerOpen = false;
-
- library.close();
-});
-
-add_task(function* test_search_contents() {
- yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "example page",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: 0 });
-
- let library = yield promiseLibrary();
- info("Ensure query contents can be cut or deleted");
-
- // Select and open the left pane "Bookmarks Toolbar" folder.
- let PO = library.PlacesOrganizer;
-
- PO.selectLeftPaneQuery('BookmarksToolbar');
- isnot(PO._places.selectedNode, null, "We have a valid selection");
- is(PlacesUtils.getConcreteItemId(PO._places.selectedNode),
- PlacesUtils.toolbarFolderId,
- "We have correctly selected bookmarks toolbar node.");
-
- let searchBox = library.document.getElementById("searchFilter");
- searchBox.value = "example";
- library.PlacesSearchBox.search(searchBox.value);
-
- let bookmarkNode = library.ContentTree.view.selectedNode;
- is(bookmarkNode.uri, "http://example.com/", "Found the expected bookmark");
-
- // Check that both cut and delete commands are enabled.
- ok(library.ContentTree.view.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(library.ContentTree.view.controller.isCommandEnabled("cmd_cut"),
- "Cut command is enabled");
- ok(library.ContentTree.view.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
-
- library.close();
-});
-
-add_task(function* test_tags() {
- yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "example page",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: 0 });
- PlacesUtils.tagging.tagURI(NetUtil.newURI("http://example.com/"), ["test"]);
-
- let library = yield promiseLibrary();
- info("Ensure query contents can be cut or deleted");
-
- // Select and open the left pane "Bookmarks Toolbar" folder.
- let PO = library.PlacesOrganizer;
-
- PO.selectLeftPaneQuery('Tags');
- let tagsNode = PO._places.selectedNode;
- isnot(tagsNode, null, "We have a valid selection");
- let tagsTitle = PlacesUtils.getString("TagsFolderTitle");
- is(tagsNode.title, tagsTitle,
- "Tags has been properly selected");
-
- // Check that both cut and delete commands are disabled.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is disabled");
-
- // Now select the tag.
- PlacesUtils.asContainer(tagsNode).containerOpen = true;
- let tag = tagsNode.getChild(0);
- PO._places.selectNode(tag);
- is(PO._places.selectedNode.title, "test",
- "The created tag has been properly selected");
-
- // Check that cut is disabled but delete is enabled.
- ok(PO._places.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(PO._places.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
-
- let bookmarkNode = library.ContentTree.view.selectedNode;
- is(bookmarkNode.uri, "http://example.com/", "Found the expected bookmark");
-
- // Check that both cut and delete commands are enabled.
- ok(library.ContentTree.view.controller.isCommandEnabled("cmd_copy"),
- "Copy command is enabled");
- ok(!library.ContentTree.view.controller.isCommandEnabled("cmd_cut"),
- "Cut command is disabled");
- ok(library.ContentTree.view.controller.isCommandEnabled("cmd_delete"),
- "Delete command is enabled");
-
- tagsNode.containerOpen = false;
-
- library.close();
-});
diff --git a/browser/components/places/tests/browser/browser_library_downloads.js b/browser/components/places/tests/browser/browser_library_downloads.js
deleted file mode 100644
index 81daadd71..000000000
--- a/browser/components/places/tests/browser/browser_library_downloads.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 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/. */
-
-/*
- * Tests bug 564900: Add folder specifically for downloads to Library left pane.
- * https://bugzilla.mozilla.org/show_bug.cgi?id=564900
- * This test visits various pages then opens the Library and ensures
- * that both the Downloads folder shows up and that the correct visits
- * are shown in it.
- */
-
-var now = Date.now();
-
-function test() {
- waitForExplicitFinish();
-
- let onLibraryReady = function(win) {
- // Add visits to compare contents with.
- let places = [
- { uri: NetUtil.newURI("http://mozilla.com"),
- visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_TYPED) ]
- },
- { uri: NetUtil.newURI("http://google.com"),
- visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_DOWNLOAD) ]
- },
- { uri: NetUtil.newURI("http://en.wikipedia.org"),
- visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_TYPED) ]
- },
- { uri: NetUtil.newURI("http://ubuntu.org"),
- visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_DOWNLOAD) ]
- },
- ]
- PlacesUtils.asyncHistory.updatePlaces(places, {
- handleResult: function () {},
- handleError: function () {
- ok(false, "gHistory.updatePlaces() failed");
- },
- handleCompletion: function () {
- // Make sure Downloads is present.
- isnot(win.PlacesOrganizer._places.selectedNode, null,
- "Downloads is present and selected");
-
-
- // Check results.
- let contentRoot = win.ContentArea.currentView.result.root;
- let len = contentRoot.childCount;
- const TEST_URIS = ["http://ubuntu.org/", "http://google.com/"];
- for (let i = 0; i < len; i++) {
- is(contentRoot.getChild(i).uri, TEST_URIS[i],
- "Comparing downloads shown at index " + i);
- }
-
- win.close();
- PlacesTestUtils.clearHistory().then(finish);
- }
- })
- }
-
- openLibrary(onLibraryReady, "Downloads");
-}
-
-function VisitInfo(aTransitionType)
-{
- this.transitionType =
- aTransitionType === undefined ?
- PlacesUtils.history.TRANSITION_LINK : aTransitionType;
- this.visitDate = now++ * 1000;
-}
-VisitInfo.prototype = {}
diff --git a/browser/components/places/tests/browser/browser_library_infoBox.js b/browser/components/places/tests/browser/browser_library_infoBox.js
deleted file mode 100644
index 17cd78f8c..000000000
--- a/browser/components/places/tests/browser/browser_library_infoBox.js
+++ /dev/null
@@ -1,197 +0,0 @@
-/* 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/. */
-
-/**
- * Test appropriate visibility of infoBoxExpanderWrapper and
- * additionalInfoFields in infoBox section of library
- */
-
-const TEST_URI = "http://www.mozilla.org/";
-
-var gTests = [];
-var gLibrary;
-
-// ------------------------------------------------------------------------------
-
-gTests.push({
- desc: "Bug 430148 - Remove or hide the more/less button in details pane...",
- run: function() {
- var PO = gLibrary.PlacesOrganizer;
- let ContentTree = gLibrary.ContentTree;
- var infoBoxExpanderWrapper = getAndCheckElmtById("infoBoxExpanderWrapper");
-
- function addVisitsCallback() {
- // open all bookmarks node
- PO.selectLeftPaneQuery("AllBookmarks");
- isnot(PO._places.selectedNode, null,
- "Correctly selected all bookmarks node.");
- checkInfoBoxSelected(PO);
- ok(infoBoxExpanderWrapper.hidden,
- "Expander button is hidden for all bookmarks node.");
- checkAddInfoFieldsCollapsed(PO);
-
- // open history node
- PO.selectLeftPaneQuery("History");
- isnot(PO._places.selectedNode, null, "Correctly selected history node.");
- checkInfoBoxSelected(PO);
- ok(infoBoxExpanderWrapper.hidden,
- "Expander button is hidden for history node.");
- checkAddInfoFieldsCollapsed(PO);
-
- // open history child node
- var historyNode = PO._places.selectedNode.
- QueryInterface(Ci.nsINavHistoryContainerResultNode);
- historyNode.containerOpen = true;
- var childNode = historyNode.getChild(0);
- isnot(childNode, null, "History node first child is not null.");
- PO._places.selectNode(childNode);
- checkInfoBoxSelected(PO);
- ok(infoBoxExpanderWrapper.hidden,
- "Expander button is hidden for history child node.");
- checkAddInfoFieldsCollapsed(PO);
-
- // open history item
- var view = ContentTree.view.view;
- ok(view.rowCount > 0, "History item exists.");
- view.selection.select(0);
- ok(infoBoxExpanderWrapper.hidden,
- "Expander button is hidden for history item.");
- checkAddInfoFieldsCollapsed(PO);
-
- historyNode.containerOpen = false;
-
- // open bookmarks menu node
- PO.selectLeftPaneQuery("BookmarksMenu");
- isnot(PO._places.selectedNode, null,
- "Correctly selected bookmarks menu node.");
- checkInfoBoxSelected(PO);
- ok(infoBoxExpanderWrapper.hidden,
- "Expander button is hidden for bookmarks menu node.");
- checkAddInfoFieldsCollapsed(PO);
-
- // open recently bookmarked node
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- NetUtil.newURI("place:folder=BOOKMARKS_MENU" +
- "&folder=UNFILED_BOOKMARKS" +
- "&folder=TOOLBAR" +
- "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
- "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING +
- "&maxResults=10" +
- "&excludeQueries=1"),
- 0, "Recent Bookmarks");
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- NetUtil.newURI("http://mozilla.org/"),
- 1, "Mozilla");
- var menuNode = PO._places.selectedNode.
- QueryInterface(Ci.nsINavHistoryContainerResultNode);
- menuNode.containerOpen = true;
- childNode = menuNode.getChild(0);
- isnot(childNode, null, "Bookmarks menu child node exists.");
- is(childNode.title, "Recent Bookmarks",
- "Correctly selected recently bookmarked node.");
- PO._places.selectNode(childNode);
- checkInfoBoxSelected(PO);
- ok(!infoBoxExpanderWrapper.hidden,
- "Expander button is not hidden for recently bookmarked node.");
- checkAddInfoFieldsNotCollapsed(PO);
-
- // open first bookmark
- view = ContentTree.view.view;
- ok(view.rowCount > 0, "Bookmark item exists.");
- view.selection.select(0);
- checkInfoBoxSelected(PO);
- ok(!infoBoxExpanderWrapper.hidden,
- "Expander button is not hidden for bookmark item.");
- checkAddInfoFieldsNotCollapsed(PO);
- checkAddInfoFields(PO, "bookmark item");
-
- menuNode.containerOpen = false;
-
- PlacesTestUtils.clearHistory().then(nextTest);
- }
- // add a visit to browser history
- PlacesTestUtils.addVisits(
- { uri: PlacesUtils._uri(TEST_URI), visitDate: Date.now() * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED }
- ).then(addVisitsCallback);
- }
-});
-
-function checkInfoBoxSelected(PO) {
- is(getAndCheckElmtById("detailsDeck").selectedIndex, 1,
- "Selected element in detailsDeck is infoBox.");
-}
-
-function checkAddInfoFieldsCollapsed(PO) {
- PO._additionalInfoFields.forEach(function (id) {
- ok(getAndCheckElmtById(id).collapsed,
- "Additional info field correctly collapsed: #" + id);
- });
-}
-
-function checkAddInfoFieldsNotCollapsed(PO) {
- ok(PO._additionalInfoFields.some(function (id) {
- return !getAndCheckElmtById(id).collapsed;
- }), "Some additional info field correctly not collapsed");
-}
-
-function checkAddInfoFields(PO, nodeName) {
- ok(true, "Checking additional info fields visibiity for node: " + nodeName);
- var expanderButton = getAndCheckElmtById("infoBoxExpander");
-
- // make sure additional fields are hidden by default
- PO._additionalInfoFields.forEach(function (id) {
- ok(getAndCheckElmtById(id).hidden,
- "Additional info field correctly hidden by default: #" + id);
- });
-
- // toggle fields and make sure they are hidden/unhidden as expected
- expanderButton.click();
- PO._additionalInfoFields.forEach(function (id) {
- ok(!getAndCheckElmtById(id).hidden,
- "Additional info field correctly unhidden after toggle: #" + id);
- });
- expanderButton.click();
- PO._additionalInfoFields.forEach(function (id) {
- ok(getAndCheckElmtById(id).hidden,
- "Additional info field correctly hidden after toggle: #" + id);
- });
-}
-
-function getAndCheckElmtById(id) {
- var elmt = gLibrary.document.getElementById(id);
- isnot(elmt, null, "Correctly got element: #" + id);
- return elmt;
-}
-
-// ------------------------------------------------------------------------------
-
-function nextTest() {
- if (gTests.length) {
- var test = gTests.shift();
- ok(true, "TEST: " + test.desc);
- dump("TEST: " + test.desc + "\n");
- test.run();
- }
- else {
- // Close Library window.
- gLibrary.close();
- // No need to cleanup anything, we have a correct left pane now.
- finish();
- }
-}
-
-function test() {
- waitForExplicitFinish();
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils is running in chrome context");
- ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context");
-
- // Open Library.
- openLibrary(function (library) {
- gLibrary = library;
- gLibrary.PlacesOrganizer._places.focus();
- nextTest(gLibrary);
- });
-}
diff --git a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js
deleted file mode 100644
index 7cea38f20..000000000
--- a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Test we correctly fix broken Library left pane queries names.
- */
-
-// Array of left pane queries objects, each one has the following properties:
-// name: query's identifier got from annotations,
-// itemId: query's itemId,
-// correctTitle: original and correct query's title.
-var leftPaneQueries = [];
-
-function onLibraryReady(organizer) {
- // Check titles have been fixed.
- for (var i = 0; i < leftPaneQueries.length; i++) {
- var query = leftPaneQueries[i];
- is(PlacesUtils.bookmarks.getItemTitle(query.itemId),
- query.correctTitle, "Title is correct for query " + query.name);
- if ("concreteId" in query) {
- is(PlacesUtils.bookmarks.getItemTitle(query.concreteId),
- query.concreteTitle, "Concrete title is correct for query " + query.name);
- }
- }
-
- // Close Library window.
- organizer.close();
- // No need to cleanup anything, we have a correct left pane now.
- finish();
-}
-
-function test() {
- waitForExplicitFinish();
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils is running in chrome context");
- ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context");
- ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0,
- "Left pane version in chrome context, current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION );
-
- // Ensure left pane is initialized.
- ok(PlacesUIUtils.leftPaneFolderId > 0, "left pane folder is initialized");
-
- // Get the left pane folder.
- var leftPaneItems = PlacesUtils.annotations
- .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
-
- is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder");
- // Check version.
- var version = PlacesUtils.annotations
- .getItemAnnotation(leftPaneItems[0],
- PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, "Left pane version is actual");
-
- // Get all left pane queries.
- var items = PlacesUtils.annotations
- .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_QUERY_ANNO);
- // Get current queries names.
- for (var i = 0; i < items.length; i++) {
- var itemId = items[i];
- var queryName = PlacesUtils.annotations
- .getItemAnnotation(items[i],
- PlacesUIUtils.ORGANIZER_QUERY_ANNO);
- var query = { name: queryName,
- itemId: itemId,
- correctTitle: PlacesUtils.bookmarks.getItemTitle(itemId) }
- switch (queryName) {
- case "BookmarksToolbar":
- query.concreteId = PlacesUtils.toolbarFolderId;
- query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId);
- break;
- case "BookmarksMenu":
- query.concreteId = PlacesUtils.bookmarksMenuFolderId;
- query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId);
- break;
- case "UnfiledBookmarks":
- query.concreteId = PlacesUtils.unfiledBookmarksFolderId;
- query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId);
- break;
- }
- leftPaneQueries.push(query);
- // Rename to a bad title.
- PlacesUtils.bookmarks.setItemTitle(query.itemId, "badName");
- if ("concreteId" in query)
- PlacesUtils.bookmarks.setItemTitle(query.concreteId, "badName");
- }
-
- PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter);
-
- // Open Library, this will kick-off left pane code.
- openLibrary(onLibraryReady);
-}
diff --git a/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js b/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js
deleted file mode 100644
index b90df120c..000000000
--- a/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function test() {
- waitForExplicitFinish();
- openLibrary(onLibraryReady);
-}
-
-function onLibraryReady(aLibrary) {
- let hierarchy = [ "AllBookmarks", "BookmarksMenu" ];
-
- let folder1 = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.bookmarksMenuFolderId,
- "Folder 1",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- hierarchy.push(folder1);
- let folder2 = PlacesUtils.bookmarks
- .createFolder(folder1, "Folder 2",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- hierarchy.push(folder2);
- let bookmark = PlacesUtils.bookmarks
- .insertBookmark(folder2, NetUtil.newURI("http://example.com/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Bookmark");
-
- registerCleanupFunction(function() {
- PlacesUtils.bookmarks.removeItem(folder1);
- aLibrary.close();
- });
-
- aLibrary.PlacesOrganizer.selectLeftPaneContainerByHierarchy(hierarchy);
-
- is(aLibrary.PlacesOrganizer._places.selectedNode.itemId, folder2,
- "Found the expected left pane selected node");
-
- is(aLibrary.ContentTree.view.view.nodeForTreeIndex(0).itemId, bookmark,
- "Found the expected right pane contents");
-
- finish();
-}
diff --git a/browser/components/places/tests/browser/browser_library_middleclick.js b/browser/components/places/tests/browser/browser_library_middleclick.js
deleted file mode 100644
index 894f89446..000000000
--- a/browser/components/places/tests/browser/browser_library_middleclick.js
+++ /dev/null
@@ -1,279 +0,0 @@
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
- /**
- * Tests middle-clicking items in the Library.
- */
-
-const ENABLE_HISTORY_PREF = "places.history.enabled";
-
-var gLibrary = null;
-var gTests = [];
-var gCurrentTest = null;
-
-// Listener for TabOpen and tabs progress.
-var gTabsListener = {
- _loadedURIs: [],
- _openTabsCount: 0,
-
- handleEvent: function(aEvent) {
- if (aEvent.type != "TabOpen")
- return;
-
- if (++this._openTabsCount == gCurrentTest.URIs.length) {
- is(gBrowser.tabs.length, gCurrentTest.URIs.length + 1,
- "We have opened " + gCurrentTest.URIs.length + " new tab(s)");
- }
-
- var tab = aEvent.target;
- is(tab.ownerGlobal, window,
- "Tab has been opened in current browser window");
- },
-
- onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI,
- aFlags) {
- var spec = aLocationURI.spec;
- ok(true, spec);
- // When a new tab is opened, location is first set to "about:blank", so
- // we can ignore those calls.
- // Ignore multiple notifications for the same URI too.
- if (spec == "about:blank" || this._loadedURIs.includes(spec))
- return;
-
- ok(gCurrentTest.URIs.includes(spec),
- "Opened URI found in list: " + spec);
-
- if (gCurrentTest.URIs.includes(spec))
- this._loadedURIs.push(spec);
-
- if (this._loadedURIs.length == gCurrentTest.URIs.length) {
- // We have correctly opened all URIs.
-
- // Reset arrays.
- this._loadedURIs.length = 0;
-
- this._openTabsCount = 0;
-
- executeSoon(function () {
- // Close all tabs.
- while (gBrowser.tabs.length > 1)
- gBrowser.removeCurrentTab();
-
- // Test finished. This will move to the next one.
- waitForFocus(gCurrentTest.finish, gBrowser.ownerGlobal);
- });
- }
- }
-}
-
-// ------------------------------------------------------------------------------
-// Open bookmark in a new tab.
-
-gTests.push({
- desc: "Open bookmark in a new tab.",
- URIs: ["about:buildconfig"],
- _itemId: -1,
-
- setup: function() {
- var bs = PlacesUtils.bookmarks;
- // Add a new unsorted bookmark.
- this._itemId = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri(this.URIs[0]),
- bs.DEFAULT_INDEX,
- "Title");
- // Select unsorted bookmarks root in the left pane.
- gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- isnot(gLibrary.PlacesOrganizer._places.selectedNode, null,
- "We correctly have selection in the Library left pane");
- // Get our bookmark in the right pane.
- var bookmarkNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0);
- is(bookmarkNode.uri, this.URIs[0], "Found bookmark in the right pane");
- },
-
- finish: function() {
- setTimeout(runNextTest, 0);
- },
-
- cleanup: function() {
- PlacesUtils.bookmarks.removeItem(this._itemId);
- }
-});
-
-// ------------------------------------------------------------------------------
-// Open a folder in tabs.
-
-gTests.push({
- desc: "Open a folder in tabs.",
- URIs: ["about:buildconfig", "about:"],
- _folderId: -1,
-
- setup: function() {
- var bs = PlacesUtils.bookmarks;
- // Create a new folder.
- var folderId = bs.createFolder(bs.unfiledBookmarksFolder,
- "Folder",
- bs.DEFAULT_INDEX);
- this._folderId = folderId;
-
- // Add bookmarks in folder.
- this.URIs.forEach(function(aURI) {
- bs.insertBookmark(folderId,
- PlacesUtils._uri(aURI),
- bs.DEFAULT_INDEX,
- "Title");
- });
-
- // Select unsorted bookmarks root in the left pane.
- gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- isnot(gLibrary.PlacesOrganizer._places.selectedNode, null,
- "We correctly have selection in the Library left pane");
- // Get our bookmark in the right pane.
- var folderNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0);
- is(folderNode.title, "Folder", "Found folder in the right pane");
- },
-
- finish: function() {
- setTimeout(runNextTest, 0);
- },
-
- cleanup: function() {
- PlacesUtils.bookmarks.removeItem(this._folderId);
- }
-});
-
-// ------------------------------------------------------------------------------
-// Open a query in tabs.
-
-gTests.push({
- desc: "Open a query in tabs.",
- URIs: ["about:buildconfig", "about:"],
- _folderId: -1,
- _queryId: -1,
-
- setup: function() {
- var bs = PlacesUtils.bookmarks;
- // Create a new folder.
- var folderId = bs.createFolder(bs.unfiledBookmarksFolder,
- "Folder",
- bs.DEFAULT_INDEX);
- this._folderId = folderId;
-
- // Add bookmarks in folder.
- this.URIs.forEach(function(aURI) {
- bs.insertBookmark(folderId,
- PlacesUtils._uri(aURI),
- bs.DEFAULT_INDEX,
- "Title");
- });
-
- // Create a bookmarks query containing our bookmarks.
- var hs = PlacesUtils.history;
- var options = hs.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- var query = hs.getNewQuery();
- // The colon included in the terms selects only about: URIs. If not included
- // we also may get pages like about.html included in the query result.
- query.searchTerms = "about:";
- var queryString = hs.queriesToQueryString([query], 1, options);
- this._queryId = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri(queryString),
- 0, // It must be the first.
- "Query");
-
- // Select unsorted bookmarks root in the left pane.
- gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- isnot(gLibrary.PlacesOrganizer._places.selectedNode, null,
- "We correctly have selection in the Library left pane");
- // Get our bookmark in the right pane.
- var folderNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0);
- is(folderNode.title, "Query", "Found query in the right pane");
- },
-
- finish: function() {
- setTimeout(runNextTest, 0);
- },
-
- cleanup: function() {
- PlacesUtils.bookmarks.removeItem(this._folderId);
- PlacesUtils.bookmarks.removeItem(this._queryId);
- }
-});
-
-// ------------------------------------------------------------------------------
-
-function test() {
- waitForExplicitFinish();
- // Increase timeout, this test can be quite slow due to waitForFocus calls.
- requestLongerTimeout(2);
-
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils in context");
- ok(PlacesUIUtils, "PlacesUIUtils in context");
-
- // Add tabs listeners.
- gBrowser.tabContainer.addEventListener("TabOpen", gTabsListener, false);
- gBrowser.addTabsProgressListener(gTabsListener);
-
- // Temporary disable history, so we won't record pages navigation.
- gPrefService.setBoolPref(ENABLE_HISTORY_PREF, false);
-
- // Open Library window.
- openLibrary(function (library) {
- gLibrary = library;
- // Kick off tests.
- runNextTest();
- });
-}
-
-function runNextTest() {
- // Cleanup from previous test.
- if (gCurrentTest)
- gCurrentTest.cleanup();
-
- if (gTests.length > 0) {
- // Goto next test.
- gCurrentTest = gTests.shift();
- info("Start of test: " + gCurrentTest.desc);
- // Test setup will set Library so that the bookmark to be opened is the
- // first node in the content (right pane) tree.
- gCurrentTest.setup();
-
- // Middle click on first node in the content tree of the Library.
- gLibrary.focus();
- waitForFocus(function() {
- mouseEventOnCell(gLibrary.ContentTree.view, 0, 0, { button: 1 });
- }, gLibrary);
- }
- else {
- // No more tests.
-
- // Close Library window.
- gLibrary.close();
-
- // Remove tabs listeners.
- gBrowser.tabContainer.removeEventListener("TabOpen", gTabsListener, false);
- gBrowser.removeTabsProgressListener(gTabsListener);
-
- // Restore history.
- try {
- gPrefService.clearUserPref(ENABLE_HISTORY_PREF);
- } catch (ex) {}
-
- finish();
- }
-}
-
-function mouseEventOnCell(aTree, aRowIndex, aColumnIndex, aEventDetails) {
- var selection = aTree.view.selection;
- selection.select(aRowIndex);
- aTree.treeBoxObject.ensureRowIsVisible(aRowIndex);
- var column = aTree.columns[aColumnIndex];
-
- // get cell coordinates
- var rect = aTree.treeBoxObject.getCoordsForCellItem(aRowIndex, column, "text");
-
- EventUtils.synthesizeMouse(aTree.body, rect.x, rect.y,
- aEventDetails, gLibrary);
-}
diff --git a/browser/components/places/tests/browser/browser_library_openFlatContainer.js b/browser/components/places/tests/browser/browser_library_openFlatContainer.js
deleted file mode 100644
index 167b33031..000000000
--- a/browser/components/places/tests/browser/browser_library_openFlatContainer.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-/**
- * Test opening a flat container in the right pane even if its parent in the
- * left pane is closed.
- */
-
-add_task(function* () {
- let folder = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.unfiledBookmarksFolderId,
- "Folder",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let bookmark = PlacesUtils.bookmarks
- .insertBookmark(folder, NetUtil.newURI("http://example.com/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Bookmark");
-
- let library = yield promiseLibrary("AllBookmarks");
- registerCleanupFunction(function () {
- library.close();
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- });
-
- // Select unfiled later, to ensure it's closed.
- library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
- ok(!library.PlacesOrganizer._places.selectedNode.containerOpen,
- "Unfiled container is closed");
-
- let folderNode = library.ContentTree.view.view.nodeForTreeIndex(0);
- is(folderNode.itemId, folder,
- "Found the expected folder in the right pane");
- // Select the folder node in the right pane.
- library.ContentTree.view.selectNode(folderNode);
-
- synthesizeClickOnSelectedTreeCell(library.ContentTree.view,
- { clickCount: 2 });
-
- is(library.ContentTree.view.view.nodeForTreeIndex(0).itemId, bookmark,
- "Found the expected bookmark in the right pane");
-});
diff --git a/browser/components/places/tests/browser/browser_library_open_leak.js b/browser/components/places/tests/browser/browser_library_open_leak.js
deleted file mode 100644
index f002236a9..000000000
--- a/browser/components/places/tests/browser/browser_library_open_leak.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Bug 474831
- * https://bugzilla.mozilla.org/show_bug.cgi?id=474831
- *
- * Tests for leaks caused by simply opening and closing the Places Library
- * window. Opens the Places Library window, waits for it to load, closes it,
- * and finishes.
- */
-
-function test() {
- waitForExplicitFinish();
- openLibrary(function (win) {
- ok(true, "Library has been correctly opened");
- win.close();
- finish();
- });
-}
diff --git a/browser/components/places/tests/browser/browser_library_panel_leak.js b/browser/components/places/tests/browser/browser_library_panel_leak.js
deleted file mode 100644
index 643a261fb..000000000
--- a/browser/components/places/tests/browser/browser_library_panel_leak.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Bug 433231 - Places Library leaks the nsGlobalWindow when closed with a
- * history entry selected.
- * https://bugzilla.mozilla.org/show_bug.cgi?id=433231
- *
- * STRs: Open Library, select an history entry in History, close Library.
- * ISSUE: We were adding a bookmarks observer when editing a bookmark, when
- * selecting an history entry the panel was not un-initialized, and
- * since an histroy entry does not have an itemId, the observer was
- * never removed.
- */
-
-const TEST_URI = "http://www.mozilla.org/";
-
-function test() {
- function onLibraryReady(organizer) {
- let contentTree = organizer.document.getElementById("placeContent");
- isnot(contentTree, null, "Sanity check: placeContent tree should exist");
- isnot(organizer.PlacesOrganizer, null, "Sanity check: PlacesOrganizer should exist");
- isnot(organizer.gEditItemOverlay, null, "Sanity check: gEditItemOverlay should exist");
-
- ok(organizer.gEditItemOverlay.initialized, "gEditItemOverlay is initialized");
- isnot(organizer.gEditItemOverlay.itemId, -1, "Editing a bookmark");
-
- // Select History in the left pane.
- organizer.PlacesOrganizer.selectLeftPaneQuery('History');
- // Select the first history entry.
- let selection = contentTree.view.selection;
- selection.clearSelection();
- selection.rangedSelect(0, 0, true);
- // Check the panel is editing the history entry.
- is(organizer.gEditItemOverlay.itemId, -1, "Editing an history entry");
- // Close Library window.
- organizer.close();
- // Clean up history.
- PlacesTestUtils.clearHistory().then(finish);
- }
-
- waitForExplicitFinish();
- // Add an history entry.
- ok(PlacesUtils, "checking PlacesUtils, running in chrome context?");
- PlacesTestUtils.addVisits(
- {uri: PlacesUtils._uri(TEST_URI), visitDate: Date.now() * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED}
- ).then(() => {
- openLibrary(onLibraryReady);
- });
-}
diff --git a/browser/components/places/tests/browser/browser_library_search.js b/browser/components/places/tests/browser/browser_library_search.js
deleted file mode 100644
index 93af22363..000000000
--- a/browser/components/places/tests/browser/browser_library_search.js
+++ /dev/null
@@ -1,182 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Bug 451151
- * https://bugzilla.mozilla.org/show_bug.cgi?id=451151
- *
- * Summary:
- * Tests frontend Places Library searching -- search, search reset, search scope
- * consistency.
- *
- * Details:
- * Each test below
- * 1. selects a folder in the left pane and ensures that the content tree is
- * appropriately updated,
- * 2. performs a search and ensures that the content tree is correct for the
- * folder and search and that the search UI is visible and appropriate to
- * folder,
- * 5. resets the search and ensures that the content tree is correct and that
- * the search UI is hidden, and
- * 6. if folder scope was clicked, searches again and ensures folder scope
- * remains selected.
- */
-
-const TEST_URL = "http://dummy.mozilla.org/";
-const TEST_DOWNLOAD_URL = "http://dummy.mozilla.org/dummy.pdf";
-
-var gLibrary;
-
-var testCases = [
- function allBookmarksScope() {
- let defScope = getDefaultScope(PlacesUIUtils.allBookmarksFolderId);
- search(PlacesUIUtils.allBookmarksFolderId, "dummy", defScope);
- },
-
- function historyScope() {
- let defScope = getDefaultScope(PlacesUIUtils.leftPaneQueries["History"]);
- search(PlacesUIUtils.leftPaneQueries["History"], "dummy", defScope);
- },
-
- function downloadsScope() {
- let defScope = getDefaultScope(PlacesUIUtils.leftPaneQueries["Downloads"]);
- search(PlacesUIUtils.leftPaneQueries["Downloads"], "dummy", defScope);
- },
-];
-
-/**
- * Returns the default search scope for a given folder.
- *
- * @param aFolderId
- * the item ID of a node in the left pane's tree
- * @return the default scope when the folder is newly selected
- */
-function getDefaultScope(aFolderId) {
- switch (aFolderId) {
- case PlacesUIUtils.leftPaneQueries["History"]:
- return "scopeBarHistory"
- case PlacesUIUtils.leftPaneQueries["Downloads"]:
- return "scopeBarDownloads";
- default:
- return "scopeBarAll";
- }
-}
-
-/**
- * Returns the single nsINavHistoryQuery represented by a given place URI.
- *
- * @param aPlaceURI
- * a URI that represents a single query
- * @return an nsINavHistoryQuery object
- */
-function queryStringToQuery(aPlaceURI) {
- let queries = {};
- PlacesUtils.history.queryStringToQueries(aPlaceURI, queries, {}, {});
- return queries.value[0];
-}
-
-/**
- * Resets the search by clearing the search box's text and ensures that the
- * search scope remains as expected.
- *
- * @param aExpectedScopeButtonId
- * this button should be selected after the reset
- */
-function resetSearch(aExpectedScopeButtonId) {
- search(null, "", aExpectedScopeButtonId);
-}
-
-/**
- * Performs a search for a given folder and search string and ensures that the
- * URI of the right pane's content tree is as expected for the folder and search
- * string. Also ensures that the search scope button is as expected after the
- * search.
- *
- * @param aFolderId
- * the item ID of a node in the left pane's tree
- * @param aSearchStr
- * the search text; may be empty to reset the search
- * @param aExpectedScopeButtonId
- * after searching the selected scope button should be this
- */
-function search(aFolderId, aSearchStr, aExpectedScopeButtonId) {
- let doc = gLibrary.document;
- let folderTree = doc.getElementById("placesList");
- let contentTree = doc.getElementById("placeContent");
-
- // First, ensure that selecting the folder in the left pane updates the
- // content tree properly.
- if (aFolderId) {
- folderTree.selectItems([aFolderId]);
- isnot(folderTree.selectedNode, null,
- "Sanity check: left pane tree should have selection after selecting!");
-
- // getFolders() on a History query returns an empty array, so no use
- // comparing against aFolderId in that case.
- if (aFolderId !== PlacesUIUtils.leftPaneQueries["History"] &&
- aFolderId !== PlacesUIUtils.leftPaneQueries["Downloads"]) {
- // contentTree.place should be equal to contentTree.result.root.uri,
- // but it's not until bug 476952 is fixed.
- let query = queryStringToQuery(contentTree.result.root.uri);
- is(query.getFolders()[0], aFolderId,
- "Content tree's folder should be what was selected in the left pane");
- }
- }
-
- // Second, ensure that searching updates the content tree and search UI
- // properly.
- let searchBox = doc.getElementById("searchFilter");
- searchBox.value = aSearchStr;
- gLibrary.PlacesSearchBox.search(searchBox.value);
- let query = queryStringToQuery(contentTree.result.root.uri);
- if (aSearchStr) {
- is(query.searchTerms, aSearchStr,
- "Content tree's searchTerms should be text in search box");
- }
- else {
- is(query.hasSearchTerms, false,
- "Content tree's searchTerms should not exist after search reset");
- }
-}
-
-/**
- * test() contains window-launching boilerplate that calls this to really kick
- * things off. Add functions to the testCases array, and this will call them.
- */
-function onLibraryAvailable() {
- testCases.forEach(aTest => aTest());
-
- gLibrary.close();
- gLibrary = null;
-
- // Cleanup.
- PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL), ["dummyTag"]);
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- PlacesTestUtils.clearHistory().then(finish);
-}
-
-function test() {
- waitForExplicitFinish();
-
- // Sanity:
- ok(PlacesUtils, "PlacesUtils in context");
-
- // Add visits, a bookmark and a tag.
- PlacesTestUtils.addVisits(
- [{ uri: PlacesUtils._uri(TEST_URL), visitDate: Date.now() * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED },
- { uri: PlacesUtils._uri(TEST_DOWNLOAD_URL), visitDate: Date.now() * 1000,
- transition: PlacesUtils.history.TRANSITION_DOWNLOAD }]
- ).then(() => {
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils._uri(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "dummy");
- PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL), ["dummyTag"]);
-
- gLibrary = openLibrary(onLibraryAvailable);
- });
-}
diff --git a/browser/components/places/tests/browser/browser_library_views_liveupdate.js b/browser/components/places/tests/browser/browser_library_views_liveupdate.js
deleted file mode 100644
index c78ed641a..000000000
--- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* 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/. */
-
-/**
- * Tests Library Left pane view for liveupdate.
- */
-
-var gLibrary = null;
-
-function test() {
- waitForExplicitFinish();
- // This test takes quite some time, and timeouts frequently, so we require
- // more time to run.
- // See Bug 525610.
- requestLongerTimeout(2);
-
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils in context");
- ok(PlacesUIUtils, "PlacesUIUtils in context");
-
- // Open Library, we will check the left pane.
- openLibrary(function (library) {
- gLibrary = library;
- startTest();
- });
-}
-
-/**
- * Adds bookmarks observer, and executes a bunch of bookmarks operations.
- */
-function startTest() {
- var bs = PlacesUtils.bookmarks;
- // Add observers.
- bs.addObserver(bookmarksObserver, false);
- PlacesUtils.annotations.addObserver(bookmarksObserver, false);
- var addedBookmarks = [];
-
- // MENU
- ok(true, "*** Acting on menu bookmarks");
- var id = bs.insertBookmark(bs.bookmarksMenuFolder,
- PlacesUtils._uri("http://bm1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bm1");
- addedBookmarks.push(id);
- id = bs.insertBookmark(bs.bookmarksMenuFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "bm2");
- bs.setItemTitle(id, "bm2_edited");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.bookmarksMenuFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.bookmarksMenuFolder,
- "bmf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "bmf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://bmf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bmf1");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.bookmarksMenuFolder, 0);
-
- // TOOLBAR
- ok(true, "*** Acting on toolbar bookmarks");
- bs.insertBookmark(bs.toolbarFolder,
- PlacesUtils._uri("http://tb1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "tb1");
- bs.setItemTitle(id, "tb1_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(bs.toolbarFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "tb2");
- bs.setItemTitle(id, "tb2_edited");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.toolbarFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.toolbarFolder,
- "tbf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "tbf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://tbf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bmf1");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.toolbarFolder, 0);
-
- // UNSORTED
- ok(true, "*** Acting on unsorted bookmarks");
- id = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri("http://ub1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "ub1");
- bs.setItemTitle(id, "ub1_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "ub2");
- bs.setItemTitle(id, "ub2_edited");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.unfiledBookmarksFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.unfiledBookmarksFolder,
- "ubf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "ubf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://ubf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "ubf1");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.unfiledBookmarksFolder, 0);
-
- // Remove all added bookmarks.
- addedBookmarks.forEach(function (aItem) {
- // If we remove an item after its containing folder has been removed,
- // this will throw, but we can ignore that.
- try {
- bs.removeItem(aItem);
- } catch (ex) {}
- });
-
- // Remove observers.
- bs.removeObserver(bookmarksObserver);
- PlacesUtils.annotations.removeObserver(bookmarksObserver);
- finishTest();
-}
-
-/**
- * Restores browser state and calls finish.
- */
-function finishTest() {
- // Close Library window.
- gLibrary.close();
- finish();
-}
-
-/**
- * The observer is where magic happens, for every change we do it will look for
- * nodes positions in the affected views.
- */
-var bookmarksObserver = {
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver
- , Ci.nsIAnnotationObserver
- ]),
-
- // nsIAnnotationObserver
- onItemAnnotationSet: function() {},
- onItemAnnotationRemoved: function() {},
- onPageAnnotationSet: function() {},
- onPageAnnotationRemoved: function() {},
-
- // nsINavBookmarkObserver
- onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, aItemType,
- aURI) {
- var node = null;
- var index = null;
- [node, index] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places);
- // Left pane should not be updated for normal bookmarks or separators.
- switch (aItemType) {
- case PlacesUtils.bookmarks.TYPE_BOOKMARK:
- var uriString = aURI.spec;
- var isQuery = uriString.substr(0, 6) == "place:";
- if (isQuery) {
- isnot(node, null, "Found new Places node in left pane");
- ok(index >= 0, "Node is at index " + index);
- break;
- }
- // Fallback to separator case if this is not a query.
- case PlacesUtils.bookmarks.TYPE_SEPARATOR:
- is(node, null, "New Places node not added in left pane");
- break;
- default:
- isnot(node, null, "Found new Places node in left pane");
- ok(index >= 0, "Node is at index " + index);
- }
- },
-
- onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) {
- var node = null;
- [node, ] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places);
- is(node, null, "Places node not found in left pane");
- },
-
- onItemMoved: function(aItemId,
- aOldFolderId, aOldIndex,
- aNewFolderId, aNewIndex, aItemType) {
- var node = null;
- var index = null;
- [node, index] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places);
- // Left pane should not be updated for normal bookmarks or separators.
- switch (aItemType) {
- case PlacesUtils.bookmarks.TYPE_BOOKMARK:
- var uriString = PlacesUtils.bookmarks.getBookmarkURI(aItemId).spec;
- var isQuery = uriString.substr(0, 6) == "place:";
- if (isQuery) {
- isnot(node, null, "Found new Places node in left pane");
- ok(index >= 0, "Node is at index " + index);
- break;
- }
- // Fallback to separator case if this is not a query.
- case PlacesUtils.bookmarks.TYPE_SEPARATOR:
- is(node, null, "New Places node not added in left pane");
- break;
- default:
- isnot(node, null, "Found new Places node in left pane");
- ok(index >= 0, "Node is at index " + index);
- }
- },
-
- onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {},
- onEndUpdateBatch: function PSB_onEndUpdateBatch() {},
- onItemVisited: function() {},
- onItemChanged: function PSB_onItemChanged(aItemId, aProperty,
- aIsAnnotationProperty, aNewValue) {
- if (aProperty == "title") {
- let validator = function(aTreeRowIndex) {
- let tree = gLibrary.PlacesOrganizer._places;
- let cellText = tree.view.getCellText(aTreeRowIndex,
- tree.columns.getColumnAt(0));
- return cellText == aNewValue;
- }
- let [node, , valid] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places, validator);
- if (node) // Only visible nodes.
- ok(valid, "Title cell value has been correctly updated");
- }
- }
-};
-
-
-/**
- * Get places node and index for an itemId in a tree view.
- *
- * @param aItemId
- * item id of the item to search.
- * @param aTree
- * Tree to search in.
- * @param aValidator [optional]
- * function to check row validity if found. Defaults to {return true;}.
- * @returns [node, index, valid] or [null, null, false] if not found.
- */
-function getNodeForTreeItem(aItemId, aTree, aValidator) {
-
- function findNode(aContainerIndex) {
- if (aTree.view.isContainerEmpty(aContainerIndex))
- return [null, null, false];
-
- // The rowCount limit is just for sanity, but we will end looping when
- // we have checked the last child of this container or we have found node.
- for (var i = aContainerIndex + 1; i < aTree.view.rowCount; i++) {
- var node = aTree.view.nodeForTreeIndex(i);
-
- if (node.itemId == aItemId) {
- // Minus one because we want relative index inside the container.
- let valid = aValidator ? aValidator(i) : true;
- return [node, i - aTree.view.getParentIndex(i) - 1, valid];
- }
-
- if (PlacesUtils.nodeIsFolder(node)) {
- // Open container.
- aTree.view.toggleOpenState(i);
- // Search inside it.
- var foundNode = findNode(i);
- // Close container.
- aTree.view.toggleOpenState(i);
- // Return node if found.
- if (foundNode[0] != null)
- return foundNode;
- }
-
- // We have finished walking this container.
- if (!aTree.view.hasNextSibling(aContainerIndex + 1, i))
- break;
- }
- return [null, null, false]
- }
-
- // Root node is hidden, so we need to manually walk the first level.
- for (var i = 0; i < aTree.view.rowCount; i++) {
- // Open container.
- aTree.view.toggleOpenState(i);
- // Search inside it.
- var foundNode = findNode(i);
- // Close container.
- aTree.view.toggleOpenState(i);
- // Return node if found.
- if (foundNode[0] != null)
- return foundNode;
- }
- return [null, null, false];
-}
diff --git a/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js b/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js
deleted file mode 100644
index 02d564e28..000000000
--- a/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Tests that visits across frames are correctly represented in the database.
- */
-
-const BASE_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser";
-const PAGE_URL = BASE_URL + "/framedPage.html";
-const LEFT_URL = BASE_URL + "/frameLeft.html";
-const RIGHT_URL = BASE_URL + "/frameRight.html";
-
-add_task(function* test() {
- // We must wait for both frames to be loaded and the visits to be registered.
- let deferredLeftFrameVisit = PromiseUtils.defer();
- let deferredRightFrameVisit = PromiseUtils.defer();
-
- Services.obs.addObserver(function observe(subject) {
- Task.spawn(function* () {
- let url = subject.QueryInterface(Ci.nsIURI).spec;
- if (url == LEFT_URL ) {
- is((yield getTransitionForUrl(url)), null,
- "Embed visits should not get a database entry.");
- deferredLeftFrameVisit.resolve();
- }
- else if (url == RIGHT_URL ) {
- is((yield getTransitionForUrl(url)),
- PlacesUtils.history.TRANSITION_FRAMED_LINK,
- "User activated visits should get a FRAMED_LINK transition.");
- Services.obs.removeObserver(observe, "uri-visit-saved");
- deferredRightFrameVisit.resolve();
- }
- });
- }, "uri-visit-saved", false);
-
- // Open a tab and wait for all the subframes to load.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE_URL);
-
- // Wait for the left frame visit to be registered.
- info("Waiting left frame visit");
- yield deferredLeftFrameVisit.promise;
-
- // Click on the link in the left frame to cause a page load in the
- // right frame.
- info("Clicking link");
- yield ContentTask.spawn(tab.linkedBrowser, {}, function* () {
- content.frames[0].document.getElementById("clickme").click();
- });
-
- // Wait for the right frame visit to be registered.
- info("Waiting right frame visit");
- yield deferredRightFrameVisit.promise;
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-function* getTransitionForUrl(url) {
- // Ensure all the transactions completed.
- yield PlacesTestUtils.promiseAsyncUpdates();
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`
- SELECT visit_type
- FROM moz_historyvisits
- JOIN moz_places h ON place_id = h.id
- WHERE url_hash = hash(:url) AND url = :url`,
- { url });
- if (rows.length) {
- return rows[0].getResultByName("visit_type");
- }
- return null;
-}
diff --git a/browser/components/places/tests/browser/browser_sidebarpanels_click.js b/browser/components/places/tests/browser/browser_sidebarpanels_click.js
deleted file mode 100644
index 80ed2eb2b..000000000
--- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the items in the bookmarks and history sidebar
-// panels are clickable in both LTR and RTL modes.
-
-function test() {
- waitForExplicitFinish();
- ignoreAllUncaughtExceptions();
-
- const BOOKMARKS_SIDEBAR_ID = "viewBookmarksSidebar";
- const BOOKMARKS_SIDEBAR_TREE_ID = "bookmarks-view";
- const HISTORY_SIDEBAR_ID = "viewHistorySidebar";
- const HISTORY_SIDEBAR_TREE_ID = "historyTree";
- const TEST_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser/sidebarpanels_click_test_page.html";
-
- // If a sidebar is already open, close it.
- if (!document.getElementById("sidebar-box").hidden) {
- info("Unexpected sidebar found - a previous test failed to cleanup correctly");
- SidebarUI.hide();
- }
-
- let sidebar = document.getElementById("sidebar");
- let tests = [];
- let currentTest;
-
- tests.push({
- _itemID: null,
- init: function(aCallback) {
- // Add a bookmark to the Unfiled Bookmarks folder.
- this._itemID = PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, PlacesUtils._uri(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "test"
- );
- aCallback();
- },
- prepare: function() {
- },
- selectNode: function(tree) {
- tree.selectItems([this._itemID]);
- },
- cleanup: function(aCallback) {
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- executeSoon(aCallback);
- },
- sidebarName: BOOKMARKS_SIDEBAR_ID,
- treeName: BOOKMARKS_SIDEBAR_TREE_ID,
- desc: "Bookmarks sidebar test"
- });
-
- tests.push({
- init: function(aCallback) {
- // Add a history entry.
- let uri = PlacesUtils._uri(TEST_URL);
- PlacesTestUtils.addVisits({
- uri: uri, visitDate: Date.now() * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED
- }).then(aCallback);
- },
- prepare: function() {
- sidebar.contentDocument.getElementById("byvisited").doCommand();
- },
- selectNode: function(tree) {
- tree.selectNode(tree.view.nodeForTreeIndex(0));
- is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected");
- is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked");
- },
- cleanup: function(aCallback) {
- PlacesTestUtils.clearHistory().then(aCallback);
- },
- sidebarName: HISTORY_SIDEBAR_ID,
- treeName: HISTORY_SIDEBAR_TREE_ID,
- desc: "History sidebar test"
- });
-
- function testPlacesPanel(preFunc, postFunc) {
- currentTest.init(function() {
- SidebarUI.show(currentTest.sidebarName);
- });
-
- sidebar.addEventListener("load", function() {
- sidebar.removeEventListener("load", arguments.callee, true);
- executeSoon(function() {
- currentTest.prepare();
-
- if (preFunc)
- preFunc();
-
- function observer(aSubject, aTopic, aData) {
- info("alert dialog observed as expected");
- Services.obs.removeObserver(observer, "common-dialog-loaded");
- Services.obs.removeObserver(observer, "tabmodal-dialog-loaded");
-
- aSubject.Dialog.ui.button0.click();
-
- executeSoon(function () {
- SidebarUI.hide();
- currentTest.cleanup(postFunc);
- });
- }
- Services.obs.addObserver(observer, "common-dialog-loaded", false);
- Services.obs.addObserver(observer, "tabmodal-dialog-loaded", false);
-
- let tree = sidebar.contentDocument.getElementById(currentTest.treeName);
-
- // Select the inserted places item.
- currentTest.selectNode(tree);
-
- synthesizeClickOnSelectedTreeCell(tree);
- // Now, wait for the observer to catch the alert dialog.
- // If something goes wrong, the test will time out at this stage.
- // Note that for the history sidebar, the URL itself is not opened,
- // and Places will show the load-js-data-url-error prompt as an alert
- // box, which means that the click actually worked, so it's good enough
- // for the purpose of this test.
- });
- }, true);
- }
-
- function changeSidebarDirection(aDirection) {
- sidebar.contentDocument.documentElement.style.direction = aDirection;
- }
-
- function runNextTest() {
- // Remove eventual tabs created by previous sub-tests.
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeTab(gBrowser.tabContainer.lastChild);
- }
-
- if (tests.length == 0) {
- finish();
- }
- else {
- // Create a new tab and run the test.
- gBrowser.selectedTab = gBrowser.addTab();
- currentTest = tests.shift();
- testPlacesPanel(function() {
- changeSidebarDirection("ltr");
- info("Running " + currentTest.desc + " in LTR mode");
- },
- function() {
- testPlacesPanel(function() {
- // Run the test in RTL mode.
- changeSidebarDirection("rtl");
- info("Running " + currentTest.desc + " in RTL mode");
- },
- function() {
- runNextTest();
- });
- });
- }
- }
-
- // Ensure history is clean before starting the test.
- PlacesTestUtils.clearHistory().then(runNextTest);
-}
diff --git a/browser/components/places/tests/browser/browser_sort_in_library.js b/browser/components/places/tests/browser/browser_sort_in_library.js
deleted file mode 100644
index af9c35e59..000000000
--- a/browser/components/places/tests/browser/browser_sort_in_library.js
+++ /dev/null
@@ -1,249 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests the following bugs:
- *
- * Bug 443745 - View>Sort>of "alpha" sort items is default to Z>A instead of A>Z
- * https://bugzilla.mozilla.org/show_bug.cgi?id=443745
- *
- * Bug 444179 - Library>Views>Sort>Sort by Tags does nothing
- * https://bugzilla.mozilla.org/show_bug.cgi?id=444179
- *
- * Basically, fully tests sorting the placeContent tree in the Places Library
- * window. Sorting is verified by comparing the nsINavHistoryResult returned by
- * placeContent.result to the expected sort values.
- */
-
-// Two properties of nsINavHistoryResult control the sort of the tree:
-// sortingMode and sortingAnnotation. sortingMode's value is one of the
-// nsINavHistoryQueryOptions.SORT_BY_* constants. sortingAnnotation is the
-// annotation used to sort for SORT_BY_ANNOTATION_* mode.
-//
-// This lookup table maps the possible values of anonid's of the treecols to
-// objects that represent the treecols' correct state after the user sorts the
-// previously unsorted tree by selecting a column from the Views > Sort menu.
-// sortingMode is constructed from the key and dir properties (i.e.,
-// SORT_BY_<key>_<dir>) and sortingAnnotation is checked against anno. anno
-// may be undefined if key is not "ANNOTATION".
-const SORT_LOOKUP_TABLE = {
- title: { key: "TITLE", dir: "ASCENDING" },
- tags: { key: "TAGS", dir: "ASCENDING" },
- url: { key: "URI", dir: "ASCENDING" },
- date: { key: "DATE", dir: "DESCENDING" },
- visitCount: { key: "VISITCOUNT", dir: "DESCENDING" },
- dateAdded: { key: "DATEADDED", dir: "DESCENDING" },
- lastModified: { key: "LASTMODIFIED", dir: "DESCENDING" },
- description: { key: "ANNOTATION",
- dir: "ASCENDING",
- anno: "bookmarkProperties/description" }
-};
-
-// This is the column that's sorted if one is not specified and the tree is
-// currently unsorted. Set it to a key substring in the name of one of the
-// nsINavHistoryQueryOptions.SORT_BY_* constants, e.g., "TITLE", "URI".
-// Method ViewMenu.setSortColumn in browser/components/places/content/places.js
-// determines this value.
-const DEFAULT_SORT_KEY = "TITLE";
-
-// Part of the test is checking that sorts stick, so each time we sort we need
-// to remember it.
-var prevSortDir = null;
-var prevSortKey = null;
-
-/**
- * Ensures that the sort of aTree is aSortingMode and aSortingAnno.
- *
- * @param aTree
- * the tree to check
- * @param aSortingMode
- * one of the Ci.nsINavHistoryQueryOptions.SORT_BY_* constants
- * @param aSortingAnno
- * checked only if sorting mode is one of the
- * Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_* constants
- */
-function checkSort(aTree, aSortingMode, aSortingAnno) {
- // The placeContent tree's sort is determined by the nsINavHistoryResult it
- // stores. Get it and check that the sort is what the caller expects.
- let res = aTree.result;
- isnot(res, null,
- "sanity check: placeContent.result should not return null");
-
- // Check sortingMode.
- is(res.sortingMode, aSortingMode,
- "column should now have sortingMode " + aSortingMode);
-
- // Check sortingAnnotation, but only if sortingMode is ANNOTATION.
- if ([Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING,
- Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING].
- indexOf(aSortingMode) >= 0) {
- is(res.sortingAnnotation, aSortingAnno,
- "column should now have sorting annotation " + aSortingAnno);
- }
-}
-
-/**
- * Sets the sort of aTree.
- *
- * @param aOrganizerWin
- * the Places window
- * @param aTree
- * the tree to sort
- * @param aUnsortFirst
- * true if the sort should be set to SORT_BY_NONE before sorting by aCol
- * and aDir
- * @param aShouldFail
- * true if setSortColumn should fail on aCol or aDir
- * @param aCol
- * the column of aTree by which to sort
- * @param aDir
- * either "ascending" or "descending"
- */
-function setSort(aOrganizerWin, aTree, aUnsortFirst, aShouldFail, aCol, aDir) {
- if (aUnsortFirst) {
- aOrganizerWin.ViewMenu.setSortColumn();
- checkSort(aTree, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE, "");
-
- // Remember the sort key and direction.
- prevSortKey = null;
- prevSortDir = null;
- }
-
- let failed = false;
- try {
- aOrganizerWin.ViewMenu.setSortColumn(aCol, aDir);
-
- // Remember the sort key and direction.
- if (!aCol && !aDir) {
- prevSortKey = null;
- prevSortDir = null;
- }
- else {
- if (aCol)
- prevSortKey = SORT_LOOKUP_TABLE[aCol.getAttribute("anonid")].key;
- else if (prevSortKey === null)
- prevSortKey = DEFAULT_SORT_KEY;
-
- if (aDir)
- prevSortDir = aDir.toUpperCase();
- else if (prevSortDir === null)
- prevSortDir = SORT_LOOKUP_TABLE[aCol.getAttribute("anonid")].dir;
- }
- } catch (exc) {
- failed = true;
- }
-
- is(failed, !!aShouldFail,
- "setSortColumn on column " +
- (aCol ? aCol.getAttribute("anonid") : "(no column)") +
- " with direction " + (aDir || "(no direction)") +
- " and table previously " + (aUnsortFirst ? "unsorted" : "sorted") +
- " should " + (aShouldFail ? "" : "not ") + "fail");
-}
-
-/**
- * Tries sorting by an invalid column and sort direction.
- *
- * @param aOrganizerWin
- * the Places window
- * @param aPlaceContentTree
- * the placeContent tree in aOrganizerWin
- */
-function testInvalid(aOrganizerWin, aPlaceContentTree) {
- // Invalid column should fail by throwing an exception.
- let bogusCol = document.createElement("treecol");
- bogusCol.setAttribute("anonid", "bogusColumn");
- setSort(aOrganizerWin, aPlaceContentTree, true, true, bogusCol, "ascending");
-
- // Invalid direction reverts to SORT_BY_NONE.
- setSort(aOrganizerWin, aPlaceContentTree, false, false, null, "bogus dir");
- checkSort(aPlaceContentTree, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE, "");
-}
-
-/**
- * Tests sorting aPlaceContentTree by column only and then by both column
- * and direction.
- *
- * @param aOrganizerWin
- * the Places window
- * @param aPlaceContentTree
- * the placeContent tree in aOrganizerWin
- * @param aUnsortFirst
- * true if, before each sort we try, we should sort to SORT_BY_NONE
- */
-function testSortByColAndDir(aOrganizerWin, aPlaceContentTree, aUnsortFirst) {
- let cols = aPlaceContentTree.getElementsByTagName("treecol");
- ok(cols.length > 0, "sanity check: placeContent should contain columns");
-
- for (let i = 0; i < cols.length; i++) {
- let col = cols.item(i);
- ok(col.hasAttribute("anonid"),
- "sanity check: column " + col.id + " should have anonid");
-
- let colId = col.getAttribute("anonid");
- ok(colId in SORT_LOOKUP_TABLE,
- "sanity check: unexpected placeContent column anonid");
-
- let sortConst =
- "SORT_BY_" + SORT_LOOKUP_TABLE[colId].key + "_" +
- (aUnsortFirst ? SORT_LOOKUP_TABLE[colId].dir : prevSortDir);
- let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst];
- let expectedAnno = SORT_LOOKUP_TABLE[colId].anno || "";
-
- // Test sorting by only a column.
- setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, col);
- checkSort(aPlaceContentTree, expectedSortMode, expectedAnno);
-
- // Test sorting by both a column and a direction.
- ["ascending", "descending"].forEach(function (dir) {
- let sortConst =
- "SORT_BY_" + SORT_LOOKUP_TABLE[colId].key + "_" + dir.toUpperCase();
- let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst];
- setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, col, dir);
- checkSort(aPlaceContentTree, expectedSortMode, expectedAnno);
- });
- }
-}
-
-/**
- * Tests sorting aPlaceContentTree by direction only.
- *
- * @param aOrganizerWin
- * the Places window
- * @param aPlaceContentTree
- * the placeContent tree in aOrganizerWin
- * @param aUnsortFirst
- * true if, before each sort we try, we should sort to SORT_BY_NONE
- */
-function testSortByDir(aOrganizerWin, aPlaceContentTree, aUnsortFirst) {
- ["ascending", "descending"].forEach(function (dir) {
- let key = (aUnsortFirst ? DEFAULT_SORT_KEY : prevSortKey);
- let sortConst = "SORT_BY_" + key + "_" + dir.toUpperCase();
- let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst];
- setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, null, dir);
- checkSort(aPlaceContentTree, expectedSortMode, "");
- });
-}
-
-function test() {
- waitForExplicitFinish();
-
- openLibrary(function (win) {
- let tree = win.document.getElementById("placeContent");
- isnot(tree, null, "sanity check: placeContent tree should exist");
- // Run the tests.
- testSortByColAndDir(win, tree, true);
- testSortByColAndDir(win, tree, false);
- testSortByDir(win, tree, true);
- testSortByDir(win, tree, false);
- testInvalid(win, tree);
- // Reset the sort to SORT_BY_NONE.
- setSort(win, tree, false, false);
- // Close the window and finish.
- win.close();
- finish();
- });
-}
diff --git a/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js b/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js
deleted file mode 100644
index 7a0eec22f..000000000
--- a/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js
+++ /dev/null
@@ -1,53 +0,0 @@
-var bookmarksMenuButton = document.getElementById("bookmarks-menu-button");
-var BMB_menuPopup = document.getElementById("BMB_bookmarksPopup");
-var BMB_showAllBookmarks = document.getElementById("BMB_bookmarksShowAll");
-var contextMenu = document.getElementById("placesContext");
-var newBookmarkItem = document.getElementById("placesContext_new:bookmark");
-
-waitForExplicitFinish();
-add_task(function* testPopup() {
- info("Checking popup context menu before moving the bookmarks button");
- yield checkPopupContextMenu();
- let pos = CustomizableUI.getPlacementOfWidget("bookmarks-menu-button").position;
- CustomizableUI.addWidgetToArea("bookmarks-menu-button", CustomizableUI.AREA_PANEL);
- CustomizableUI.addWidgetToArea("bookmarks-menu-button", CustomizableUI.AREA_NAVBAR, pos);
- info("Checking popup context menu after moving the bookmarks button");
- yield checkPopupContextMenu();
-});
-
-function* checkPopupContextMenu() {
- let dropmarker = document.getAnonymousElementByAttribute(bookmarksMenuButton, "anonid", "dropmarker");
- BMB_menuPopup.setAttribute("style", "transition: none;");
- let popupShownPromise = onPopupEvent(BMB_menuPopup, "shown");
- EventUtils.synthesizeMouseAtCenter(dropmarker, {});
- info("Waiting for bookmarks menu to be shown.");
- yield popupShownPromise;
- let contextMenuShownPromise = onPopupEvent(contextMenu, "shown");
- EventUtils.synthesizeMouseAtCenter(BMB_showAllBookmarks, {type: "contextmenu", button: 2 });
- info("Waiting for context menu on bookmarks menu to be shown.");
- yield contextMenuShownPromise;
- ok(!newBookmarkItem.hasAttribute("disabled"), "New bookmark item shouldn't be disabled");
- let contextMenuHiddenPromise = onPopupEvent(contextMenu, "hidden");
- contextMenu.hidePopup();
- BMB_menuPopup.removeAttribute("style");
- info("Waiting for context menu on bookmarks menu to be hidden.");
- yield contextMenuHiddenPromise;
- let popupHiddenPromise = onPopupEvent(BMB_menuPopup, "hidden");
- // Can't use synthesizeMouseAtCenter because the dropdown panel is in the way
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- info("Waiting for bookmarks menu to be hidden.");
- yield popupHiddenPromise;
-}
-
-function onPopupEvent(popup, evt) {
- let fullEvent = "popup" + evt;
- let deferred = new Promise.defer();
- let onPopupHandler = (e) => {
- if (e.target == popup) {
- popup.removeEventListener(fullEvent, onPopupHandler);
- deferred.resolve();
- }
- };
- popup.addEventListener(fullEvent, onPopupHandler);
- return deferred.promise;
-}
diff --git a/browser/components/places/tests/browser/browser_views_liveupdate.js b/browser/components/places/tests/browser/browser_views_liveupdate.js
deleted file mode 100644
index 735d6b168..000000000
--- a/browser/components/places/tests/browser/browser_views_liveupdate.js
+++ /dev/null
@@ -1,475 +0,0 @@
-/* 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/. */
-
-/**
- * Tests Places views (menu, toolbar, tree) for liveupdate.
- */
-
-var toolbar = document.getElementById("PersonalToolbar");
-var wasCollapsed = toolbar.collapsed;
-
-function test() {
- waitForExplicitFinish();
-
- // Uncollapse the personal toolbar if needed.
- if (wasCollapsed) {
- promiseSetToolbarVisibility(toolbar, true).then(openBookmarksSidebar);
- } else {
- openBookmarksSidebar();
- }
-}
-
-function openBookmarksSidebar() {
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils in context");
- ok(PlacesUIUtils, "PlacesUIUtils in context");
-
- // Open bookmarks menu.
- var popup = document.getElementById("bookmarksMenuPopup");
- ok(popup, "Menu popup element exists");
- fakeOpenPopup(popup);
-
- // Open bookmarks sidebar.
- var sidebar = document.getElementById("sidebar");
- sidebar.addEventListener("load", function() {
- sidebar.removeEventListener("load", arguments.callee, true);
- // Need to executeSoon since the tree is initialized on sidebar load.
- executeSoon(startTest);
- }, true);
- SidebarUI.show("viewBookmarksSidebar");
-}
-
-/**
- * Simulates popup opening causing it to populate.
- * We cannot just use menu.open, since it would not work on Mac due to native menubar.
- */
-function fakeOpenPopup(aPopup) {
- var popupEvent = document.createEvent("MouseEvent");
- popupEvent.initMouseEvent("popupshowing", true, true, window, 0,
- 0, 0, 0, 0, false, false, false, false,
- 0, null);
- aPopup.dispatchEvent(popupEvent);
-}
-
-/**
- * Adds bookmarks observer, and executes a bunch of bookmarks operations.
- */
-function startTest() {
- var bs = PlacesUtils.bookmarks;
- // Add observers.
- bs.addObserver(bookmarksObserver, false);
- PlacesUtils.annotations.addObserver(bookmarksObserver, false);
- var addedBookmarks = [];
-
- // MENU
- info("*** Acting on menu bookmarks");
- var id = bs.insertBookmark(bs.bookmarksMenuFolder,
- PlacesUtils._uri("http://bm1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bm1");
- bs.setItemTitle(id, "bm1_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(bs.bookmarksMenuFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "bm2");
- bs.setItemTitle(id, "");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.bookmarksMenuFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.bookmarksMenuFolder,
- "bmf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "bmf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://bmf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bmf1");
- bs.setItemTitle(id, "bmf1_edited");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.bookmarksMenuFolder, 0);
-
- // TOOLBAR
- info("*** Acting on toolbar bookmarks");
- id = bs.insertBookmark(bs.toolbarFolder,
- PlacesUtils._uri("http://tb1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "tb1");
- bs.setItemTitle(id, "tb1_edited");
- addedBookmarks.push(id);
- // Test live update of title.
- bs.setItemTitle(id, "tb1_edited");
- id = bs.insertBookmark(bs.toolbarFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "tb2");
- bs.setItemTitle(id, "");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.toolbarFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.toolbarFolder,
- "tbf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "tbf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://tbf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "tbf1");
- bs.setItemTitle(id, "tbf1_edited");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.toolbarFolder, 0);
-
- // UNSORTED
- info("*** Acting on unsorted bookmarks");
- id = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri("http://ub1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "ub1");
- bs.setItemTitle(id, "ub1_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(bs.unfiledBookmarksFolder,
- PlacesUtils._uri("place:"),
- bs.DEFAULT_INDEX,
- "ub2");
- bs.setItemTitle(id, "ub2_edited");
- addedBookmarks.push(id);
- id = bs.insertSeparator(bs.unfiledBookmarksFolder, bs.DEFAULT_INDEX);
- addedBookmarks.push(id);
- id = bs.createFolder(bs.unfiledBookmarksFolder,
- "ubf",
- bs.DEFAULT_INDEX);
- bs.setItemTitle(id, "ubf_edited");
- addedBookmarks.push(id);
- id = bs.insertBookmark(id,
- PlacesUtils._uri("http://ubf1.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "bubf1");
- bs.setItemTitle(id, "bubf1_edited");
- addedBookmarks.push(id);
- bs.moveItem(id, bs.unfiledBookmarksFolder, 0);
-
- // Remove all added bookmarks.
- addedBookmarks.forEach(function (aItem) {
- // If we remove an item after its containing folder has been removed,
- // this will throw, but we can ignore that.
- try {
- bs.removeItem(aItem);
- } catch (ex) {}
- });
-
- // Remove observers.
- bs.removeObserver(bookmarksObserver);
- PlacesUtils.annotations.removeObserver(bookmarksObserver);
- finishTest();
-}
-
-/**
- * Restores browser state and calls finish.
- */
-function finishTest() {
- // Close bookmarks sidebar.
- SidebarUI.hide();
-
- // Collapse the personal toolbar if needed.
- if (wasCollapsed) {
- promiseSetToolbarVisibility(toolbar, false).then(finish);
- } else {
- finish();
- }
-}
-
-/**
- * The observer is where magic happens, for every change we do it will look for
- * nodes positions in the affected views.
- */
-var bookmarksObserver = {
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver
- , Ci.nsIAnnotationObserver
- ]),
-
- // nsIAnnotationObserver
- onItemAnnotationSet: function() {},
- onItemAnnotationRemoved: function() {},
- onPageAnnotationSet: function() {},
- onPageAnnotationRemoved: function() {},
-
- // nsINavBookmarkObserver
- onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex,
- aItemType, aURI) {
- var views = getViewsForFolder(aFolderId);
- ok(views.length > 0, "Found affected views (" + views.length + "): " + views);
-
- // Check that item has been added in the correct position.
- for (var i = 0; i < views.length; i++) {
- var [node, index] = searchItemInView(aItemId, views[i]);
- isnot(node, null, "Found new Places node in " + views[i]);
- is(index, aIndex, "Node is at index " + index);
- }
- },
-
- onItemRemoved: function PSB_onItemRemoved(aItemId, aFolderId, aIndex,
- aItemType) {
- var views = getViewsForFolder(aFolderId);
- ok(views.length > 0, "Found affected views (" + views.length + "): " + views);
- // Check that item has been removed.
- for (var i = 0; i < views.length; i++) {
- var node = null;
- [node, ] = searchItemInView(aItemId, views[i]);
- is(node, null, "Places node not found in " + views[i]);
- }
- },
-
- onItemMoved: function(aItemId,
- aOldFolderId, aOldIndex,
- aNewFolderId, aNewIndex,
- aItemType) {
- var views = getViewsForFolder(aNewFolderId);
- ok(views.length > 0, "Found affected views: " + views);
-
- // Check that item has been moved in the correct position.
- for (var i = 0; i < views.length; i++) {
- var node = null;
- var index = null;
- [node, index] = searchItemInView(aItemId, views[i]);
- isnot(node, null, "Found new Places node in " + views[i]);
- is(index, aNewIndex, "Node is at index " + index);
- }
- },
-
- onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {},
- onEndUpdateBatch: function PSB_onEndUpdateBatch() {},
- onItemVisited: function() {},
-
- onItemChanged: function PSB_onItemChanged(aItemId, aProperty,
- aIsAnnotationProperty, aNewValue,
- aLastModified, aItemType,
- aParentId) {
- if (aProperty !== "title")
- return;
-
- var views = getViewsForFolder(aParentId);
- ok(views.length > 0, "Found affected views (" + views.length + "): " + views);
-
- // Check that item has been moved in the correct position.
- let validator = function(aElementOrTreeIndex) {
- if (typeof(aElementOrTreeIndex) == "number") {
- var sidebar = document.getElementById("sidebar");
- var tree = sidebar.contentDocument.getElementById("bookmarks-view");
- let cellText = tree.view.getCellText(aElementOrTreeIndex,
- tree.columns.getColumnAt(0));
- if (!aNewValue)
- return cellText == PlacesUIUtils.getBestTitle(tree.view.nodeForTreeIndex(aElementOrTreeIndex), true);
- return cellText == aNewValue;
- }
- if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton") {
- return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode);
- }
- return aElementOrTreeIndex.getAttribute("label") == aNewValue;
- };
-
- for (var i = 0; i < views.length; i++) {
- var [node, , valid] = searchItemInView(aItemId, views[i], validator);
- isnot(node, null, "Found changed Places node in " + views[i]);
- is(node.title, aNewValue, "Node has correct title: " + aNewValue);
- ok(valid, "Node element has correct label: " + aNewValue);
- }
- }
-};
-
-/**
- * Search an item id in a view.
- *
- * @param aItemId
- * item id of the item to search.
- * @param aView
- * either "toolbar", "menu" or "sidebar"
- * @param aValidator
- * function to check validity of the found node element.
- * @returns [node, index, valid] or [null, null, false] if not found.
- */
-function searchItemInView(aItemId, aView, aValidator) {
- switch (aView) {
- case "toolbar":
- return getNodeForToolbarItem(aItemId, aValidator);
- case "menu":
- return getNodeForMenuItem(aItemId, aValidator);
- case "sidebar":
- return getNodeForSidebarItem(aItemId, aValidator);
- }
-
- return [null, null, false];
-}
-
-/**
- * Get places node and index for an itemId in bookmarks toolbar view.
- *
- * @param aItemId
- * item id of the item to search.
- * @returns [node, index] or [null, null] if not found.
- */
-function getNodeForToolbarItem(aItemId, aValidator) {
- var toolbar = document.getElementById("PlacesToolbarItems");
-
- function findNode(aContainer) {
- var children = aContainer.childNodes;
- for (var i = 0, staticNodes = 0; i < children.length; i++) {
- var child = children[i];
-
- // Is this a Places node?
- if (!child._placesNode || child.hasAttribute("simulated-places-node")) {
- staticNodes++;
- continue;
- }
-
- if (child._placesNode.itemId == aItemId) {
- let valid = aValidator ? aValidator(child) : true;
- return [child._placesNode, i - staticNodes, valid];
- }
-
- // Don't search in queries, they could contain our item in a
- // different position. Search only folders
- if (PlacesUtils.nodeIsFolder(child._placesNode)) {
- var popup = child.lastChild;
- popup.showPopup(popup);
- var foundNode = findNode(popup);
- popup.hidePopup();
- if (foundNode[0] != null)
- return foundNode;
- }
- }
- return [null, null];
- }
-
- return findNode(toolbar);
-}
-
-/**
- * Get places node and index for an itemId in bookmarks menu view.
- *
- * @param aItemId
- * item id of the item to search.
- * @returns [node, index] or [null, null] if not found.
- */
-function getNodeForMenuItem(aItemId, aValidator) {
- var menu = document.getElementById("bookmarksMenu");
-
- function findNode(aContainer) {
- var children = aContainer.childNodes;
- for (var i = 0, staticNodes = 0; i < children.length; i++) {
- var child = children[i];
-
- // Is this a Places node?
- if (!child._placesNode || child.hasAttribute("simulated-places-node")) {
- staticNodes++;
- continue;
- }
-
- if (child._placesNode.itemId == aItemId) {
- let valid = aValidator ? aValidator(child) : true;
- return [child._placesNode, i - staticNodes, valid];
- }
-
- // Don't search in queries, they could contain our item in a
- // different position. Search only folders
- if (PlacesUtils.nodeIsFolder(child._placesNode)) {
- var popup = child.lastChild;
- fakeOpenPopup(popup);
- var foundNode = findNode(popup);
-
- child.open = false;
- if (foundNode[0] != null)
- return foundNode;
- }
- }
- return [null, null, false];
- }
-
- return findNode(menu.lastChild);
-}
-
-/**
- * Get places node and index for an itemId in sidebar tree view.
- *
- * @param aItemId
- * item id of the item to search.
- * @returns [node, index] or [null, null] if not found.
- */
-function getNodeForSidebarItem(aItemId, aValidator) {
- var sidebar = document.getElementById("sidebar");
- var tree = sidebar.contentDocument.getElementById("bookmarks-view");
-
- function findNode(aContainerIndex) {
- if (tree.view.isContainerEmpty(aContainerIndex))
- return [null, null, false];
-
- // The rowCount limit is just for sanity, but we will end looping when
- // we have checked the last child of this container or we have found node.
- for (var i = aContainerIndex + 1; i < tree.view.rowCount; i++) {
- var node = tree.view.nodeForTreeIndex(i);
-
- if (node.itemId == aItemId) {
- // Minus one because we want relative index inside the container.
- let valid = aValidator ? aValidator(i) : true;
- return [node, i - tree.view.getParentIndex(i) - 1, valid];
- }
-
- if (PlacesUtils.nodeIsFolder(node)) {
- // Open container.
- tree.view.toggleOpenState(i);
- // Search inside it.
- var foundNode = findNode(i);
- // Close container.
- tree.view.toggleOpenState(i);
- // Return node if found.
- if (foundNode[0] != null)
- return foundNode;
- }
-
- // We have finished walking this container.
- if (!tree.view.hasNextSibling(aContainerIndex + 1, i))
- break;
- }
- return [null, null, false]
- }
-
- // Root node is hidden, so we need to manually walk the first level.
- for (var i = 0; i < tree.view.rowCount; i++) {
- // Open container.
- tree.view.toggleOpenState(i);
- // Search inside it.
- var foundNode = findNode(i);
- // Close container.
- tree.view.toggleOpenState(i);
- // Return node if found.
- if (foundNode[0] != null)
- return foundNode;
- }
- return [null, null, false];
-}
-
-/**
- * Get views affected by changes to a folder.
- *
- * @param aFolderId:
- * item id of the folder we have changed.
- * @returns a subset of views: ["toolbar", "menu", "sidebar"]
- */
-function getViewsForFolder(aFolderId) {
- var rootId = aFolderId;
- while (!PlacesUtils.isRootItem(rootId))
- rootId = PlacesUtils.bookmarks.getFolderIdForItem(rootId);
-
- switch (rootId) {
- case PlacesUtils.toolbarFolderId:
- return ["toolbar", "sidebar"]
- case PlacesUtils.bookmarksMenuFolderId:
- return ["menu", "sidebar"]
- case PlacesUtils.unfiledBookmarksFolderId:
- return ["sidebar"]
- }
- return new Array();
-}
diff --git a/browser/components/places/tests/browser/frameLeft.html b/browser/components/places/tests/browser/frameLeft.html
deleted file mode 100644
index 5a54fe353..000000000
--- a/browser/components/places/tests/browser/frameLeft.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
- <head>
- <title>Left frame</title>
- </head>
- <body>
- <a id="clickme" href="frameRight.html" target="right">Open page in the right frame.</a>
- </body>
-</html>
diff --git a/browser/components/places/tests/browser/frameRight.html b/browser/components/places/tests/browser/frameRight.html
deleted file mode 100644
index 226accc34..000000000
--- a/browser/components/places/tests/browser/frameRight.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
- <head>
- <title>Right Frame</title>
- </head>
- <body>
- This is the right frame.
- </body>
-</html>
diff --git a/browser/components/places/tests/browser/framedPage.html b/browser/components/places/tests/browser/framedPage.html
deleted file mode 100644
index d388562e6..000000000
--- a/browser/components/places/tests/browser/framedPage.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
- <head>
- <title>Framed page</title>
- </head>
- <frameset cols="*,*">
- <frame name="left" src="frameLeft.html">
- <frame name="right" src="about:mozilla">
- </frameset>
-</html>
diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js
deleted file mode 100644
index aaf78332e..000000000
--- a/browser/components/places/tests/browser/head.js
+++ /dev/null
@@ -1,460 +0,0 @@
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-// We need to cache this before test runs...
-var cachedLeftPaneFolderIdGetter;
-var getter = PlacesUIUtils.__lookupGetter__("leftPaneFolderId");
-if (!cachedLeftPaneFolderIdGetter && typeof(getter) == "function") {
- cachedLeftPaneFolderIdGetter = getter;
-}
-
-// ...And restore it when test ends.
-registerCleanupFunction(function() {
- let getter = PlacesUIUtils.__lookupGetter__("leftPaneFolderId");
- if (cachedLeftPaneFolderIdGetter && typeof(getter) != "function") {
- PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter);
- }
-});
-
-function openLibrary(callback, aLeftPaneRoot) {
- let library = window.openDialog("chrome://browser/content/places/places.xul",
- "", "chrome,toolbar=yes,dialog=no,resizable",
- aLeftPaneRoot);
- waitForFocus(function () {
- callback(library);
- }, library);
-
- return library;
-}
-
-/**
- * Returns a handle to a Library window.
- * If one is opens returns itm otherwise it opens a new one.
- *
- * @param aLeftPaneRoot
- * Hierarchy to open and select in the left pane.
- */
-function promiseLibrary(aLeftPaneRoot) {
- return new Promise(resolve => {
- let library = Services.wm.getMostRecentWindow("Places:Organizer");
- if (library && !library.closed) {
- if (aLeftPaneRoot) {
- library.PlacesOrganizer.selectLeftPaneContainerByHierarchy(aLeftPaneRoot);
- }
- resolve(library);
- }
- else {
- openLibrary(resolve, aLeftPaneRoot);
- }
- });
-}
-
-function promiseLibraryClosed(organizer) {
- return new Promise(resolve => {
- // Wait for the Organizer window to actually be closed
- organizer.addEventListener("unload", function onUnload() {
- organizer.removeEventListener("unload", onUnload);
- resolve();
- });
-
- // Close Library window.
- organizer.close();
- });
-}
-
-/**
- * Waits for a clipboard operation to complete, looking for the expected type.
- *
- * @see waitForClipboard
- *
- * @param aPopulateClipboardFn
- * Function to populate the clipboard.
- * @param aFlavor
- * Data flavor to expect.
- */
-function promiseClipboard(aPopulateClipboardFn, aFlavor) {
- return new Promise(resolve => {
- waitForClipboard(data => !!data, aPopulateClipboardFn, resolve, aFlavor);
- });
-}
-
-/**
- * Waits for all pending async statements on the default connection, before
- * proceeding with aCallback.
- *
- * @param aCallback
- * Function to be called when done.
- * @param aScope
- * Scope for the callback.
- * @param aArguments
- * Arguments array for the callback.
- *
- * @note The result is achieved by asynchronously executing a query requiring
- * a write lock. Since all statements on the same connection are
- * serialized, the end of this write operation means that all writes are
- * complete. Note that WAL makes so that writers don't block readers, but
- * this is a problem only across different connections.
- */
-function waitForAsyncUpdates(aCallback, aScope, aArguments)
-{
- let scope = aScope || this;
- let args = aArguments || [];
- let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
- let begin = db.createAsyncStatement("BEGIN EXCLUSIVE");
- begin.executeAsync();
- begin.finalize();
-
- let commit = db.createAsyncStatement("COMMIT");
- commit.executeAsync({
- handleResult: function() {},
- handleError: function() {},
- handleCompletion: function(aReason)
- {
- aCallback.apply(scope, args);
- }
- });
- commit.finalize();
-}
-
-function synthesizeClickOnSelectedTreeCell(aTree, aOptions) {
- let tbo = aTree.treeBoxObject;
- if (tbo.view.selection.count != 1)
- throw new Error("The test node should be successfully selected");
- // Get selection rowID.
- let min = {}, max = {};
- tbo.view.selection.getRangeAt(0, min, max);
- let rowID = min.value;
- tbo.ensureRowIsVisible(rowID);
- // Calculate the click coordinates.
- var rect = tbo.getCoordsForCellItem(rowID, aTree.columns[0], "text");
- var x = rect.x + rect.width / 2;
- var y = rect.y + rect.height / 2;
- // Simulate the click.
- EventUtils.synthesizeMouse(aTree.body, x, y, aOptions || {},
- aTree.ownerGlobal);
-}
-
-/**
- * Asynchronously check a url is visited.
- *
- * @param aURI The URI.
- * @return {Promise}
- * @resolves When the check has been added successfully.
- * @rejects JavaScript exception.
- */
-function promiseIsURIVisited(aURI) {
- let deferred = Promise.defer();
-
- PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) {
- deferred.resolve(aIsVisited);
- });
-
- return deferred.promise;
-}
-
-function promiseBookmarksNotification(notification, conditionFn) {
- info(`promiseBookmarksNotification: waiting for ${notification}`);
- return new Promise((resolve) => {
- let proxifiedObserver = new Proxy({}, {
- get: (target, name) => {
- if (name == "QueryInterface")
- return XPCOMUtils.generateQI([ Ci.nsINavBookmarkObserver ]);
- info(`promiseBookmarksNotification: got ${name} notification`);
- if (name == notification)
- return (...args) => {
- if (conditionFn.apply(this, args)) {
- PlacesUtils.bookmarks.removeObserver(proxifiedObserver, false);
- executeSoon(resolve);
- } else {
- info(`promiseBookmarksNotification: skip cause condition doesn't apply to ${JSON.stringify(args)}`);
- }
- }
- return () => {};
- }
- });
- PlacesUtils.bookmarks.addObserver(proxifiedObserver, false);
- });
-}
-
-function promiseHistoryNotification(notification, conditionFn) {
- info(`Waiting for ${notification}`);
- return new Promise((resolve) => {
- let proxifiedObserver = new Proxy({}, {
- get: (target, name) => {
- if (name == "QueryInterface")
- return XPCOMUtils.generateQI([ Ci.nsINavHistoryObserver ]);
- if (name == notification)
- return (...args) => {
- if (conditionFn.apply(this, args)) {
- PlacesUtils.history.removeObserver(proxifiedObserver, false);
- executeSoon(resolve);
- }
- }
- return () => {};
- }
- });
- PlacesUtils.history.addObserver(proxifiedObserver, false);
- });
-}
-
-/**
- * Makes the specified toolbar visible or invisible and returns a Promise object
- * that is resolved when the toolbar has completed any animations associated
- * with hiding or showing the toolbar.
- *
- * Note that this code assumes that changes to a toolbar's visibility trigger
- * a transition on the max-height property of the toolbar element.
- * Changes to this styling could cause the returned Promise object to be
- * resolved too early or not at all.
- *
- * @param aToolbar
- * The toolbar to update.
- * @param aVisible
- * True to make the toolbar visible, false to make it hidden.
- *
- * @return {Promise}
- * @resolves Any animation associated with updating the toolbar's visibility has
- * finished.
- * @rejects Never.
- */
-function promiseSetToolbarVisibility(aToolbar, aVisible, aCallback) {
- return new Promise((resolve, reject) => {
- function listener(event) {
- if (event.propertyName == "max-height") {
- aToolbar.removeEventListener("transitionend", listener);
- resolve();
- }
- }
-
- let transitionProperties =
- window.getComputedStyle(aToolbar).transitionProperty.split(", ");
- if (isToolbarVisible(aToolbar) != aVisible &&
- transitionProperties.some(
- prop => prop == "max-height" || prop == "all"
- )) {
- // Just because max-height is a transitionable property doesn't mean
- // a transition will be triggered, but it's more likely.
- aToolbar.addEventListener("transitionend", listener);
- setToolbarVisibility(aToolbar, aVisible);
- return;
- }
-
- // No animation to wait for
- setToolbarVisibility(aToolbar, aVisible);
- resolve();
- });
-}
-
-/**
- * Helper function to determine if the given toolbar is in the visible
- * state according to its autohide/collapsed attribute.
- *
- * @aToolbar The toolbar to query.
- *
- * @returns True if the relevant attribute on |aToolbar| indicates it is
- * visible, false otherwise.
- */
-function isToolbarVisible(aToolbar) {
- let hidingAttribute = aToolbar.getAttribute("type") == "menubar"
- ? "autohide"
- : "collapsed";
- let hidingValue = aToolbar.getAttribute(hidingAttribute).toLowerCase();
- // Check for both collapsed="true" and collapsed="collapsed"
- return hidingValue !== "true" && hidingValue !== hidingAttribute;
-}
-
-/**
- * Executes a task after opening the bookmarks dialog, then cancels the dialog.
- *
- * @param autoCancel
- * whether to automatically cancel the dialog at the end of the task
- * @param openFn
- * generator function causing the dialog to open
- * @param task
- * the task to execute once the dialog is open
- */
-var withBookmarksDialog = Task.async(function* (autoCancel, openFn, taskFn) {
- let closed = false;
- let dialogPromise = new Promise(resolve => {
- Services.ww.registerNotification(function winObserver(subject, topic, data) {
- if (topic == "domwindowopened") {
- let win = subject.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function load() {
- win.removeEventListener("load", load);
- ok(win.location.href.startsWith("chrome://browser/content/places/bookmarkProperties"),
- "The bookmark properties dialog is open");
- // This is needed for the overlay.
- waitForFocus(() => {
- resolve(win);
- }, win);
- });
- } else if (topic == "domwindowclosed") {
- Services.ww.unregisterNotification(winObserver);
- closed = true;
- }
- });
- });
-
- info("withBookmarksDialog: opening the dialog");
- // The dialog might be modal and could block our events loop, so executeSoon.
- executeSoon(openFn);
-
- info("withBookmarksDialog: waiting for the dialog");
- let dialogWin = yield dialogPromise;
-
- // Ensure overlay is loaded
- info("waiting for the overlay to be loaded");
- yield waitForCondition(() => dialogWin.gEditItemOverlay.initialized,
- "EditItemOverlay should be initialized");
-
- // Check the first textbox is focused.
- let doc = dialogWin.document;
- let elt = doc.querySelector("textbox:not([collapsed=true])");
- if (elt) {
- info("waiting for focus on the first textfield");
- yield waitForCondition(() => doc.activeElement == elt.inputField,
- "The first non collapsed textbox should have been focused");
- }
-
- info("withBookmarksDialog: executing the task");
- try {
- yield taskFn(dialogWin);
- } finally {
- if (!closed) {
- if (!autoCancel) {
- ok(false, "The test should have closed the dialog!");
- }
- info("withBookmarksDialog: canceling the dialog");
- doc.documentElement.cancelDialog();
- }
- }
-});
-
-/**
- * Opens the contextual menu on the element pointed by the given selector.
- *
- * @param selector
- * Valid selector syntax
- * @return Promise
- * Returns a Promise that resolves once the context menu has been
- * opened.
- */
-var openContextMenuForContentSelector = Task.async(function* (browser, selector) {
- info("wait for the context menu");
- let contextPromise = BrowserTestUtils.waitForEvent(document.getElementById("contentAreaContextMenu"),
- "popupshown");
- yield ContentTask.spawn(browser, { selector }, function* (args) {
- let doc = content.document;
- let elt = doc.querySelector(args.selector)
- dump(`openContextMenuForContentSelector: found ${elt}\n`);
-
- /* Open context menu so chrome can access the element */
- const domWindowUtils =
- content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindowUtils);
- let rect = elt.getBoundingClientRect();
- let left = rect.left + rect.width / 2;
- let top = rect.top + rect.height / 2;
- domWindowUtils.sendMouseEvent("contextmenu", left, top, 2,
- 1, 0, false, 0, 0, true);
- });
- yield contextPromise;
-});
-
-/**
- * Waits for a specified condition to happen.
- *
- * @param conditionFn
- * a Function or a generator function, returning a boolean for whether
- * the condition is fulfilled.
- * @param errorMsg
- * Error message to use if the condition has not been satisfied after a
- * meaningful amount of tries.
- */
-var waitForCondition = Task.async(function* (conditionFn, errorMsg) {
- for (let tries = 0; tries < 100; ++tries) {
- if ((yield conditionFn()))
- return;
- yield new Promise(resolve => {
- if (!waitForCondition._timers) {
- waitForCondition._timers = new Set();
- registerCleanupFunction(() => {
- is(waitForCondition._timers.size, 0, "All the wait timers have been removed");
- delete waitForCondition._timers;
- });
- }
- let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- waitForCondition._timers.add(timer);
- timer.init(() => {
- waitForCondition._timers.delete(timer);
- resolve();
- }, 100, Ci.nsITimer.TYPE_ONE_SHOT);
- });
- }
- ok(false, errorMsg);
-});
-
-/**
- * Fills a bookmarks dialog text field ensuring to cause expected edit events.
- *
- * @param id
- * id of the text field
- * @param text
- * text to fill in
- * @param win
- * dialog window
- * @param [optional] blur
- * whether to blur at the end.
- */
-function fillBookmarkTextField(id, text, win, blur = true) {
- let elt = win.document.getElementById(id);
- elt.focus();
- elt.select();
- for (let c of text.split("")) {
- EventUtils.synthesizeKey(c, {}, win);
- }
- if (blur)
- elt.blur();
-}
-
-/**
- * Executes a task after opening the bookmarks or history sidebar. Takes care
- * of closing the sidebar once done.
- *
- * @param type
- * either "bookmarks" or "history".
- * @param taskFn
- * The task to execute once the sidebar is ready. Will get the Places
- * tree view as input.
- */
-var withSidebarTree = Task.async(function* (type, taskFn) {
- let sidebar = document.getElementById("sidebar");
- info("withSidebarTree: waiting sidebar load");
- let sidebarLoadedPromise = new Promise(resolve => {
- sidebar.addEventListener("load", function load() {
- sidebar.removeEventListener("load", load, true);
- resolve();
- }, true);
- });
- let sidebarId = type == "bookmarks" ? "viewBookmarksSidebar"
- : "viewHistorySidebar";
- SidebarUI.show(sidebarId);
- yield sidebarLoadedPromise;
-
- let treeId = type == "bookmarks" ? "bookmarks-view"
- : "historyTree";
- let tree = sidebar.contentDocument.getElementById(treeId);
-
- // Need to executeSoon since the tree is initialized on sidebar load.
- info("withSidebarTree: executing the task");
- try {
- yield taskFn(tree);
- } finally {
- SidebarUI.hide();
- }
-});
diff --git a/browser/components/places/tests/browser/keyword_form.html b/browser/components/places/tests/browser/keyword_form.html
deleted file mode 100644
index a881c0d5a..000000000
--- a/browser/components/places/tests/browser/keyword_form.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE HTML>
-
-<html lang="en">
-<head>
- <meta http-equiv="Content-Type" content="text/html;charset=windows-1252">
-</head>
-<body>
- <form id="form1" method="POST" action="keyword_form.html">
- <input type="hidden" name="accenti" value="àèìòù">
- <input type="text" name="search">
- </form>
- <form id="form2" method="POST" action="keyword_form.html">
- <input type="hidden" name="accenti" value="ùòìèà">
- <input type="text" name="search">
- </form>
-</body>
-</html>
diff --git a/browser/components/places/tests/browser/pageopeningwindow.html b/browser/components/places/tests/browser/pageopeningwindow.html
deleted file mode 100644
index 282f9c593..000000000
--- a/browser/components/places/tests/browser/pageopeningwindow.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<meta charset="UTF-8">
-Hi, I was opened via a <script>document.write(location.search ?
- "popup call from the opened window... uh oh, that shouldn't happen!" :
- "bookmarklet, and I will open a new window myself.")</script><br>
-<script>
- if (!location.search) {
- open(location.href + "?donotopen=true", '_blank');
- }
-</script>
diff --git a/browser/components/places/tests/browser/sidebarpanels_click_test_page.html b/browser/components/places/tests/browser/sidebarpanels_click_test_page.html
deleted file mode 100644
index c73eaa540..000000000
--- a/browser/components/places/tests/browser/sidebarpanels_click_test_page.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
-<head>
- <title>browser_sidebarpanels_click.js test page</title>
-</head>
-<body onload="alert('test');">
-</body>
-</html>
diff --git a/browser/components/places/tests/chrome/.eslintrc.js b/browser/components/places/tests/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/browser/components/places/tests/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/browser/components/places/tests/chrome/chrome.ini b/browser/components/places/tests/chrome/chrome.ini
deleted file mode 100644
index d7b4a55c8..000000000
--- a/browser/components/places/tests/chrome/chrome.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-support-files = head.js
-
-[test_0_bug510634.xul]
-[test_0_multiple_left_pane.xul]
-[test_bug1163447_selectItems_through_shortcut.xul]
-[test_bug427633_no_newfolder_if_noip.xul]
-[test_bug485100-change-case-loses-tag.xul]
-[test_bug549192.xul]
-[test_bug549491.xul]
-[test_bug631374_tags_selector_scroll.xul]
-[test_editBookmarkOverlay_keywords.xul]
-[test_editBookmarkOverlay_tags_liveUpdate.xul]
-[test_selectItems_on_nested_tree.xul]
-[test_treeview_date.xul]
diff --git a/browser/components/places/tests/chrome/head.js b/browser/components/places/tests/chrome/head.js
deleted file mode 100644
index 26b97f6d7..000000000
--- a/browser/components/places/tests/chrome/head.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
diff --git a/browser/components/places/tests/chrome/test_0_bug510634.xul b/browser/components/places/tests/chrome/test_0_bug510634.xul
deleted file mode 100644
index 86e102180..000000000
--- a/browser/components/places/tests/chrome/test_0_bug510634.xul
+++ /dev/null
@@ -1,99 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="510634: Wrong icons on bookmarks sidebar"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript">
- <![CDATA[
-
- /**
- * Bug 510634 - Wrong icons on bookmarks sidebar
- * https://bugzilla.mozilla.org/show_bug.cgi?id=510634
- *
- * Ensures that properties for special queries are set on their tree nodes,
- * even if PlacesUIUtils.leftPaneFolderId was not initialized.
- */
-
- SimpleTest.waitForExplicitFinish();
-
- function runTest() {
- // We need to cache and restore this getter in order to simulate
- // Bug 510634
- let cachedLeftPaneFolderIdGetter =
- PlacesUIUtils.__lookupGetter__("leftPaneFolderId");
- // Must also cache and restore this getter as it is affected by
- // leftPaneFolderId, from bug 564900.
- let cachedAllBookmarksFolderIdGetter =
- PlacesUIUtils.__lookupGetter__("allBookmarksFolderId");
-
- let leftPaneFolderId = PlacesUIUtils.leftPaneFolderId;
-
- // restore the getter
- PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter);
-
- // Setup the places tree contents.
- let tree = document.getElementById("tree");
- tree.place = "place:queryType=1&folder=" + leftPaneFolderId;
-
- // The query-property is set on the title column for each row.
- let titleColumn = tree.treeBoxObject.columns.getColumnAt(0);
-
- // Open All Bookmarks
- tree.selectItems([PlacesUIUtils.leftPaneQueries["AllBookmarks"]]);
- PlacesUtils.asContainer(tree.selectedNode).containerOpen = true;
- is(PlacesUIUtils.allBookmarksFolderId, tree.selectedNode.itemId,
- "Opened All Bookmarks");
-
- ["History", "Downloads", "Tags", "AllBookmarks", "BookmarksToolbar",
- "BookmarksMenu", "UnfiledBookmarks"].forEach(
- function(aQueryName, aRow) {
- let found = false;
- for (let i = 0; i < tree.view.rowCount && !found; i++) {
- rowProperties = tree.view.getCellProperties(i, titleColumn).split(" ");
- found = rowProperties.includes("OrganizerQuery_" + aQueryName);
- }
- ok(found, "OrganizerQuery_" + aQueryName + " is set");
- }
- );
-
- // Close the root node
- tree.result.root.containerOpen = false;
-
- // Restore the getters for the next test.
- PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter);
- PlacesUIUtils.__defineGetter__("allBookmarksFolderId",
- cachedAllBookmarksFolderIdGetter);
-
- SimpleTest.finish();
- }
-
- ]]>
- </script>
-</window>
diff --git a/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul b/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul
deleted file mode 100644
index 09a4d2054..000000000
--- a/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul
+++ /dev/null
@@ -1,85 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- 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/. -->
-
-<!-- Bug 466422:
- - Check that we replace the left pane with a correct one if it gets corrupted
- - and we end up having more than one. -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Test handling of multiple left pane folders"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display: none"></div>
- <pre id="test"></pre>
- </body>
-
- <script type="application/javascript">
- <![CDATA[
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- // Sanity checks.
- ok(PlacesUtils, "PlacesUtils is running in chrome context");
- ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context");
- ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0,
- "Left pane version in chrome context, " +
- "current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION );
-
- let fakeLeftPanes = [];
- // We need 2 left pane folders to simulate a corrupt profile.
- do {
- let leftPaneItems = PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
-
- // Create a fake left pane folder.
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.rootGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- let fakeLeftPaneRoot = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations.setItemAnnotation(fakeLeftPaneRoot, PlacesUIUtils.ORGANIZER_FOLDER_ANNO,
- PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- fakeLeftPanes.push(folder.guid);
- } while (fakeLeftPanes.length < 2);
-
- // Initialize the left pane queries.
- PlacesUIUtils.leftPaneFolderId;
-
- // Check left pane.
- ok(PlacesUIUtils.leftPaneFolderId > 0,
- "Left pane folder correctly created");
- let leftPaneItems = PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO);
- is(leftPaneItems.length, 1,
- "We correctly have only 1 left pane folder");
-
- // Check that all old left pane items have been removed.
- for (let guid of fakeLeftPanes) {
- ok(!(yield PlacesUtils.bookmarks.fetch({guid})), "This folder should have been removed");
- }
- }).then(() => SimpleTest.finish());
- }
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul b/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul
deleted file mode 100644
index 8e3a99533..000000000
--- a/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul
+++ /dev/null
@@ -1,89 +0,0 @@
-<?xml version="1.0"?>
-
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/licenses/publicdomain/
- -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="1163447: selectItems in Places no longer selects items within Toolbar or Sidebar folders"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript" src="head.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript"><![CDATA[
-
- /**
- * Bug 1163447: places-tree should be able to select an item within the toolbar, and
- * unfiled bookmarks. Yet not follow recursive folder-shortcuts infinitely.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- let bmu = PlacesUtils.bookmarks;
-
- yield bmu.insert({
- parentGuid: bmu.toolbarGuid,
- index: bmu.DEFAULT_INDEX,
- type: bmu.TYPE_BOOKMARK,
- url: "place:folder=TOOLBAR",
- title: "shortcut to self - causing infinite recursion if not handled properly"
- });
-
- yield bmu.insert({
- parentGuid: bmu.toolbarGuid,
- index: bmu.DEFAULT_INDEX,
- type: bmu.TYPE_BOOKMARK,
- url: "place:folder=UNFILED_BOOKMARKS",
- title: "shortcut to unfiled, within toolbar"
- });
-
- let folder = yield bmu.insert({
- parentGuid: bmu.unfiledGuid,
- index: bmu.DEFAULT_INDEX,
- type: bmu.TYPE_FOLDER,
- title: "folder within unfiled"
- });
-
- // Setup the places tree contents.
- let tree = document.getElementById("tree");
- tree.place = "place:folder=TOOLBAR";
-
- // Select the folder via the selectItems(itemId) API being tested
- let itemId = yield PlacesUtils.promiseItemId(folder.guid);
- tree.selectItems([itemId]);
-
- is(tree.selectedNode && tree.selectedNode.itemId, itemId, "The node was selected through the shortcut");
-
- // Cleanup
- yield bmu.eraseEverything();
-
- }).catch(err => {
- ok(false, `Uncaught error: ${err}`);
- }).then(SimpleTest.finish);
- }
- ]]></script>
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul b/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul
deleted file mode 100644
index b659b2b46..000000000
--- a/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
-
-<!DOCTYPE window [
- <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
- %editBookmarkOverlayDTD;
-]>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Bug 427633 - Disable creating a New Folder in the bookmarks dialogs if insertionPoint is invalid"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://browser/content/places/editBookmarkOverlay.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <vbox id="editBookmarkPanelContent"/>
-
- <script type="application/javascript">
- <![CDATA[
-
- /**
- * Bug 427633 - Disable creating a New Folder in the bookmarks dialogs if
- * insertionPoint is invalid.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- // Add a bookmark.
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: "http://www.example.com/",
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- title: "mozilla"
- });
-
- // Init panel.
- ok(gEditItemOverlay, "gEditItemOverlay is in context");
- let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm);
- gEditItemOverlay.initPanel({ node });
- ok(gEditItemOverlay.initialized, "gEditItemOverlay is initialized");
-
- let tree = gEditItemOverlay._element("folderTree");
- yield openFolderTree(tree);
-
- tree.view.selection.clearSelection();
- ok(document.getElementById("editBMPanel_newFolderButton").disabled,
- "New folder button is disabled if there's no selection");
-
- // Cleanup.
- yield PlacesUtils.bookmarks.remove(bm.guid);
- }).then(() => SimpleTest.finish());
- }
-
- function openFolderTree(tree) {
- return new Promise(resolve => {
- tree.addEventListener("DOMAttrModified", function onAttrModified(event) {
- if (event.attrName == "place") {
- tree.removeEventListener("DOMAttrModified", onAttrModified);
- resolve();
- }
- });
-
- // Open the folder tree.
- document.getElementById("editBMPanel_foldersExpander").doCommand();
- });
- }
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul b/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul
deleted file mode 100644
index afad950cb..000000000
--- a/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul
+++ /dev/null
@@ -1,83 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
-
-<!DOCTYPE window [
- <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
- %editBookmarkOverlayDTD;
-]>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="485100: Exchanging a letter of a tag name with its big/small equivalent removes tag from bookmark"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://browser/content/places/editBookmarkOverlay.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <vbox id="editBookmarkPanelContent"/>
-
- <script type="application/javascript">
- <![CDATA[
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- let testTag = "foo";
- let testTagUpper = "Foo";
- let testURI = Services.io.newURI("http://www.example.com/", null, null);
-
- // Add a bookmark.
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- title: "mozilla",
- url: testURI
- });
-
- // Init panel
- ok(gEditItemOverlay, "gEditItemOverlay is in context");
- let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm);
- gEditItemOverlay.initPanel({ node });
-
- // add a tag
- document.getElementById("editBMPanel_tagsField").value = testTag;
- gEditItemOverlay.onTagsFieldChange();
-
- // test that the tag has been added in the backend
- is(PlacesUtils.tagging.getTagsForURI(testURI)[0], testTag, "tags match");
-
- // change the tag
- document.getElementById("editBMPanel_tagsField").value = testTagUpper;
- gEditItemOverlay.onTagsFieldChange();
-
- // test that the tag has been added in the backend
- is(PlacesUtils.tagging.getTagsForURI(testURI)[0], testTagUpper, "tags match");
-
- // Cleanup.
- PlacesUtils.tagging.untagURI(testURI, [testTag]);
- yield PlacesUtils.bookmarks.remove(bm.guid);
- }).then(() => SimpleTest.finish());
- }
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug549192.xul b/browser/components/places/tests/chrome/test_bug549192.xul
deleted file mode 100644
index 4e6a89bb1..000000000
--- a/browser/components/places/tests/chrome/test_bug549192.xul
+++ /dev/null
@@ -1,120 +0,0 @@
-<?xml version="1.0"?>
-
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/licenses/publicdomain/
- -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="549192: History view not updated after deleting entry"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript" src="head.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flatList="true"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript"><![CDATA[
- /**
- * Bug 874407
- * Ensures that history views are updated properly after visits.
- * Bug 549192
- * Ensures that history views are updated after deleting entries.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- yield PlacesTestUtils.clearHistory();
-
- // Add some visits.
- let timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000);
-
- function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
- }
-
- let vtime = Date.now() * 1000;
- const ttype = PlacesUtils.history.TRANSITION_TYPED;
- let places =
- [{ uri: Services.io.newURI("http://example.tld/", null, null),
- visitDate: newTimeInMicroseconds(), transition: ttype },
- { uri: Services.io.newURI("http://example2.tld/", null, null),
- visitDate: newTimeInMicroseconds(), transition: ttype },
- { uri: Services.io.newURI("http://example3.tld/", null, null),
- visitDate: newTimeInMicroseconds(), transition: ttype }];
-
- yield PlacesTestUtils.addVisits(places);
-
- // Make a history query.
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts);
-
- // Setup the places tree contents.
- var tree = document.getElementById("tree");
- tree.place = queryURI;
-
- // loop through the rows and check them.
- let treeView = tree.view;
- let selection = treeView.selection;
- let rc = treeView.rowCount;
-
- for (let i = 0; i < rc; i++) {
- selection.select(i);
- let node = tree.selectedNode;
- is(node.uri, places[rc - i - 1].uri.spec,
- "Found expected node at position " + i + ".");
- }
-
- is(rc, 3, "Found expected number of rows.");
-
- // First check live-update of the view when adding visits.
- places.forEach(place => place.visitDate = newTimeInMicroseconds());
- yield PlacesTestUtils.addVisits(places);
-
- for (let i = 0; i < rc; i++) {
- selection.select(i);
- let node = tree.selectedNode;
- is(node.uri, places[rc - i - 1].uri.spec,
- "Found expected node at position " + i + ".");
- }
-
- // Now remove the pages and verify live-update again.
- for (let i = 0; i < rc; i++) {
- selection.select(0);
- let node = tree.selectedNode;
- tree.controller.remove("Removing page");
- ok(treeView.treeIndexForNode(node) == Ci.nsINavHistoryResultTreeViewer.INDEX_INVISIBLE,
- node.uri + " removed.");
- ok(treeView.rowCount == rc - i - 1, "Rows count decreased");
- }
-
- // Cleanup.
- yield PlacesTestUtils.clearHistory();
- }).then(() => SimpleTest.finish());
- }
- ]]></script>
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug549491.xul b/browser/components/places/tests/chrome/test_bug549491.xul
deleted file mode 100644
index 5ec7a765a..000000000
--- a/browser/components/places/tests/chrome/test_bug549491.xul
+++ /dev/null
@@ -1,78 +0,0 @@
-<?xml version="1.0"?>
-
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/licenses/publicdomain/
- -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="549491: 'The root node is never visible' exception when details of the root node are modified "
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript" src="head.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flatList="true"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- <splitter class="tree-splitter"/>
- <treecol label="Date" anonid="date" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript"><![CDATA[
- /**
- * Bug 549491
- * https://bugzilla.mozilla.org/show_bug.cgi?id=549491
- *
- * Ensures that changing the details of places tree's root-node doesn't
- * throw.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- yield PlacesTestUtils.clearHistory();
-
- yield PlacesTestUtils.addVisits({
- uri: Services.io.newURI("http://example.tld/", null, null),
- transition: PlacesUtils.history.TRANSITION_TYPED
- });
-
- // Make a history query.
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts);
-
- // Setup the places tree contents.
- let tree = document.getElementById("tree");
- tree.place = queryURI;
-
- let rootNode = tree.result.root;
- let obs = tree.view.QueryInterface(Ci.nsINavHistoryResultObserver);
- obs.nodeHistoryDetailsChanged(rootNode, rootNode.time, rootNode.accessCount);
- obs.nodeTitleChanged(rootNode, rootNode.title);
- ok(true, "No exceptions thrown");
-
- // Cleanup.
- yield PlacesTestUtils.clearHistory();
- }).then(SimpleTest.finish);
- }
- ]]></script>
-</window>
diff --git a/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul b/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul
deleted file mode 100644
index b1d73017f..000000000
--- a/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul
+++ /dev/null
@@ -1,170 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
-
-<!DOCTYPE window [
- <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
- %editBookmarkOverlayDTD;
-]>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Bug 631374 - Editing tags in the selector scrolls up the listbox"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://browser/content/places/editBookmarkOverlay.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <vbox id="editBookmarkPanelContent"/>
-
- <script type="application/javascript">
- <![CDATA[
-
- /**
- * This test checks that editing tags doesn't scroll the tags selector
- * listbox to wrong positions.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- let bs = PlacesUtils.bookmarks;
-
- let tags = ["a", "b", "c", "d", "e", "f", "g",
- "h", "i", "l", "m", "n", "o", "p"];
-
- // Add a bookmark and tag it.
- let uri1 = Services.io.newURI("http://www1.mozilla.org/", null, null);
- let bm1 = yield bs.insert({
- parentGuid: bs.toolbarGuid,
- index: bs.DEFAULT_INDEX,
- type: bs.TYPE_BOOKMARK,
- title: "mozilla",
- url: uri1.spec
- });
- PlacesUtils.tagging.tagURI(uri1, tags);
-
- // Add a second bookmark so that tags won't disappear when unchecked.
- let uri2 = Services.io.newURI("http://www2.mozilla.org/", null, null);
- let bm2 = yield bs.insert({
- parentGuid: bs.toolbarGuid,
- index: bs.DEFAULT_INDEX,
- type: bs.TYPE_BOOKMARK,
- title: "mozilla",
- url: uri2.spec
- });
- PlacesUtils.tagging.tagURI(uri2, tags);
-
- // Init panel.
- ok(gEditItemOverlay, "gEditItemOverlay is in context");
- let node1 = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm1);
- gEditItemOverlay.initPanel({ node: node1 });
- ok(gEditItemOverlay.initialized, "gEditItemOverlay is initialized");
-
- yield openTagSelector();
- let tagsSelector = document.getElementById("editBMPanel_tagsSelector");
-
- // Go by two so there is some untouched tag in the middle.
- for (let i = 8; i < tags.length; i += 2) {
- tagsSelector.selectedIndex = i;
- let listItem = tagsSelector.selectedItem;
- isnot(listItem, null, "Valid listItem found");
-
- tagsSelector.ensureElementIsVisible(listItem);
- let visibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
-
- ok(listItem.checked, "Item is checked " + i);
- let selectedTag = listItem.label;
-
- // Uncheck the tag.
- listItem.checked = false;
- is(visibleIndex, tagsSelector.getIndexOfFirstVisibleRow(),
- "Scroll position did not change");
-
- // The listbox is rebuilt, so we have to get the new element.
- let newItem = tagsSelector.selectedItem;
- isnot(newItem, null, "Valid new listItem found");
- ok(!newItem.checked, "New listItem is unchecked " + i);
- is(newItem.label, selectedTag, "Correct tag is still selected");
-
- // Check the tag.
- newItem.checked = true;
- is(visibleIndex, tagsSelector.getIndexOfFirstVisibleRow(),
- "Scroll position did not change");
- }
-
- // Remove the second bookmark, then nuke some of the tags.
- yield bs.remove(bm2.guid);
-
- // Doing this backwords tests more interesting paths.
- for (let i = tags.length - 1; i >= 0 ; i -= 2) {
- tagsSelector.selectedIndex = i;
- let listItem = tagsSelector.selectedItem;
- isnot(listItem, null, "Valid listItem found");
-
- tagsSelector.ensureElementIsVisible(listItem);
- let firstVisibleTag = tags[tagsSelector.getIndexOfFirstVisibleRow()];
-
- ok(listItem.checked, "Item is checked " + i);
- let selectedTag = listItem.label;
-
- // Uncheck the tag.
- listItem.checked = false;
-
- // Ensure the first visible tag is still visible in the list.
- let firstVisibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
- let lastVisibleIndex = firstVisibleIndex + tagsSelector.getNumberOfVisibleRows() -1;
- let expectedTagIndex = tags.indexOf(firstVisibleTag);
- ok(expectedTagIndex >= firstVisibleIndex &&
- expectedTagIndex <= lastVisibleIndex,
- "Scroll position is correct");
-
- // The listbox is rebuilt, so we have to get the new element.
- let newItem = tagsSelector.selectedItem;
- isnot(newItem, null, "Valid new listItem found");
- ok(newItem.checked, "New listItem is checked " + i);
- is(tagsSelector.selectedItem.label,
- tags[Math.min(i + 1, tags.length - 2)],
- "The next tag is now selected");
- }
-
- // Cleanup.
- yield bs.remove(bm1.guid);
- }).then(SimpleTest.finish).catch(alert);
- }
-
- function openTagSelector() {
- // Wait for the tags selector to be open.
- let promise = new Promise(resolve => {
- let row = document.getElementById("editBMPanel_tagsSelectorRow");
- row.addEventListener("DOMAttrModified", function onAttrModified() {
- row.removeEventListener("DOMAttrModified", onAttrModified);
- resolve();
- });
- });
-
- // Open the tags selector.
- document.getElementById("editBMPanel_tagsSelectorExpander").doCommand();
-
- return promise;
- }
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul b/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul
deleted file mode 100644
index f553d018b..000000000
--- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul
+++ /dev/null
@@ -1,99 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
-
-<!DOCTYPE window [
- <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
- %editBookmarkOverlayDTD;
-]>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Bug 1343256 - Bookmark keywords disappear from one bookmark when adding a keyword to another bookmark"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="chrome://browser/content/places/editBookmarkOverlay.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <vbox id="editBookmarkPanelContent"/>
-
- <script type="application/javascript">
- <![CDATA[
- function runTest() {
- SimpleTest.waitForExplicitFinish();
- Task.spawn(test.bind(this))
- .catch(ex => ok(false, ex))
- .then(() => PlacesUtils.bookmarks.eraseEverything())
- .then(SimpleTest.finish);
- }
-
- function promiseOnItemChanged() {
- return new Promise(resolve => {
- PlacesUtils.bookmarks.addObserver({
- onBeginUpdateBatch() {},
- onEndUpdateBatch() {},
- onItemAdded() {},
- onItemRemoved() {},
- onItemVisited() {},
- onItemMoved() {},
- onItemChanged(id, property, isAnno, value) {
- PlacesUtils.bookmarks.removeObserver(this);
- resolve({ property, value });
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
- }, false);
- });
- }
-
- function* test() {
- ok(gEditItemOverlay, "Sanity check: gEditItemOverlay is in context");
- let keywordField = document.getElementById("editBMPanel_keywordField");
-
- for (let i = 0; i < 2; ++i) {
- let bm = yield PlacesUtils.bookmarks.insert({
- url: `http://www.test${i}.me/`,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- });
- info(`Init panel on bookmark #${i+1}`);
- let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm);
- gEditItemOverlay.initPanel({ node });
- is(document.getElementById("editBMPanel_keywordField").value, "",
- "The keyword field should be empty");
- info("Add a keyword to the bookmark");
- let promise = promiseOnItemChanged();
- keywordField.focus();
- keywordField.value = "kw";
- synthesizeKey(i.toString(), {});
- synthesizeKey("VK_RETURN", {});
- keywordField.blur();
- let {property, value} = yield promise;
- is(property, "keyword", "The keyword should have been changed");
- is(value, `kw${i}`, "The new keyword value is correct");
- }
-
- for (let i = 0; i < 2; ++i) {
- let entry = yield PlacesUtils.keywords.fetch({ url: `http://www.test${i}.me/` });
- is(entry.keyword, `kw${i}`, `The keyword for http://www.test${i}.me/ is correct`);
- }
- };
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul b/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul
deleted file mode 100644
index 1b1cc6473..000000000
--- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul
+++ /dev/null
@@ -1,204 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
-
-<!DOCTYPE window [
- <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
- %editBookmarkOverlayDTD;
-]>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="485100: Exchanging a letter of a tag name with its big/small equivalent removes tag from bookmark"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript"
- src="chrome://browser/content/places/editBookmarkOverlay.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <vbox id="editBookmarkPanelContent"/>
-
- <script type="application/javascript">
- <![CDATA[
- function checkTagsSelector(aAvailableTags, aCheckedTags) {
- is(PlacesUtils.tagging.allTags.length, aAvailableTags.length,
- "tagging service is in sync.");
- let tagsSelector = document.getElementById("editBMPanel_tagsSelector");
- let children = tagsSelector.childNodes;
- is(children.length, aAvailableTags.length,
- "Found expected number of tags in the tags selector");
-
- Array.prototype.forEach.call(children, function (aChild) {
- let tag = aChild.getAttribute("label");
- ok(true, "Found tag '" + tag + "' in the selector");
- ok(aAvailableTags.includes(tag), "Found expected tag");
- let checked = aChild.getAttribute("checked") == "true";
- is(checked, aCheckedTags.includes(tag),
- "Tag is correctly marked");
- });
- }
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- const TEST_URI = Services.io.newURI("http://www.test.me/", null, null);
- const TEST_URI2 = Services.io.newURI("http://www.test.again.me/", null, null);
- const TEST_TAG = "test-tag";
-
- ok(gEditItemOverlay, "Sanity check: gEditItemOverlay is in context");
-
- // Open the tags selector.
- document.getElementById("editBMPanel_tagsSelectorRow").collapsed = false;
-
- // Add a bookmark.
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: TEST_URI.spec,
- title: "test.me"
- });
-
- // Init panel.
- let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm);
- gEditItemOverlay.initPanel({ node });
-
- // Add a tag.
- PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]);
-
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG,
- "Correctly added tag to a single bookmark");
- is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG,
- "Editing a single bookmark shows the added tag");
- checkTagsSelector([TEST_TAG], [TEST_TAG]);
-
- // Remove tag.
- PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined,
- "The tag has been removed");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing a single bookmark should not show any tag");
- checkTagsSelector([], []);
-
- // Add a second bookmark.
- let bm2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- title: "test.again.me",
- url: TEST_URI2.spec
- });
-
- // Init panel with multiple uris.
- gEditItemOverlay.initPanel({ uris: [TEST_URI, TEST_URI2] });
-
- // Add a tag to the first uri.
- PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG,
- "Correctly added a tag to the first bookmark.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple bookmarks without matching tags should not show any tag.");
- checkTagsSelector([TEST_TAG], []);
-
- // Add a tag to the second uri.
- PlacesUtils.tagging.tagURI(TEST_URI2, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], TEST_TAG,
- "Correctly added a tag to the second bookmark.");
- is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG,
- "Editing multiple bookmarks should show matching tags.");
- checkTagsSelector([TEST_TAG], [TEST_TAG]);
-
- // Remove tag from the first bookmark.
- PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined,
- "Correctly removed tag from the first bookmark.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple bookmarks without matching tags should not show any tag.");
- checkTagsSelector([TEST_TAG], []);
-
- // Remove tag from the second bookmark.
- PlacesUtils.tagging.untagURI(TEST_URI2, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], undefined,
- "Correctly removed tag from the second bookmark.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple bookmarks without matching tags should not show any tag.");
- checkTagsSelector([], []);
-
- // Init panel with a nsIURI entry.
- gEditItemOverlay.initPanel({ uris: [TEST_URI] });
-
- // Add a tag.
- PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG,
- "Correctly added tag to the first entry.");
- is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG,
- "Editing a single nsIURI entry shows the added tag");
- checkTagsSelector([TEST_TAG], [TEST_TAG]);
-
- // Remove tag.
- PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined,
- "Correctly removed tag from the nsIURI entry.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing a single nsIURI entry should not show any tag");
- checkTagsSelector([], []);
-
- // Init panel with multiple nsIURI entries.
- gEditItemOverlay.initPanel({ uris: [TEST_URI, TEST_URI2] });
-
- // Add a tag to the first entry.
- PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG,
- "Tag correctly added.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple nsIURIs without matching tags should not show any tag.");
- checkTagsSelector([TEST_TAG], []);
-
- // Add a tag to the second entry.
- PlacesUtils.tagging.tagURI(TEST_URI2, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], TEST_TAG,
- "Tag correctly added.");
- is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG,
- "Editing multiple nsIURIs should show matching tags");
- checkTagsSelector([TEST_TAG], [TEST_TAG]);
-
- // Remove tag from the first entry.
- PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined,
- "Correctly removed tag from the first entry.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple nsIURIs without matching tags should not show any tag.");
- checkTagsSelector([TEST_TAG], []);
-
- // Remove tag from the second entry.
- PlacesUtils.tagging.untagURI(TEST_URI2, [TEST_TAG]);
- is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], undefined,
- "Correctly removed tag from the second entry.");
- is(document.getElementById("editBMPanel_tagsField").value, "",
- "Editing multiple nsIURIs without matching tags should not show any tag.");
- checkTagsSelector([], []);
-
- // Cleanup.
- yield PlacesUtils.bookmarks.remove(bm.guid);
- yield PlacesUtils.bookmarks.remove(bm2.guid);
- }).then(SimpleTest.finish);
- }
- ]]>
- </script>
-
-</window>
diff --git a/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul b/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul
deleted file mode 100644
index 032c7a258..000000000
--- a/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0"?>
-
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/licenses/publicdomain/
- -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="549192: History view not updated after deleting entry"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript" src="head.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript"><![CDATA[
- /**
- * Ensure that selectItems doesn't recurse infinitely in nested trees.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- Task.spawn(function* () {
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "place:folder=UNFILED_BOOKMARKS",
- title: "shortcut"
- });
-
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "place:folder=UNFILED_BOOKMARKS&maxResults=10",
- title: "query"
- });
-
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "folder"
- });
-
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://www.mozilla.org/",
- title: "bookmark"
- });
-
- // Setup the places tree contents.
- let tree = document.getElementById("tree");
- tree.place = "place:folder=UNFILED_BOOKMARKS";
-
- // Select the last bookmark.
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- tree.selectItems([itemId]);
- is (tree.selectedNode.itemId, itemId, "The right node was selected");
- }).then(SimpleTest.finish);
- }
- ]]></script>
-</window>
diff --git a/browser/components/places/tests/chrome/test_treeview_date.xul b/browser/components/places/tests/chrome/test_treeview_date.xul
deleted file mode 100644
index 559232611..000000000
--- a/browser/components/places/tests/chrome/test_treeview_date.xul
+++ /dev/null
@@ -1,159 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- 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/. -->
-
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
-<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
-<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="435322: Places tree view's formatting"
- onload="runTest();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
- <script type="application/javascript" src="head.js" />
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
- <tree id="tree"
- type="places"
- flatList="true"
- flex="1">
- <treecols>
- <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/>
- <splitter class="tree-splitter"/>
- <treecol label="Tags" id="tags" anonid="tags" flex="1"/>
- <splitter class="tree-splitter"/>
- <treecol label="Url" id="url" anonid="url" flex="1"/>
- <splitter class="tree-splitter"/>
- <treecol label="Visit Date" id="date" anonid="date" flex="1"/>
- <splitter class="tree-splitter"/>
- <treecol label="Visit Count" id="visitCount" anonid="visitCount" flex="1"/>
- </treecols>
- <treechildren flex="1"/>
- </tree>
-
- <script type="application/javascript">
- <![CDATA[
-
- /**
- * Bug 435322
- * https://bugzilla.mozilla.org/show_bug.cgi?id=435322
- *
- * Ensures that date in places treeviews is correctly formatted.
- */
-
- function runTest() {
- SimpleTest.waitForExplicitFinish();
-
- function uri(spec) {
- return Services.io.newURI(spec, null, null);
- }
-
- Task.spawn(function* () {
- yield PlacesTestUtils.clearHistory();
-
- let midnight = new Date();
- midnight.setHours(0);
- midnight.setMinutes(0);
- midnight.setSeconds(0);
- midnight.setMilliseconds(0);
-
- // Add a visit 1ms before midnight, a visit at midnight, and
- // a visit 1ms after midnight.
- yield PlacesTestUtils.addVisits([
- {uri: uri("http://before.midnight.com/"),
- visitDate: (midnight.getTime() - 1) * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED},
- {uri: uri("http://at.midnight.com/"),
- visitDate: (midnight.getTime()) * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED},
- {uri: uri("http://after.midnight.com/"),
- visitDate: (midnight.getTime() + 1) * 1000,
- transition: PlacesUtils.history.TRANSITION_TYPED}
- ]);
-
- // add a bookmark to the midnight visit
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- url: "http://at.midnight.com/",
- title: "A bookmark at midnight",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK
- });
-
- // Make a history query.
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts);
-
- // Setup the places tree contents.
- let tree = document.getElementById("tree");
- tree.place = queryURI;
-
- // loop through the rows and check formatting
- let treeView = tree.view;
- let rc = treeView.rowCount;
- ok(rc >= 3, "Rows found");
- let columns = tree.columns;
- ok(columns.count > 0, "Columns found");
- const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Ci.nsIXULChromeRegistry)
- .getSelectedLocale("global", true);
- for (let r = 0; r < rc; r++) {
- let node = treeView.nodeForTreeIndex(r);
- ok(node, "Places node found");
- for (let ci = 0; ci < columns.count; ci++) {
- let c = columns.getColumnAt(ci);
- let text = treeView.getCellText(r, c);
- switch (c.element.getAttribute("anonid")) {
- case "title":
- // The title can differ, we did not set any title so we would
- // expect null, but in such a case the view will generate a title
- // through PlacesUIUtils.getBestTitle.
- if (node.title)
- is(text, node.title, "Title is correct");
- break;
- case "url":
- is(text, node.uri, "Uri is correct");
- break;
- case "date":
- let timeObj = new Date(node.time / 1000);
- // Default is short date format.
- let dtOptions = { year: 'numeric', month: 'numeric', day: 'numeric',
- hour: 'numeric', minute: 'numeric' };
- // For today's visits we don't show date portion.
- if (node.uri == "http://at.midnight.com/" ||
- node.uri == "http://after.midnight.com/") {
- dtOptions = { hour: 'numeric', minute: 'numeric' };
- } else if (node.uri != "http://before.midnight.com/") {
- // Avoid to test spurious uris, due to how the test works
- // a redirecting uri could be put in the tree while we test.
- break;
- }
- let timeStr = timeObj.toLocaleString(locale, dtOptions);
-
- is(text, timeStr, "Date format is correct");
- break;
- case "visitCount":
- is(text, 1, "Visit count is correct");
- break;
- }
- }
- }
-
- // Cleanup.
- yield PlacesUtils.bookmarks.remove(bm.guid);
- yield PlacesTestUtils.clearHistory();
- }).then(SimpleTest.finish);
- }
- ]]>
- </script>
-</window>
diff --git a/browser/components/places/tests/unit/.eslintrc.js b/browser/components/places/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/places/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/places/tests/unit/bookmarks.glue.html b/browser/components/places/tests/unit/bookmarks.glue.html
deleted file mode 100644
index 07b22e9b3..000000000
--- a/browser/components/places/tests/unit/bookmarks.glue.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE NETSCAPE-Bookmark-file-1>
-<!-- This is an automatically generated file.
- It will be read and overwritten.
- DO NOT EDIT! -->
-<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
-<TITLE>Bookmarks</TITLE>
-<H1>Bookmarks Menu</H1>
-
-<DL><p>
- <DT><A HREF="http://example.com/" ADD_DATE="1233157972" LAST_MODIFIED="1233157984">example</A>
- <DT><H3 ADD_DATE="1233157910" LAST_MODIFIED="1233157972" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks Toolbar</H3>
-<DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
- <DL><p>
- <DT><A HREF="http://example.com/" ADD_DATE="1233157972" LAST_MODIFIED="1233157984">example</A>
- </DL><p>
-</DL><p>
diff --git a/browser/components/places/tests/unit/bookmarks.glue.json b/browser/components/places/tests/unit/bookmarks.glue.json
deleted file mode 100644
index 95900e176..000000000
--- a/browser/components/places/tests/unit/bookmarks.glue.json
+++ /dev/null
@@ -1 +0,0 @@
-{"title":"","id":1,"dateAdded":1233157910552624,"lastModified":1233157955206833,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"title":"Bookmarks Menu","id":2,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157993171424,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"title":"examplejson","id":27,"parent":2,"dateAdded":1233157972101126,"lastModified":1233157984999673,"type":"text/x-moz-place","uri":"http://example.com/"}]},{"index":1,"title":"Bookmarks Toolbar","id":3,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157972101126,"annos":[{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar"}],"type":"text/x-moz-place-container","root":"toolbarFolder","children":[{"title":"examplejson","id":26,"parent":3,"dateAdded":1233157972101126,"lastModified":1233157984999673,"type":"text/x-moz-place","uri":"http://example.com/"}]},{"index":2,"title":"Tags","id":4,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157910582667,"type":"text/x-moz-place-container","root":"tagsFolder","children":[]},{"index":3,"title":"Other Bookmarks","id":5,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157911033315,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[]}]}
diff --git a/browser/components/places/tests/unit/corruptDB.sqlite b/browser/components/places/tests/unit/corruptDB.sqlite
deleted file mode 100644
index b234246ca..000000000
--- a/browser/components/places/tests/unit/corruptDB.sqlite
+++ /dev/null
Binary files differ
diff --git a/browser/components/places/tests/unit/distribution.ini b/browser/components/places/tests/unit/distribution.ini
deleted file mode 100644
index 93e73cb5c..000000000
--- a/browser/components/places/tests/unit/distribution.ini
+++ /dev/null
@@ -1,27 +0,0 @@
-# Distribution Configuration File
-# Bug 516444 demo
-
-[Global]
-id=516444
-version=1.0
-about=Test distribution file
-
-[BookmarksToolbar]
-item.1.title=Toolbar Link Before
-item.1.link=https://example.org/toolbar/before/
-item.1.keyword=e:t:b
-item.1.icon=https://example.org/favicon.png
-item.1.iconData=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==
-item.2.type=default
-item.3.title=Toolbar Link After
-item.3.link=https://example.org/toolbar/after/
-item.3.keyword=e:t:a
-
-[BookmarksMenu]
-item.1.title=Menu Link Before
-item.1.link=https://example.org/menu/before/
-item.1.icon=https://example.org/favicon.png
-item.1.iconData=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==
-item.2.type=default
-item.3.title=Menu Link After
-item.3.link=https://example.org/menu/after/
diff --git a/browser/components/places/tests/unit/head_bookmarks.js b/browser/components/places/tests/unit/head_bookmarks.js
deleted file mode 100644
index 460295f96..000000000
--- a/browser/components/places/tests/unit/head_bookmarks.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- 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/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/LoadContextInfo.jsm");
-
-// Import common head.
-var commonFile = do_get_file("../../../../../toolkit/components/places/tests/head_common.js", false);
-if (commonFile) {
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-XPCOMUtils.defineLazyGetter(this, "PlacesUIUtils", function() {
- Cu.import("resource:///modules/PlacesUIUtils.jsm");
- return PlacesUIUtils;
-});
-
-const ORGANIZER_FOLDER_ANNO = "PlacesOrganizer/OrganizerFolder";
-const ORGANIZER_QUERY_ANNO = "PlacesOrganizer/OrganizerQuery";
-
-// Needed by some test that relies on having an app registered.
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-updateAppInfo({
- name: "PlacesTest",
- ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}",
- version: "1",
- platformVersion: "",
-});
-
-// Smart bookmarks constants.
-const SMART_BOOKMARKS_VERSION = 8;
-const SMART_BOOKMARKS_ON_TOOLBAR = 1;
-const SMART_BOOKMARKS_ON_MENU = 2; // Takes into account the additional separator.
-
-// Default bookmarks constants.
-const DEFAULT_BOOKMARKS_ON_TOOLBAR = 1;
-const DEFAULT_BOOKMARKS_ON_MENU = 1;
-
-const SMART_BOOKMARKS_ANNO = "Places/SmartBookmark";
-
-function checkItemHasAnnotation(guid, name) {
- return PlacesUtils.promiseItemId(guid).then(id => {
- let hasAnnotation = PlacesUtils.annotations.itemHasAnnotation(id, name);
- Assert.ok(hasAnnotation, `Expected annotation ${name}`);
- });
-}
-
-var createCorruptDB = Task.async(function* () {
- let dbPath = OS.Path.join(OS.Constants.Path.profileDir, "places.sqlite");
- yield OS.File.remove(dbPath);
-
- // Create a corrupt database.
- let dir = yield OS.File.getCurrentDirectory();
- let src = OS.Path.join(dir, "corruptDB.sqlite");
- yield OS.File.copy(src, dbPath);
-
- // Check there's a DB now.
- Assert.ok((yield OS.File.exists(dbPath)), "should have a DB now");
-});
-
-/**
- * Rebuilds smart bookmarks listening to console output to report any message or
- * exception generated.
- *
- * @return {Promise}
- * Resolved when done.
- */
-function rebuildSmartBookmarks() {
- let consoleListener = {
- observe(aMsg) {
- if (aMsg.message.startsWith("[JavaScript Warning:")) {
- // TODO (Bug 1300416): Ignore spurious strict warnings.
- return;
- }
- do_throw("Got console message: " + aMsg.message);
- },
- QueryInterface: XPCOMUtils.generateQI([ Ci.nsIConsoleListener ]),
- };
- Services.console.reset();
- Services.console.registerListener(consoleListener);
- do_register_cleanup(() => {
- try {
- Services.console.unregisterListener(consoleListener);
- } catch (ex) { /* will likely fail */ }
- });
- Cc["@mozilla.org/browser/browserglue;1"]
- .getService(Ci.nsIObserver)
- .observe(null, "browser-glue-test", "smart-bookmarks-init");
- return promiseTopicObserved("test-smart-bookmarks-done").then(() => {
- Services.console.unregisterListener(consoleListener);
- });
-}
-
-const SINGLE_TRY_TIMEOUT = 100;
-const NUMBER_OF_TRIES = 30;
-
-/**
- * Similar to waitForConditionPromise, but poll for an asynchronous value
- * every SINGLE_TRY_TIMEOUT ms, for no more than tryCount times.
- *
- * @param promiseFn
- * A function to generate a promise, which resolves to the expected
- * asynchronous value.
- * @param timeoutMsg
- * The reason to reject the returned promise with.
- * @param [optional] tryCount
- * Maximum times to try before rejecting the returned promise with
- * timeoutMsg, defaults to NUMBER_OF_TRIES.
- * @return {Promise}
- * @resolves to the asynchronous value being polled.
- * @rejects if the asynchronous value is not available after tryCount attempts.
- */
-var waitForResolvedPromise = Task.async(function* (promiseFn, timeoutMsg, tryCount=NUMBER_OF_TRIES) {
- let tries = 0;
- do {
- try {
- let value = yield promiseFn();
- return value;
- } catch (ex) {}
- yield new Promise(resolve => do_timeout(SINGLE_TRY_TIMEOUT, resolve));
- } while (++tries <= tryCount);
- throw new Error(timeoutMsg);
-});
diff --git a/browser/components/places/tests/unit/test_421483.js b/browser/components/places/tests/unit/test_421483.js
deleted file mode 100644
index a0d138372..000000000
--- a/browser/components/places/tests/unit/test_421483.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-
-const SMART_BOOKMARKS_PREF = "browser.places.smartBookmarksVersion";
-
-var gluesvc = Cc["@mozilla.org/browser/browserglue;1"].
- getService(Ci.nsIObserver);
-// Avoid default bookmarks import.
-gluesvc.observe(null, "initial-migration-will-import-default-bookmarks", "");
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* smart_bookmarks_disabled() {
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", -1);
- yield rebuildSmartBookmarks();
-
- let smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- Assert.equal(smartBookmarkItemIds.length, 0);
-
- do_print("check that pref has not been bumped up");
- Assert.equal(Services.prefs.getIntPref("browser.places.smartBookmarksVersion"), -1);
-});
-
-add_task(function* create_smart_bookmarks() {
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0);
- yield rebuildSmartBookmarks();
-
- let smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- Assert.notEqual(smartBookmarkItemIds.length, 0);
-
- do_print("check that pref has been bumped up");
- Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0);
-});
-
-add_task(function* remove_smart_bookmark_and_restore() {
- let smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- let smartBookmarksCount = smartBookmarkItemIds.length;
- do_print("remove one smart bookmark and restore");
-
- let guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]);
- yield PlacesUtils.bookmarks.remove(guid);
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0);
-
- yield rebuildSmartBookmarks();
- smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- Assert.equal(smartBookmarkItemIds.length, smartBookmarksCount);
-
- do_print("check that pref has been bumped up");
- Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0);
-});
-
-add_task(function* move_smart_bookmark_rename_and_restore() {
- let smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- let smartBookmarksCount = smartBookmarkItemIds.length;
- do_print("smart bookmark should be restored in place");
-
- let guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]);
- let bm = yield PlacesUtils.bookmarks.fetch(guid);
- let oldTitle = bm.title;
-
- // create a subfolder and move inside it
- let subfolder = yield PlacesUtils.bookmarks.insert({
- parentGuid: bm.parentGuid,
- title: "test",
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- // change title and move into new subfolder
- yield PlacesUtils.bookmarks.update({
- guid: guid,
- parentGuid: subfolder.guid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "new title"
- });
-
- // restore
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0);
- yield rebuildSmartBookmarks();
-
- smartBookmarkItemIds =
- PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO);
- Assert.equal(smartBookmarkItemIds.length, smartBookmarksCount);
-
- guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]);
- bm = yield PlacesUtils.bookmarks.fetch(guid);
- Assert.equal(bm.parentGuid, subfolder.guid);
- Assert.equal(bm.title, oldTitle);
-
- do_print("check that pref has been bumped up");
- Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0);
-});
diff --git a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js
deleted file mode 100644
index c0626f53b..000000000
--- a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js
+++ /dev/null
@@ -1,361 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function waitForBookmarkNotification(aNotification, aCallback, aProperty)
-{
- PlacesUtils.bookmarks.addObserver({
- validate: function (aMethodName, aData)
- {
- if (aMethodName == aNotification &&
- (!aProperty || aProperty == aData.property)) {
- PlacesUtils.bookmarks.removeObserver(this);
- aCallback(aData);
- }
- },
-
- // nsINavBookmarkObserver
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver]),
- onBeginUpdateBatch: function onBeginUpdateBatch() {
- return this.validate(arguments.callee.name, arguments);
- },
- onEndUpdateBatch: function onEndUpdateBatch() {
- return this.validate(arguments.callee.name, arguments);
- },
- onItemAdded: function onItemAdded(aItemId, aParentId, aIndex, aItemType,
- aURI, aTitle)
- {
- return this.validate(arguments.callee.name, { id: aItemId,
- index: aIndex,
- type: aItemType,
- url: aURI ? aURI.spec : null,
- title: aTitle });
- },
- onItemRemoved: function onItemRemoved() {
- return this.validate(arguments.callee.name, arguments);
- },
- onItemChanged: function onItemChanged(id, property, aIsAnno,
- aNewValue, aLastModified, type)
- {
- return this.validate(arguments.callee.name,
- { id,
- get index() {
- return PlacesUtils.bookmarks.getItemIndex(this.id);
- },
- type,
- property,
- get url() {
- return type == PlacesUtils.bookmarks.TYPE_BOOKMARK ?
- PlacesUtils.bookmarks.getBookmarkURI(this.id).spec :
- null;
- },
- get title() {
- return PlacesUtils.bookmarks.getItemTitle(this.id);
- },
- });
- },
- onItemVisited: function onItemVisited() {
- return this.validate(arguments.callee.name, arguments);
- },
- onItemMoved: function onItemMoved(aItemId, aOldParentId, aOldIndex,
- aNewParentId, aNewIndex, aItemType)
- {
- this.validate(arguments.callee.name, { id: aItemId,
- index: aNewIndex,
- type: aItemType });
- }
- }, false);
-}
-
-function wrapNodeByIdAndParent(aItemId, aParentId)
-{
- let wrappedNode;
- let root = PlacesUtils.getFolderContents(aParentId, false, false).root;
- for (let i = 0; i < root.childCount; ++i) {
- let node = root.getChild(i);
- if (node.itemId == aItemId) {
- let type;
- if (PlacesUtils.nodeIsContainer(node)) {
- type = PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER;
- }
- else if (PlacesUtils.nodeIsURI(node)) {
- type = PlacesUtils.TYPE_X_MOZ_PLACE;
- }
- else if (PlacesUtils.nodeIsSeparator(node)) {
- type = PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR;
- }
- else {
- do_throw("Unknown node type");
- }
- wrappedNode = PlacesUtils.wrapNode(node, type);
- }
- }
- root.containerOpen = false;
- return JSON.parse(wrappedNode);
-}
-
-add_test(function test_text_paste()
-{
- const TEST_URL = "http://places.moz.org/"
- const TEST_TITLE = "Places bookmark"
-
- waitForBookmarkNotification("onItemAdded", function(aData)
- {
- do_check_eq(aData.title, TEST_TITLE);
- do_check_eq(aData.url, TEST_URL);
- do_check_eq(aData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aData.index, 0);
- run_next_test();
- });
-
- let txn = PlacesUIUtils.makeTransaction(
- { title: TEST_TITLE, uri: TEST_URL },
- PlacesUtils.TYPE_X_MOZ_URL,
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- true // Unused for text.
- );
- PlacesUtils.transactionManager.doTransaction(txn);
-});
-
-add_test(function test_container()
-{
- const TEST_TITLE = "Places folder"
-
- waitForBookmarkNotification("onItemChanged", function(aChangedData)
- {
- do_check_eq(aChangedData.title, TEST_TITLE);
- do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- do_check_eq(aChangedData.index, 1);
-
- waitForBookmarkNotification("onItemAdded", function(aAddedData)
- {
- do_check_eq(aAddedData.title, TEST_TITLE);
- do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- do_check_eq(aAddedData.index, 2);
- let id = aAddedData.id;
-
- waitForBookmarkNotification("onItemMoved", function(aMovedData)
- {
- do_check_eq(aMovedData.id, id);
- do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- do_check_eq(aMovedData.index, 1);
-
- run_next_test();
- });
-
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- 1, // Move to position 1.
- false
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- });
-
- try {
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- true
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- } catch (ex) {
- do_throw(ex);
- }
- }, "random-anno");
-
- let id = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId,
- TEST_TITLE,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.annotations.setItemAnnotation(id, PlacesUIUtils.DESCRIPTION_ANNO,
- "description", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- PlacesUtils.annotations.setItemAnnotation(id, "random-anno",
- "random-value", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-});
-
-
-add_test(function test_separator()
-{
- waitForBookmarkNotification("onItemChanged", function(aChangedData)
- {
- do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- do_check_eq(aChangedData.index, 3);
-
- waitForBookmarkNotification("onItemAdded", function(aAddedData)
- {
- do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- do_check_eq(aAddedData.index, 4);
- let id = aAddedData.id;
-
- waitForBookmarkNotification("onItemMoved", function(aMovedData)
- {
- do_check_eq(aMovedData.id, id);
- do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- do_check_eq(aMovedData.index, 1);
-
- run_next_test();
- });
-
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- 1, // Move to position 1.
- false
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- });
-
- try {
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- true
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- } catch (ex) {
- do_throw(ex);
- }
- }, "random-anno");
-
- let id = PlacesUtils.bookmarks.insertSeparator(PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.annotations.setItemAnnotation(id, "random-anno",
- "random-value", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-});
-
-add_test(function test_bookmark()
-{
- const TEST_URL = "http://places.moz.org/"
- const TEST_TITLE = "Places bookmark"
-
- waitForBookmarkNotification("onItemChanged", function(aChangedData)
- {
- do_check_eq(aChangedData.title, TEST_TITLE);
- do_check_eq(aChangedData.url, TEST_URL);
- do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aChangedData.index, 5);
-
- waitForBookmarkNotification("onItemAdded", function(aAddedData)
- {
- do_check_eq(aAddedData.title, TEST_TITLE);
- do_check_eq(aAddedData.url, TEST_URL);
- do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aAddedData.index, 6);
- let id = aAddedData.id;
-
- waitForBookmarkNotification("onItemMoved", function(aMovedData)
- {
- do_check_eq(aMovedData.id, id);
- do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aMovedData.index, 1);
-
- run_next_test();
- });
-
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- 1, // Move to position 1.
- false
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- });
-
- try {
- let txn = PlacesUIUtils.makeTransaction(
- wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId),
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- true
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- } catch (ex) {
- do_throw(ex);
- }
- }, "random-anno");
-
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- NetUtil.newURI(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- TEST_TITLE);
- PlacesUtils.annotations.setItemAnnotation(id, PlacesUIUtils.DESCRIPTION_ANNO,
- "description", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- PlacesUtils.annotations.setItemAnnotation(id, "random-anno",
- "random-value", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-});
-
-add_test(function test_visit()
-{
- const TEST_URL = "http://places.moz.org/"
- const TEST_TITLE = "Places bookmark"
-
- waitForBookmarkNotification("onItemAdded", function(aAddedData)
- {
- do_check_eq(aAddedData.title, TEST_TITLE);
- do_check_eq(aAddedData.url, TEST_URL);
- do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aAddedData.index, 7);
-
- waitForBookmarkNotification("onItemAdded", function(aAddedData2)
- {
- do_check_eq(aAddedData2.title, TEST_TITLE);
- do_check_eq(aAddedData2.url, TEST_URL);
- do_check_eq(aAddedData2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- do_check_eq(aAddedData2.index, 8);
- run_next_test();
- });
-
- try {
- let node = wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId);
- // Simulate a not-bookmarked node, will copy it to a new bookmark.
- node.id = -1;
- let txn = PlacesUIUtils.makeTransaction(
- node,
- 0, // Unused for real nodes.
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- true
- );
- PlacesUtils.transactionManager.doTransaction(txn);
- } catch (ex) {
- do_throw(ex);
- }
- });
-
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- NetUtil.newURI(TEST_URL),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- TEST_TITLE);
-});
-
-add_test(function check_annotations() {
- // As last step check how many items for each annotation exist.
-
- // Copies should retain the description annotation.
- let descriptions =
- PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.DESCRIPTION_ANNO, {});
- do_check_eq(descriptions.length, 4);
-
- // Only the original bookmarks should have this annotation.
- let others = PlacesUtils.annotations.getItemsWithAnnotation("random-anno", {});
- do_check_eq(others.length, 3);
- run_next_test();
-});
-
-function run_test()
-{
- run_next_test();
-}
diff --git a/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js b/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js
deleted file mode 100644
index 4db21555f..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue correctly exports bookmarks.html at shutdown if
- * browser.bookmarks.autoExportHTML is set to true.
- */
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- remove_bookmarks_html();
-
- Services.prefs.setBoolPref("browser.bookmarks.autoExportHTML", true);
- do_register_cleanup(() => Services.prefs.clearUserPref("browser.bookmarks.autoExportHTML"));
-
- // Initialize nsBrowserGlue before Places.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports);
-
- // Initialize Places through the History Service.
- Cc["@mozilla.org/browser/nav-history-service;1"]
- .getService(Ci.nsINavHistoryService);
-
- Services.obs.addObserver(function observer() {
- Services.obs.removeObserver(observer, "profile-before-change");
- check_bookmarks_html();
- }, "profile-before-change", false);
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt.js b/browser/components/places/tests/unit/test_browserGlue_corrupt.js
deleted file mode 100644
index 5b2a09068..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_corrupt.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue correctly restores bookmarks from a JSON backup if
- * database is corrupt and one backup is available.
- */
-
-function run_test() {
- // Create our bookmarks.html from bookmarks.glue.html.
- create_bookmarks_html("bookmarks.glue.html");
-
- remove_all_JSON_backups();
-
- // Create our JSON backup from bookmarks.glue.json.
- create_JSON_backup("bookmarks.glue.json");
-
- run_next_test();
-}
-
-do_register_cleanup(function () {
- remove_bookmarks_html();
- remove_all_JSON_backups();
- return PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_main() {
- // Create a corrupt database.
- yield createCorruptDB();
-
- // Initialize nsBrowserGlue before Places.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports);
-
- // Check the database was corrupt.
- // nsBrowserGlue uses databaseStatus to manage initialization.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- // The test will continue once restore has finished and smart bookmarks
- // have been created.
- yield promiseTopicObserved("places-browser-init-complete");
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Check that JSON backup has been restored.
- // Notice restore from JSON notification is fired before smart bookmarks creation.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(bm.title, "examplejson");
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js b/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js
deleted file mode 100644
index 7cb4e5e4c..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue correctly imports from bookmarks.html if database
- * is corrupt but a JSON backup is not available.
- */
-
-function run_test() {
- // Create our bookmarks.html from bookmarks.glue.html.
- create_bookmarks_html("bookmarks.glue.html");
-
- // Remove JSON backup from profile.
- remove_all_JSON_backups();
-
- run_next_test();
-}
-
-do_register_cleanup(remove_bookmarks_html);
-
-add_task(function* () {
- // Create a corrupt database.
- yield createCorruptDB();
-
- // Initialize nsBrowserGlue before Places.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports);
-
- // Check the database was corrupt.
- // nsBrowserGlue uses databaseStatus to manage initialization.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- // The test will continue once import has finished and smart bookmarks
- // have been created.
- yield promiseTopicObserved("places-browser-init-complete");
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Check that bookmarks html has been restored.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(bm.title, "example");
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js b/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js
deleted file mode 100644
index 480420091..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue correctly restores default bookmarks if database is
- * corrupt, nor a JSON backup nor bookmarks.html are available.
- */
-
-Components.utils.import("resource://gre/modules/AppConstants.jsm");
-
-function run_test() {
- // Remove bookmarks.html from profile.
- remove_bookmarks_html();
-
- // Remove JSON backup from profile.
- remove_all_JSON_backups();
-
- run_next_test();
-}
-
-add_task(function* () {
- // Create a corrupt database.
- yield createCorruptDB();
-
- // Initialize nsBrowserGlue before Places.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports);
-
- // Check the database was corrupt.
- // nsBrowserGlue uses databaseStatus to manage initialization.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- // The test will continue once import has finished and smart bookmarks
- // have been created.
- yield promiseTopicObserved("places-browser-init-complete");
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Check that default bookmarks have been restored.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
-
- // Bug 1283076: Nightly bookmark points to Get Involved page, not Getting Started one
- let chanTitle = AppConstants.NIGHTLY_BUILD ? "Get Involved" : "Getting Started";
- do_check_eq(bm.title, chanTitle);
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_distribution.js b/browser/components/places/tests/unit/test_browserGlue_distribution.js
deleted file mode 100644
index c3d6e1d9e..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_distribution.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that nsBrowserGlue correctly imports bookmarks from distribution.ini.
- */
-
-const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
-const PREF_BMPROCESSED = "distribution.516444.bookmarksProcessed";
-const PREF_DISTRIBUTION_ID = "distribution.id";
-
-const TOPICDATA_DISTRIBUTION_CUSTOMIZATION = "force-distribution-customization";
-const TOPIC_CUSTOMIZATION_COMPLETE = "distribution-customization-complete";
-const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
-
-function run_test() {
- // Set special pref to load distribution.ini from the profile folder.
- Services.prefs.setBoolPref("distribution.testing.loadFromProfile", true);
-
- // Copy distribution.ini file to the profile dir.
- let distroDir = gProfD.clone();
- distroDir.leafName = "distribution";
- let iniFile = distroDir.clone();
- iniFile.append("distribution.ini");
- if (iniFile.exists()) {
- iniFile.remove(false);
- print("distribution.ini already exists, did some test forget to cleanup?");
- }
-
- let testDistributionFile = gTestDir.clone();
- testDistributionFile.append("distribution.ini");
- testDistributionFile.copyTo(distroDir, "distribution.ini");
- Assert.ok(testDistributionFile.exists());
-
- run_next_test();
-}
-
-do_register_cleanup(function () {
- // Remove the distribution file, even if the test failed, otherwise all
- // next tests will import it.
- let iniFile = gProfD.clone();
- iniFile.leafName = "distribution";
- iniFile.append("distribution.ini");
- if (iniFile.exists()) {
- iniFile.remove(false);
- }
- Assert.ok(!iniFile.exists());
-});
-
-add_task(function* () {
- // Disable Smart Bookmarks creation.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
-
- // Initialize Places through the History Service and check that a new
- // database has been created.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CREATE);
-
- // Force distribution.
- let glue = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver)
- glue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_DISTRIBUTION_CUSTOMIZATION);
-
- // Test will continue on customization complete notification.
- yield promiseTopicObserved(TOPIC_CUSTOMIZATION_COMPLETE);
-
- // Check the custom bookmarks exist on menu.
- let menuItem = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 0
- });
- Assert.equal(menuItem.title, "Menu Link Before");
-
- menuItem = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 1 + DEFAULT_BOOKMARKS_ON_MENU
- });
- Assert.equal(menuItem.title, "Menu Link After");
-
- // Check no favicon or keyword exists for this bookmark
- yield Assert.rejects(waitForResolvedPromise(() => {
- return PlacesUtils.promiseFaviconData(menuItem.url.href);
- }, "Favicon not found", 10), /Favicon\snot\sfound/, "Favicon not found");
-
- let keywordItem = yield PlacesUtils.keywords.fetch({
- url: menuItem.url.href
- });
- Assert.strictEqual(keywordItem, null);
-
- // Check the custom bookmarks exist on toolbar.
- let toolbarItem = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- Assert.equal(toolbarItem.title, "Toolbar Link Before");
-
- // Check the custom favicon and keyword exist for this bookmark
- let faviconItem = yield waitForResolvedPromise(() => {
- return PlacesUtils.promiseFaviconData(toolbarItem.url.href);
- }, "Favicon not found", 10);
- Assert.equal(faviconItem.uri.spec, "https://example.org/favicon.png");
- Assert.greater(faviconItem.dataLen, 0);
- Assert.equal(faviconItem.mimeType, "image/png");
-
- let base64Icon = "data:image/png;base64," +
- base64EncodeString(String.fromCharCode.apply(String, faviconItem.data));
- Assert.equal(base64Icon, SMALLPNG_DATA_URI.spec);
-
- keywordItem = yield PlacesUtils.keywords.fetch({
- url: toolbarItem.url.href
- });
- Assert.notStrictEqual(keywordItem, null);
- Assert.equal(keywordItem.keyword, "e:t:b");
-
- toolbarItem = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1 + DEFAULT_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(toolbarItem.title, "Toolbar Link After");
-
- // Check the bmprocessed pref has been created.
- Assert.ok(Services.prefs.getBoolPref(PREF_BMPROCESSED));
-
- // Check distribution prefs have been created.
- Assert.equal(Services.prefs.getCharPref(PREF_DISTRIBUTION_ID), "516444");
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_migrate.js b/browser/components/places/tests/unit/test_browserGlue_migrate.js
deleted file mode 100644
index 817f10c81..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_migrate.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that nsBrowserGlue does not overwrite bookmarks imported from the
- * migrators. They usually run before nsBrowserGlue, so if we find any
- * bookmark on init, we should not try to import.
- */
-
-const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
-
-function run_test() {
- // Create our bookmarks.html from bookmarks.glue.html.
- create_bookmarks_html("bookmarks.glue.html");
-
- // Remove current database file.
- clearDB();
-
- run_next_test();
-}
-
-do_register_cleanup(remove_bookmarks_html);
-
-add_task(function* test_migrate_bookmarks() {
- // Initialize Places through the History Service and check that a new
- // database has been created.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CREATE);
-
- // A migrator would run before nsBrowserGlue Places initialization, so mimic
- // that behavior adding a bookmark and notifying the migration.
- let bg = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver);
- bg.observe(null, "initial-migration-will-import-default-bookmarks", null);
-
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://mozilla.org/",
- title: "migrated"
- });
-
- let promise = promiseTopicObserved("places-browser-init-complete");
- bg.observe(null, "initial-migration-did-import-default-bookmarks", null);
- yield promise;
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Check the created bookmark still exists.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: SMART_BOOKMARKS_ON_MENU
- });
- Assert.equal(bm.title, "migrated");
-
- // Check that we have not imported any new bookmark.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: SMART_BOOKMARKS_ON_MENU + 1
- })));
-
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_MENU
- })));
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_prefs.js b/browser/components/places/tests/unit/test_browserGlue_prefs.js
deleted file mode 100644
index 9f3504636..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_prefs.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that nsBrowserGlue is correctly interpreting the preferences settable
- * by the user or by other components.
- */
-
-const PREF_IMPORT_BOOKMARKS_HTML = "browser.places.importBookmarksHTML";
-const PREF_RESTORE_DEFAULT_BOOKMARKS = "browser.bookmarks.restore_default_bookmarks";
-const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
-const PREF_AUTO_EXPORT_HTML = "browser.bookmarks.autoExportHTML";
-
-const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
-const TOPICDATA_FORCE_PLACES_INIT = "force-places-init";
-
-var bg = Cc["@mozilla.org/browser/browserglue;1"].
- getService(Ci.nsIObserver);
-
-function run_test() {
- // Create our bookmarks.html from bookmarks.glue.html.
- create_bookmarks_html("bookmarks.glue.html");
-
- remove_all_JSON_backups();
-
- // Create our JSON backup from bookmarks.glue.json.
- create_JSON_backup("bookmarks.glue.json");
-
- run_next_test();
-}
-
-do_register_cleanup(function () {
- remove_bookmarks_html();
- remove_all_JSON_backups();
-
- return PlacesUtils.bookmarks.eraseEverything();
-});
-
-function simulatePlacesInit() {
- do_print("Simulate Places init");
- // Force nsBrowserGlue::_initPlaces().
- bg.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_FORCE_PLACES_INIT);
- return promiseTopicObserved("places-browser-init-complete");
-}
-
-add_task(function* test_checkPreferences() {
- // Initialize Places through the History Service and check that a new
- // database has been created.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CREATE);
-
- // Wait for Places init notification.
- yield promiseTopicObserved("places-browser-init-complete");
-
- // Ensure preferences status.
- Assert.ok(!Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML));
-
- Assert.throws(() => Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
- Assert.throws(() => Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
-});
-
-add_task(function* test_import() {
- do_print("Import from bookmarks.html if importBookmarksHTML is true.");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been imported, and a smart bookmark has been
- // created.
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(bm.title, "example");
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-});
-
-add_task(function* test_import_noSmartBookmarks() {
- do_print("import from bookmarks.html, but don't create smart bookmarks " +
- "if they are disabled");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
- Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been imported, but smart bookmarks have not
- // been created.
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- Assert.equal(bm.title, "example");
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-});
-
-add_task(function* test_import_autoExport_updatedSmartBookmarks() {
- do_print("Import from bookmarks.html, but don't create smart bookmarks " +
- "if autoExportHTML is true and they are at latest version");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 999);
- Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
- Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been imported, but smart bookmarks have not
- // been created.
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- Assert.equal(bm.title, "example");
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-
- Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
-});
-
-add_task(function* test_import_autoExport_oldSmartBookmarks() {
- do_print("Import from bookmarks.html, and create smart bookmarks if " +
- "autoExportHTML is true and they are not at latest version.");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0);
- Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
- Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been imported, but smart bookmarks have not
- // been created.
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(bm.title, "example");
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-
- Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
-});
-
-add_task(function* test_restore() {
- do_print("restore from default bookmarks.html if " +
- "restore_default_bookmarks is true.");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been restored.
- Assert.ok(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- }));
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
-});
-
-add_task(function* test_restore_import() {
- do_print("setting both importBookmarksHTML and " +
- "restore_default_bookmarks should restore defaults.");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check: we should not have any bookmark on the toolbar.
- Assert.ok(!(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- })));
-
- // Set preferences.
- Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
- Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
-
- yield simulatePlacesInit();
-
- // Check bookmarks.html has been restored.
- Assert.ok(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- }));
-
- // Check preferences have been reverted.
- Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
- Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_restore.js b/browser/components/places/tests/unit/test_browserGlue_restore.js
deleted file mode 100644
index 9d7ac5ac1..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_restore.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue correctly restores bookmarks from a JSON backup if
- * database has been created and one backup is available.
- */
-
-function run_test() {
- // Create our bookmarks.html from bookmarks.glue.html.
- create_bookmarks_html("bookmarks.glue.html");
-
- remove_all_JSON_backups();
-
- // Create our JSON backup from bookmarks.glue.json.
- create_JSON_backup("bookmarks.glue.json");
-
- // Remove current database file.
- clearDB();
-
- run_next_test();
-}
-
-do_register_cleanup(function () {
- remove_bookmarks_html();
- remove_all_JSON_backups();
- return PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_main() {
- // Initialize nsBrowserGlue before Places.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports);
-
- // Initialize Places through the History Service.
- let hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
- // Check a new database has been created.
- // nsBrowserGlue uses databaseStatus to manage initialization.
- Assert.equal(hs.databaseStatus, hs.DATABASE_STATUS_CREATE);
-
- // The test will continue once restore has finished and smart bookmarks
- // have been created.
- yield promiseTopicObserved("places-browser-init-complete");
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Check that JSON backup has been restored.
- // Notice restore from JSON notification is fired before smart bookmarks creation.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: SMART_BOOKMARKS_ON_TOOLBAR
- });
- Assert.equal(bm.title, "examplejson");
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js b/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js
deleted file mode 100644
index 6ecaec4fe..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js
+++ /dev/null
@@ -1,285 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that nsBrowserGlue is correctly interpreting the preferences settable
- * by the user or by other components.
- */
-
-const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
-const PREF_AUTO_EXPORT_HTML = "browser.bookmarks.autoExportHTML";
-const PREF_IMPORT_BOOKMARKS_HTML = "browser.places.importBookmarksHTML";
-const PREF_RESTORE_DEFAULT_BOOKMARKS = "browser.bookmarks.restore_default_bookmarks";
-
-function run_test() {
- remove_bookmarks_html();
- remove_all_JSON_backups();
- run_next_test();
-}
-
-do_register_cleanup(() => PlacesUtils.bookmarks.eraseEverything());
-
-function countFolderChildren(aFolderItemId) {
- let rootNode = PlacesUtils.getFolderContents(aFolderItemId).root;
- let cc = rootNode.childCount;
- // Dump contents.
- for (let i = 0; i < cc ; i++) {
- let node = rootNode.getChild(i);
- let title = PlacesUtils.nodeIsSeparator(node) ? "---" : node.title;
- print("Found child(" + i + "): " + title);
- }
- rootNode.containerOpen = false;
- return cc;
-}
-
-add_task(function* setup() {
- // Initialize browserGlue, but remove it's listener to places-init-complete.
- Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver);
-
- // Initialize Places.
- PlacesUtils.history;
-
- // Wait for Places init notification.
- yield promiseTopicObserved("places-browser-init-complete");
-
- // Ensure preferences status.
- Assert.ok(!Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML));
- Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
- Assert.throws(() => Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-});
-
-add_task(function* test_version_0() {
- do_print("All smart bookmarks are created if smart bookmarks version is 0.");
-
- // Sanity check: we should have default bookmark.
- Assert.ok(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- }));
-
- Assert.ok(yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 0
- }));
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
-
-add_task(function* test_version_change() {
- do_print("An existing smart bookmark is replaced when version changes.");
-
- // Sanity check: we have a smart bookmark on the toolbar.
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
-
- // Change its title.
- yield PlacesUtils.bookmarks.update({guid: bm.guid, title: "new title"});
- bm = yield PlacesUtils.bookmarks.fetch({guid: bm.guid});
- Assert.equal(bm.title, "new title");
-
- // Sanity check items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Check smart bookmark has been replaced, itemId has changed.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
- Assert.notEqual(bm.title, "new title");
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
-
-add_task(function* test_version_change_pos() {
- do_print("bookmarks position is retained when version changes.");
-
- // Sanity check items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
- let firstItemTitle = bm.title;
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Check smart bookmarks are still in correct position.
- bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO);
- Assert.equal(bm.title, firstItemTitle);
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
-
-add_task(function* test_version_change_pos_moved() {
- do_print("moved bookmarks position is retained when version changes.");
-
- // Sanity check items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- let bm1 = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: 0
- });
- yield checkItemHasAnnotation(bm1.guid, SMART_BOOKMARKS_ANNO);
- let firstItemTitle = bm1.title;
-
- // Move the first smart bookmark to the end of the menu.
- yield PlacesUtils.bookmarks.update({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- guid: bm1.guid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
-
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
- Assert.equal(bm.guid, bm1.guid);
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- bm1 = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
- yield checkItemHasAnnotation(bm1.guid, SMART_BOOKMARKS_ANNO);
- Assert.equal(bm1.title, firstItemTitle);
-
- // Move back the smart bookmark to the original position.
- yield PlacesUtils.bookmarks.update({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- guid: bm1.guid,
- index: 1
- });
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
-
-add_task(function* test_recreation() {
- do_print("An explicitly removed smart bookmark should not be recreated.");
-
- // Remove toolbar's smart bookmarks
- let bm = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0
- });
- yield PlacesUtils.bookmarks.remove(bm.guid);
-
- // Sanity check items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- // We should not have recreated the smart bookmark on toolbar.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
-
-add_task(function* test_recreation_version_0() {
- do_print("Even if a smart bookmark has been removed recreate it if version is 0.");
-
- // Sanity check items.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Set preferences.
- Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0);
-
- yield rebuildSmartBookmarks();
-
- // Count items.
- // We should not have recreated the smart bookmark on toolbar.
- Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId),
- SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR);
- Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId),
- SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU);
-
- // Check version has been updated.
- Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION),
- SMART_BOOKMARKS_VERSION);
-});
diff --git a/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js b/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js
deleted file mode 100644
index 072056b3f..000000000
--- a/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/* 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/. */
-
-const UI_VERSION = 26;
-const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
-const TOPICDATA_BROWSERGLUE_TEST = "force-ui-migration";
-const DEFAULT_BEHAVIOR_PREF = "browser.urlbar.default.behavior";
-const AUTOCOMPLETE_PREF = "browser.urlbar.autocomplete.enabled";
-
-var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"]
- .getService(Ci.nsIObserver);
-var gGetBoolPref = Services.prefs.getBoolPref;
-
-function run_test() {
- run_next_test();
-}
-
-do_register_cleanup(cleanup);
-
-function cleanup() {
- let prefix = "browser.urlbar.suggest.";
- for (let type of ["history", "bookmark", "openpage", "history.onlyTyped"]) {
- Services.prefs.clearUserPref(prefix + type);
- }
- Services.prefs.clearUserPref("browser.migration.version");
- Services.prefs.clearUserPref(AUTOCOMPLETE_PREF);
-}
-
-function setupBehaviorAndMigrate(aDefaultBehavior, aAutocompleteEnabled = true) {
- cleanup();
- // Migrate browser.urlbar.default.behavior preference.
- Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1);
- Services.prefs.setIntPref(DEFAULT_BEHAVIOR_PREF, aDefaultBehavior);
- Services.prefs.setBoolPref(AUTOCOMPLETE_PREF, aAutocompleteEnabled);
- // Simulate a migration.
- gBrowserGlue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_BROWSERGLUE_TEST);
-}
-
-add_task(function*() {
- do_print("Migrate default.behavior = 0");
- setupBehaviorAndMigrate(0);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"),
- "Bookmark preference should be true.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.openpage"),
- "Openpage preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false.");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 1");
- setupBehaviorAndMigrate(1);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false,
- "Bookmark preference should be false.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 2");
- setupBehaviorAndMigrate(2);
-
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history"), false,
- "History preference should be false.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"),
- "Bookmark preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 3");
- setupBehaviorAndMigrate(3);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"),
- "Bookmark preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 19");
- setupBehaviorAndMigrate(19);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"),
- "Bookmark preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 33");
- setupBehaviorAndMigrate(33);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false,
- "Bookmark preference should be false.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"),
- "Typed preference should be true");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 129");
- setupBehaviorAndMigrate(129);
-
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"),
- "History preference should be true.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false,
- "Bookmark preference should be false.");
- Assert.ok(gGetBoolPref("browser.urlbar.suggest.openpage"),
- "Openpage preference should be true");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
-
-add_task(function*() {
- do_print("Migrate default.behavior = 0, autocomplete.enabled = false");
- setupBehaviorAndMigrate(0, false);
-
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history"), false,
- "History preference should be false.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false,
- "Bookmark preference should be false.");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false,
- "Openpage preference should be false");
- Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false,
- "Typed preference should be false");
-});
diff --git a/browser/components/places/tests/unit/test_clearHistory_shutdown.js b/browser/components/places/tests/unit/test_clearHistory_shutdown.js
deleted file mode 100644
index 0c1d78801..000000000
--- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js
+++ /dev/null
@@ -1,181 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that requesting clear history at shutdown will really clear history.
- */
-
-const URIS = [
- "http://a.example1.com/"
-, "http://b.example1.com/"
-, "http://b.example2.com/"
-, "http://c.example3.com/"
-];
-
-const TOPIC_CONNECTION_CLOSED = "places-connection-closed";
-
-var EXPECTED_NOTIFICATIONS = [
- "places-shutdown"
-, "places-will-close-connection"
-, "places-expiration-finished"
-, "places-connection-closed"
-];
-
-const UNEXPECTED_NOTIFICATIONS = [
- "xpcom-shutdown"
-];
-
-const FTP_URL = "ftp://localhost/clearHistoryOnShutdown/";
-
-// Send the profile-after-change notification to the form history component to ensure
-// that it has been initialized.
-var formHistoryStartup = Cc["@mozilla.org/satchel/form-history-startup;1"].
- getService(Ci.nsIObserver);
-formHistoryStartup.observe(null, "profile-after-change", null);
-XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
- "resource://gre/modules/FormHistory.jsm");
-
-var timeInMicroseconds = Date.now() * 1000;
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_execute() {
- do_print("Initialize browserglue before Places");
-
- // Avoid default bookmarks import.
- let glue = Cc["@mozilla.org/browser/browserglue;1"].
- getService(Ci.nsIObserver);
- glue.observe(null, "initial-migration-will-import-default-bookmarks", null);
- glue.observe(null, "test-initialize-sanitizer", null);
-
-
- Services.prefs.setBoolPref("privacy.clearOnShutdown.cache", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.cookies", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.offlineApps", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.history", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.downloads", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.cookies", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.formData", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.sessions", true);
- Services.prefs.setBoolPref("privacy.clearOnShutdown.siteSettings", true);
-
- Services.prefs.setBoolPref("privacy.sanitize.sanitizeOnShutdown", true);
-
- do_print("Add visits.");
- for (let aUrl of URIS) {
- yield PlacesTestUtils.addVisits({
- uri: uri(aUrl), visitDate: timeInMicroseconds++,
- transition: PlacesUtils.history.TRANSITION_TYPED
- });
- }
- do_print("Add cache.");
- yield storeCache(FTP_URL, "testData");
- do_print("Add form history.");
- yield addFormHistory();
- Assert.equal((yield getFormHistoryCount()), 1, "Added form history");
-
- do_print("Simulate and wait shutdown.");
- yield shutdownPlaces();
-
- Assert.equal((yield getFormHistoryCount()), 0, "Form history cleared");
-
- let stmt = DBConn(true).createStatement(
- "SELECT id FROM moz_places WHERE url = :page_url "
- );
-
- try {
- URIS.forEach(function(aUrl) {
- stmt.params.page_url = aUrl;
- do_check_false(stmt.executeStep());
- stmt.reset();
- });
- } finally {
- stmt.finalize();
- }
-
- do_print("Check cache");
- // Check cache.
- yield checkCache(FTP_URL);
-});
-
-function addFormHistory() {
- return new Promise(resolve => {
- let now = Date.now() * 1000;
- FormHistory.update({ op: "add",
- fieldname: "testfield",
- value: "test",
- timesUsed: 1,
- firstUsed: now,
- lastUsed: now
- },
- { handleCompletion(reason) { resolve(); } });
- });
-}
-
-function getFormHistoryCount() {
- return new Promise((resolve, reject) => {
- let count = -1;
- FormHistory.count({ fieldname: "testfield" },
- { handleResult(result) { count = result; },
- handleCompletion(reason) { resolve(count); }
- });
- });
-}
-
-function storeCache(aURL, aContent) {
- let cache = Services.cache2;
- let storage = cache.diskCacheStorage(LoadContextInfo.default, false);
-
- return new Promise(resolve => {
- let storeCacheListener = {
- onCacheEntryCheck: function (entry, appcache) {
- return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED;
- },
-
- onCacheEntryAvailable: function (entry, isnew, appcache, status) {
- do_check_eq(status, Cr.NS_OK);
-
- entry.setMetaDataElement("servertype", "0");
- var os = entry.openOutputStream(0);
-
- var written = os.write(aContent, aContent.length);
- if (written != aContent.length) {
- do_throw("os.write has not written all data!\n" +
- " Expected: " + written + "\n" +
- " Actual: " + aContent.length + "\n");
- }
- os.close();
- entry.close();
- resolve();
- }
- };
-
- storage.asyncOpenURI(Services.io.newURI(aURL, null, null), "",
- Ci.nsICacheStorage.OPEN_NORMALLY,
- storeCacheListener);
- });
-}
-
-
-function checkCache(aURL) {
- let cache = Services.cache2;
- let storage = cache.diskCacheStorage(LoadContextInfo.default, false);
-
- return new Promise(resolve => {
- let checkCacheListener = {
- onCacheEntryAvailable: function (entry, isnew, appcache, status) {
- do_check_eq(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND);
- resolve();
- }
- };
-
- storage.asyncOpenURI(Services.io.newURI(aURL, null, null), "",
- Ci.nsICacheStorage.OPEN_READONLY,
- checkCacheListener);
- });
-}
diff --git a/browser/components/places/tests/unit/test_leftpane_corruption_handling.js b/browser/components/places/tests/unit/test_leftpane_corruption_handling.js
deleted file mode 100644
index 0af6f4e95..000000000
--- a/browser/components/places/tests/unit/test_leftpane_corruption_handling.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* 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/. */
-
-/**
- * Tests that we build a working leftpane in various corruption situations.
- */
-
-// Used to store the original leftPaneFolderId getter.
-var gLeftPaneFolderIdGetter;
-var gAllBookmarksFolderIdGetter;
-// Used to store the original left Pane status as a JSON string.
-var gReferenceHierarchy;
-var gLeftPaneFolderId;
-
-add_task(function* () {
- // We want empty roots.
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Sanity check.
- Assert.ok(!!PlacesUIUtils);
-
- // Check getters.
- gLeftPaneFolderIdGetter = Object.getOwnPropertyDescriptor(PlacesUIUtils, "leftPaneFolderId");
- Assert.equal(typeof(gLeftPaneFolderIdGetter.get), "function");
- gAllBookmarksFolderIdGetter = Object.getOwnPropertyDescriptor(PlacesUIUtils, "allBookmarksFolderId");
- Assert.equal(typeof(gAllBookmarksFolderIdGetter.get), "function");
-
- do_register_cleanup(() => PlacesUtils.bookmarks.eraseEverything());
-});
-
-add_task(function* () {
- // Add a third party bogus annotated item. Should not be removed.
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "test",
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- let folderId = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_QUERY_ANNO,
- "test", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- // Create the left pane, and store its current status, it will be used
- // as reference value.
- gLeftPaneFolderId = PlacesUIUtils.leftPaneFolderId;
- gReferenceHierarchy = folderIdToHierarchy(gLeftPaneFolderId);
-
- while (gTests.length) {
- // Run current test.
- yield Task.spawn(gTests.shift());
-
- // Regenerate getters.
- Object.defineProperty(PlacesUIUtils, "leftPaneFolderId", gLeftPaneFolderIdGetter);
- gLeftPaneFolderId = PlacesUIUtils.leftPaneFolderId;
- Object.defineProperty(PlacesUIUtils, "allBookmarksFolderId", gAllBookmarksFolderIdGetter);
-
- // Check the new left pane folder.
- let leftPaneHierarchy = folderIdToHierarchy(gLeftPaneFolderId)
- Assert.equal(gReferenceHierarchy, leftPaneHierarchy);
-
- folder = yield PlacesUtils.bookmarks.fetch({guid: folder.guid});
- Assert.equal(folder.title, "test");
- }
-});
-
-// Corruption cases.
-var gTests = [
-
- function* test1() {
- print("1. Do nothing, checks test calibration.");
- },
-
- function* test2() {
- print("2. Delete the left pane folder.");
- let guid = yield PlacesUtils.promiseItemGuid(gLeftPaneFolderId);
- yield PlacesUtils.bookmarks.remove(guid);
- },
-
- function* test3() {
- print("3. Delete a child of the left pane folder.");
- let guid = yield PlacesUtils.promiseItemGuid(gLeftPaneFolderId);
- let bm = yield PlacesUtils.bookmarks.fetch({parentGuid: guid, index: 0});
- yield PlacesUtils.bookmarks.remove(bm.guid);
- },
-
- function* test4() {
- print("4. Delete AllBookmarks.");
- let guid = yield PlacesUtils.promiseItemGuid(PlacesUIUtils.allBookmarksFolderId);
- yield PlacesUtils.bookmarks.remove(guid);
- },
-
- function* test5() {
- print("5. Create a duplicated left pane folder.");
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "PlacesRoot",
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- let folderId = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_FOLDER_ANNO,
- "PlacesRoot", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- },
-
- function* test6() {
- print("6. Create a duplicated left pane query.");
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "AllBookmarks",
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- let folderId = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_QUERY_ANNO,
- "AllBookmarks", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- },
-
- function* test7() {
- print("7. Remove the left pane folder annotation.");
- PlacesUtils.annotations.removeItemAnnotation(gLeftPaneFolderId,
- ORGANIZER_FOLDER_ANNO);
- },
-
- function* test8() {
- print("8. Remove a left pane query annotation.");
- PlacesUtils.annotations.removeItemAnnotation(PlacesUIUtils.allBookmarksFolderId,
- ORGANIZER_QUERY_ANNO);
- },
-
- function* test9() {
- print("9. Remove a child of AllBookmarks.");
- let guid = yield PlacesUtils.promiseItemGuid(PlacesUIUtils.allBookmarksFolderId);
- let bm = yield PlacesUtils.bookmarks.fetch({parentGuid: guid, index: 0});
- yield PlacesUtils.bookmarks.remove(bm.guid);
- }
-
-];
-
-/**
- * Convert a folder item id to a JSON representation of it and its contents.
- */
-function folderIdToHierarchy(aFolderId) {
- let root = PlacesUtils.getFolderContents(aFolderId).root;
- let hier = JSON.stringify(hierarchyToObj(root));
- root.containerOpen = false;
- return hier;
-}
-
-function hierarchyToObj(aNode) {
- let o = {}
- o.title = aNode.title;
- o.annos = PlacesUtils.getAnnotationsForItem(aNode.itemId)
- if (PlacesUtils.nodeIsURI(aNode)) {
- o.uri = aNode.uri;
- }
- else if (PlacesUtils.nodeIsFolder(aNode)) {
- o.children = [];
- PlacesUtils.asContainer(aNode).containerOpen = true;
- for (let i = 0; i < aNode.childCount; ++i) {
- o.children.push(hierarchyToObj(aNode.getChild(i)));
- }
- aNode.containerOpen = false;
- }
- return o;
-}
diff --git a/browser/components/places/tests/unit/xpcshell.ini b/browser/components/places/tests/unit/xpcshell.ini
deleted file mode 100644
index 1c40e1c53..000000000
--- a/browser/components/places/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,25 +0,0 @@
-[DEFAULT]
-head = head_bookmarks.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files =
- bookmarks.glue.html
- bookmarks.glue.json
- corruptDB.sqlite
- distribution.ini
-
-[test_421483.js]
-[test_browserGlue_bookmarkshtml.js]
-[test_browserGlue_corrupt.js]
-[test_browserGlue_corrupt_nobackup.js]
-[test_browserGlue_corrupt_nobackup_default.js]
-[test_browserGlue_distribution.js]
-[test_browserGlue_migrate.js]
-[test_browserGlue_prefs.js]
-[test_browserGlue_restore.js]
-[test_browserGlue_smartBookmarks.js]
-[test_browserGlue_urlbar_defaultbehavior_migration.js]
-[test_clearHistory_shutdown.js]
-[test_leftpane_corruption_handling.js]
-[test_PUIU_makeTransaction.js]
diff --git a/browser/components/preferences/in-content/tests/.eslintrc.js b/browser/components/preferences/in-content/tests/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/preferences/in-content/tests/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/preferences/in-content/tests/browser.ini b/browser/components/preferences/in-content/tests/browser.ini
deleted file mode 100644
index 6cba02599..000000000
--- a/browser/components/preferences/in-content/tests/browser.ini
+++ /dev/null
@@ -1,43 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- privacypane_tests_perwindow.js
-
-[browser_advanced_update.js]
-[browser_basic_rebuild_fonts_test.js]
-[browser_bug410900.js]
-[browser_bug705422.js]
-[browser_bug731866.js]
-[browser_bug795764_cachedisabled.js]
-[browser_bug1018066_resetScrollPosition.js]
-[browser_bug1020245_openPreferences_to_paneContent.js]
-[browser_bug1184989_prevent_scrolling_when_preferences_flipped.js]
-support-files =
- browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul
-[browser_change_app_handler.js]
-skip-if = os != "win" # This test tests the windows-specific app selection dialog, so can't run on non-Windows
-[browser_connection.js]
-[browser_connection_bug388287.js]
-[browser_cookies_exceptions.js]
-[browser_defaultbrowser_alwayscheck.js]
-[browser_healthreport.js]
-skip-if = true || !healthreport # Bug 1185403 for the "true"
-[browser_homepages_filter_aboutpreferences.js]
-[browser_notifications_do_not_disturb.js]
-[browser_permissions_urlFieldHidden.js]
-[browser_proxy_backup.js]
-[browser_privacypane_1.js]
-[browser_privacypane_3.js]
-[browser_privacypane_4.js]
-[browser_privacypane_5.js]
-[browser_privacypane_8.js]
-[browser_sanitizeOnShutdown_prefLocked.js]
-[browser_searchsuggestions.js]
-[browser_security.js]
-[browser_subdialogs.js]
-support-files =
- subdialog.xul
- subdialog2.xul
-[browser_telemetry.js]
-# Skip this test on Android as FHR and Telemetry are separate systems there.
-skip-if = !healthreport || !telemetry || (os == 'linux' && debug) || (os == 'android')
diff --git a/browser/components/preferences/in-content/tests/browser_advanced_update.js b/browser/components/preferences/in-content/tests/browser_advanced_update.js
deleted file mode 100644
index e9d0e8652..000000000
--- a/browser/components/preferences/in-content/tests/browser_advanced_update.js
+++ /dev/null
@@ -1,158 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const { classes: Cc, interfaces: Ci, manager: Cm, utils: Cu, results: Cr } = Components;
-
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-
-const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
-
-const mockUpdateManager = {
- contractId: "@mozilla.org/updates/update-manager;1",
-
- _mockClassId: uuidGenerator.generateUUID(),
-
- _originalClassId: "",
-
- _originalFactory: null,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager]),
-
- createInstance: function(outer, iiD) {
- if (outer) {
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
- return this.QueryInterface(iiD);
- },
-
- register: function () {
- let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
- if (!registrar.isCIDRegistered(this._mockClassId)) {
- this._originalClassId = registrar.contractIDToCID(this.contractId);
- this._originalFactory = Cm.getClassObject(Cc[this.contractId], Ci.nsIFactory);
- registrar.unregisterFactory(this._originalClassId, this._originalFactory);
- registrar.registerFactory(this._mockClassId, "Unregister after testing", this.contractId, this);
- }
- },
-
- unregister: function () {
- let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
- registrar.unregisterFactory(this._mockClassId, this);
- registrar.registerFactory(this._originalClassId, "", this.contractId, this._originalFactory);
- },
-
- get updateCount() {
- return this._updates.length;
- },
-
- getUpdateAt: function (index) {
- return this._updates[index];
- },
-
- _updates: [
- {
- name: "Firefox Developer Edition 49.0a2",
- statusText: "The Update was successfully installed",
- buildID: "20160728004010",
- type: "minor",
- installDate: 1469763105156,
- detailsURL: "https://www.mozilla.org/firefox/aurora/"
- },
- {
- name: "Firefox Developer Edition 43.0a2",
- statusText: "The Update was successfully installed",
- buildID: "20150929004011",
- type: "minor",
- installDate: 1443585886224,
- detailsURL: "https://www.mozilla.org/firefox/aurora/"
- },
- {
- name: "Firefox Developer Edition 42.0a2",
- statusText: "The Update was successfully installed",
- buildID: "20150920004018",
- type: "major",
- installDate: 1442818147544,
- detailsURL: "https://www.mozilla.org/firefox/aurora/"
- }
- ]
-};
-
-function resetPreferences() {
- Services.prefs.clearUserPref("browser.search.update");
-}
-
-function formatInstallDate(sec) {
- var date = new Date(sec);
- const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Ci.nsIXULChromeRegistry)
- .getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric', second: 'numeric' };
- return date.toLocaleString(locale, dtOptions);
-}
-
-registerCleanupFunction(resetPreferences);
-
-add_task(function*() {
- yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab", { leaveOpen: true });
- resetPreferences();
- Services.prefs.setBoolPref("browser.search.update", false);
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let enableSearchUpdate = doc.getElementById("enableSearchUpdate");
- is_element_visible(enableSearchUpdate, "Check search update preference is visible");
-
- // Ensure that the update pref dialog reflects the actual pref value.
- ok(!enableSearchUpdate.checked, "Ensure search updates are disabled");
- Services.prefs.setBoolPref("browser.search.update", true);
- ok(enableSearchUpdate.checked, "Ensure search updates are enabled");
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function*() {
- mockUpdateManager.register();
-
- yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab", { leaveOpen: true });
- let doc = gBrowser.selectedBrowser.contentDocument;
-
- let showBtn = doc.getElementById("showUpdateHistory");
- let dialogOverlay = doc.getElementById("dialogOverlay");
-
- // Test the dialog window opens
- is(dialogOverlay.style.visibility, "", "The dialog should be invisible");
- showBtn.doCommand();
- yield promiseLoadSubDialog("chrome://mozapps/content/update/history.xul");
- is(dialogOverlay.style.visibility, "visible", "The dialog should be visible");
-
- let dialogFrame = doc.getElementById("dialogFrame");
- let frameDoc = dialogFrame.contentDocument;
- let updates = frameDoc.querySelectorAll("update");
-
- // Test the update history numbers are correct
- is(updates.length, mockUpdateManager.updateCount, "The update count is incorrect.");
-
- // Test the updates are displayed correctly
- let update = null;
- let updateData = null;
- for (let i = 0; i < updates.length; ++i) {
- update = updates[i];
- updateData = mockUpdateManager.getUpdateAt(i);
-
- is(update.name, updateData.name + " (" + updateData.buildID + ")", "Wrong update name");
- is(update.type, updateData.type == "major" ? "New Version" : "Security Update", "Wrong update type");
- is(update.installDate, formatInstallDate(updateData.installDate), "Wrong update installDate");
- is(update.detailsURL, updateData.detailsURL, "Wrong update detailsURL");
- is(update.status, updateData.statusText, "Wrong update status");
- }
-
- // Test the dialog window closes
- let closeBtn = doc.getElementById("dialogClose");
- closeBtn.doCommand();
- is(dialogOverlay.style.visibility, "", "The dialog should be invisible");
-
- mockUpdateManager.unregister();
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js
deleted file mode 100644
index 32c1bd726..000000000
--- a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-Services.prefs.setBoolPref("browser.preferences.instantApply", true);
-
-registerCleanupFunction(function() {
- Services.prefs.clearUserPref("browser.preferences.instantApply");
-});
-
-add_task(function*() {
- yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true});
- let doc = gBrowser.contentDocument;
- var langGroup = Services.prefs.getComplexValue("font.language.group", Ci.nsIPrefLocalizedString).data
- is(doc.getElementById("font.language.group").value, langGroup,
- "Language group should be set correctly.");
-
- let defaultFontType = Services.prefs.getCharPref("font.default." + langGroup);
- let fontFamily = Services.prefs.getCharPref("font.name." + defaultFontType + "." + langGroup);
- let fontFamilyField = doc.getElementById("defaultFont");
- is(fontFamilyField.value, fontFamily, "Font family should be set correctly.");
-
- let defaultFontSize = Services.prefs.getIntPref("font.size.variable." + langGroup);
- let fontSizeField = doc.getElementById("defaultFontSize");
- is(fontSizeField.value, defaultFontSize, "Font size should be set correctly.");
-
- doc.getElementById("advancedFonts").click();
- let win = yield promiseLoadSubDialog("chrome://browser/content/preferences/fonts.xul");
- doc = win.document;
-
- // Simulate a dumb font backend.
- win.FontBuilder._enumerator = {
- _list: ["MockedFont1", "MockedFont2", "MockedFont3"],
- EnumerateFonts: function(lang, type, list) {
- return this._list;
- },
- EnumerateAllFonts: function() {
- return this._list;
- },
- getDefaultFont: function() { return null; },
- getStandardFamilyName: function(name) { return name; },
- };
- win.FontBuilder._allFonts = null;
- win.FontBuilder._langGroupSupported = false;
-
- let langGroupElement = doc.getElementById("font.language.group");
- let selectLangsField = doc.getElementById("selectLangs");
- let serifField = doc.getElementById("serif");
- let armenian = "x-armn";
- let western = "x-western";
-
- langGroupElement.value = armenian;
- selectLangsField.value = armenian;
- is(serifField.value, "", "Font family should not be set.");
-
- langGroupElement.value = western;
- selectLangsField.value = western;
-
- // Simulate a font backend supporting language-specific enumeration.
- // NB: FontBuilder has cached the return value from EnumerateAllFonts(),
- // so _allFonts will always have 3 elements regardless of subsequent
- // _list changes.
- win.FontBuilder._enumerator._list = ["MockedFont2"];
-
- langGroupElement.value = armenian;
- selectLangsField.value = armenian;
- is(serifField.value, "MockedFont2", "Font family should be set.");
-
- langGroupElement.value = western;
- selectLangsField.value = western;
-
- // Simulate a system that has no fonts for the specified language.
- win.FontBuilder._enumerator._list = [];
-
- langGroupElement.value = armenian;
- selectLangsField.value = armenian;
- is(serifField.value, "", "Font family should not be set.");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js b/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js
deleted file mode 100644
index 9d938fdd4..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var originalWindowHeight;
-registerCleanupFunction(function() {
- window.resizeTo(window.outerWidth, originalWindowHeight);
- while (gBrowser.tabs[1])
- gBrowser.removeTab(gBrowser.tabs[1]);
-});
-
-add_task(function*() {
- originalWindowHeight = window.outerHeight;
- window.resizeTo(window.outerWidth, 300);
- let prefs = yield openPreferencesViaOpenPreferencesAPI("paneApplications", undefined, {leaveOpen: true});
- is(prefs.selectedPane, "paneApplications", "Applications pane was selected");
- let mainContent = gBrowser.contentDocument.querySelector(".main-content");
- mainContent.scrollTop = 50;
- is(mainContent.scrollTop, 50, "main-content should be scrolled 50 pixels");
-
- gBrowser.contentWindow.gotoPref("paneGeneral");
- is(mainContent.scrollTop, 0,
- "Switching to a different category should reset the scroll position");
-});
-
diff --git a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js
deleted file mode 100644
index bc2c6d800..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Services.prefs.setBoolPref("browser.preferences.instantApply", true);
-
-registerCleanupFunction(function() {
- Services.prefs.clearUserPref("browser.preferences.instantApply");
-});
-
-add_task(function*() {
- let prefs = yield openPreferencesViaOpenPreferencesAPI("paneContent");
- is(prefs.selectedPane, "paneContent", "Content pane was selected");
- prefs = yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab");
- is(prefs.selectedPane, "paneAdvanced", "Advanced pane was selected");
- is(prefs.selectedAdvancedTab, "updateTab", "The update tab within the advanced prefs should be selected");
- prefs = yield openPreferencesViaHash("privacy");
- is(prefs.selectedPane, "panePrivacy", "Privacy pane is selected when hash is 'privacy'");
- prefs = yield openPreferencesViaOpenPreferencesAPI("nonexistant-category");
- is(prefs.selectedPane, "paneGeneral", "General pane is selected by default when a nonexistant-category is requested");
- prefs = yield openPreferencesViaHash("nonexistant-category");
- is(prefs.selectedPane, "paneGeneral", "General pane is selected when hash is a nonexistant-category");
- prefs = yield openPreferencesViaHash();
- is(prefs.selectedPane, "paneGeneral", "General pane is selected by default");
-});
-
-function openPreferencesViaHash(aPane) {
- let deferred = Promise.defer();
- gBrowser.selectedTab = gBrowser.addTab("about:preferences" + (aPane ? "#" + aPane : ""));
- let newTabBrowser = gBrowser.selectedBrowser;
-
- newTabBrowser.addEventListener("Initialized", function PrefInit() {
- newTabBrowser.removeEventListener("Initialized", PrefInit, true);
- newTabBrowser.contentWindow.addEventListener("load", function prefLoad() {
- newTabBrowser.contentWindow.removeEventListener("load", prefLoad);
- let win = gBrowser.contentWindow;
- let selectedPane = win.history.state;
- gBrowser.removeCurrentTab();
- deferred.resolve({selectedPane: selectedPane});
- });
- }, true);
-
- return deferred.promise;
-}
diff --git a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js b/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js
deleted file mode 100644
index 0972b2de4..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js
+++ /dev/null
@@ -1,92 +0,0 @@
-const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
-
-add_task(function* () {
- waitForExplicitFinish();
-
- const tabURL = getRootDirectory(gTestPath) + "browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul";
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: tabURL }, function* (browser) {
- let doc = browser.contentDocument;
- let container = doc.getElementById("container");
-
- // Test button
- let button = doc.getElementById("button");
- button.focus();
- EventUtils.synthesizeKey(" ", {});
- yield checkPageScrolling(container, "button");
-
- // Test checkbox
- let checkbox = doc.getElementById("checkbox");
- checkbox.focus();
- EventUtils.synthesizeKey(" ", {});
- ok(checkbox.checked, "Checkbox is checked");
- yield checkPageScrolling(container, "checkbox");
-
- // Test listbox
- let listbox = doc.getElementById("listbox");
- let listitem = doc.getElementById("listitem");
- listbox.focus();
- EventUtils.synthesizeKey(" ", {});
- ok(listitem.selected, "Listitem is selected");
- yield checkPageScrolling(container, "listbox");
-
- // Test radio
- let radiogroup = doc.getElementById("radiogroup");
- radiogroup.focus();
- EventUtils.synthesizeKey(" ", {});
- yield checkPageScrolling(container, "radio");
- });
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:preferences#search" }, function* (browser) {
- let doc = browser.contentDocument;
- let container = doc.getElementsByClassName("main-content")[0];
-
- // Test search
- let engineList = doc.getElementById("engineList");
- engineList.focus();
- EventUtils.synthesizeKey(" ", {});
- is(engineList.view.selection.currentIndex, 0, "Search engineList is selected");
- EventUtils.synthesizeKey(" ", {});
- yield checkPageScrolling(container, "search engineList");
- });
-
- // Test session restore
- const CRASH_URL = "about:mozilla";
- const CRASH_FAVICON = "chrome://branding/content/icon32.png";
- const CRASH_SHENTRY = {url: CRASH_URL};
- const CRASH_TAB = {entries: [CRASH_SHENTRY], image: CRASH_FAVICON};
- const CRASH_STATE = {windows: [{tabs: [CRASH_TAB]}]};
-
- const TAB_URL = "about:sessionrestore";
- const TAB_FORMDATA = {url: TAB_URL, id: {sessionData: CRASH_STATE}};
- const TAB_SHENTRY = {url: TAB_URL};
- const TAB_STATE = {entries: [TAB_SHENTRY], formdata: TAB_FORMDATA};
-
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
-
- // Fake a post-crash tab
- ss.setTabState(tab, JSON.stringify(TAB_STATE));
-
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- let doc = tab.linkedBrowser.contentDocument;
-
- // Make body scrollable
- doc.body.style.height = (doc.body.clientHeight + 100) + "px";
-
- let tabList = doc.getElementById("tabList");
- tabList.focus();
- EventUtils.synthesizeKey(" ", {});
- yield checkPageScrolling(doc.documentElement, "session restore");
-
- gBrowser.removeCurrentTab();
- finish();
-});
-
-function checkPageScrolling(container, type) {
- return new Promise(resolve => {
- setTimeout(() => {
- is(container.scrollTop, 0, "Page should not scroll when " + type + " flipped");
- resolve();
- }, 0);
- });
-}
diff --git a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul b/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul
deleted file mode 100644
index 59b644c8f..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0"?>
-<!--
- XUL Widget Test for Bug 1184989
- -->
-<page title="Bug 1184989 Test"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
-<vbox id="container" style="height: 200px; overflow: auto;">
- <vbox style="height: 500px;">
- <hbox>
- <button id="button" label="button" />
- </hbox>
-
- <hbox>
- <checkbox id="checkbox" label="checkbox" />
- </hbox>
-
- <hbox style="height: 50px;">
- <listbox id="listbox">
- <listitem id="listitem" label="listitem" />
- <listitem label="listitem" />
- </listbox>
- </hbox>
-
- <hbox>
- <radiogroup id="radiogroup">
- <radio id="radio" label="radio" />
- </radiogroup>
- </hbox>
- </vbox>
-</vbox>
-
-</page>
diff --git a/browser/components/preferences/in-content/tests/browser_bug410900.js b/browser/components/preferences/in-content/tests/browser_bug410900.js
deleted file mode 100644
index 5b100966d..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug410900.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-
-function test() {
- waitForExplicitFinish();
-
- // Setup a phony handler to ensure the app pane will be populated.
- var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
- createInstance(Ci.nsIWebHandlerApp);
- handler.name = "App pane alive test";
- handler.uriTemplate = "http://test.mozilla.org/%s";
-
- var extps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
- getService(Ci.nsIExternalProtocolService);
- var info = extps.getProtocolHandlerInfo("apppanetest");
- info.possibleApplicationHandlers.appendElement(handler, false);
-
- var hserv = Cc["@mozilla.org/uriloader/handler-service;1"].
- getService(Ci.nsIHandlerService);
- hserv.store(info);
-
- openPreferencesViaOpenPreferencesAPI("applications", null, {leaveOpen: true}).then(
- () => runTest(gBrowser.selectedBrowser.contentWindow)
- );
-}
-
-function runTest(win) {
- var rbox = win.document.getElementById("handlersView");
- ok(rbox, "handlersView is present");
-
- var items = rbox && rbox.getElementsByTagName("richlistitem");
- ok(items && items.length > 0, "App handler list populated");
-
- var handlerAdded = false;
- for (let i = 0; i < items.length; i++) {
- if (items[i].getAttribute('type') == "apppanetest")
- handlerAdded = true;
- }
- ok(handlerAdded, "apppanetest protocol handler was successfully added");
-
- gBrowser.removeCurrentTab();
- finish();
-}
diff --git a/browser/components/preferences/in-content/tests/browser_bug705422.js b/browser/components/preferences/in-content/tests/browser_bug705422.js
deleted file mode 100644
index 24732083b..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug705422.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- waitForExplicitFinish();
- // Allow all cookies, then actually set up the test
- SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 0]]}, initTest);
-}
-
-function initTest() {
- const searchTerm = "example";
- const dummyTerm = "elpmaxe";
-
- var cm = Components.classes["@mozilla.org/cookiemanager;1"]
- .getService(Components.interfaces.nsICookieManager);
-
- // delete all cookies (might be left over from other tests)
- cm.removeAll();
-
- // data for cookies
- var vals = [[searchTerm+".com", dummyTerm, dummyTerm], // match
- [searchTerm+".org", dummyTerm, dummyTerm], // match
- [dummyTerm+".com", searchTerm, dummyTerm], // match
- [dummyTerm+".edu", searchTerm+dummyTerm, dummyTerm], // match
- [dummyTerm+".net", dummyTerm, searchTerm], // match
- [dummyTerm+".org", dummyTerm, searchTerm+dummyTerm], // match
- [dummyTerm+".int", dummyTerm, dummyTerm]]; // no match
-
- // matches must correspond to above data
- const matches = 6;
-
- var ios = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
- var cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
- .getService(Components.interfaces.nsICookieService);
- var v;
- // inject cookies
- for (v in vals) {
- let [host, name, value] = vals[v];
- var cookieUri = ios.newURI("http://"+host, null, null);
- cookieSvc.setCookieString(cookieUri, null, name+"="+value+";", null);
- }
-
- // open cookie manager
- var cmd = window.openDialog("chrome://browser/content/preferences/cookies.xul",
- "Browser:Cookies", "", {});
-
- // when it has loaded, run actual tests
- cmd.addEventListener("load", function() { executeSoon(function() { runTest(cmd, searchTerm, vals.length, matches); }); }, false);
-}
-
-function isDisabled(win, expectation) {
- var disabled = win.document.getElementById("removeAllCookies").disabled;
- is(disabled, expectation, "Remove all cookies button has correct state: "+(expectation?"disabled":"enabled"));
-}
-
-function runTest(win, searchTerm, cookies, matches) {
- var cm = Components.classes["@mozilla.org/cookiemanager;1"]
- .getService(Components.interfaces.nsICookieManager);
-
-
- // number of cookies should match injected cookies
- var injectedCookies = 0,
- injectedEnumerator = cm.enumerator;
- while (injectedEnumerator.hasMoreElements()) {
- injectedCookies++;
- injectedEnumerator.getNext();
- }
- is(injectedCookies, cookies, "Number of cookies match injected cookies");
-
- // "delete all cookies" should be enabled
- isDisabled(win, false);
-
- // filter cookies and count matches
- win.gCookiesWindow.setFilter(searchTerm);
- is(win.gCookiesWindow._view.rowCount, matches, "Correct number of cookies shown after filter is applied");
-
- // "delete all cookies" should be enabled
- isDisabled(win, false);
-
-
- // select first cookie and delete
- var tree = win.document.getElementById("cookiesList");
- var deleteButton = win.document.getElementById("removeSelectedCookies");
- var rect = tree.treeBoxObject.getCoordsForCellItem(0, tree.columns[0], "cell");
- EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {}, win);
- EventUtils.synthesizeMouseAtCenter(deleteButton, {}, win);
-
- // count cookies should be matches-1
- is(win.gCookiesWindow._view.rowCount, matches-1, "Deleted selected cookie");
-
- // select two adjacent cells and delete
- EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {}, win);
- var eventObj = {};
- if (navigator.platform.indexOf("Mac") >= 0)
- eventObj.metaKey = true;
- else
- eventObj.ctrlKey = true;
- rect = tree.treeBoxObject.getCoordsForCellItem(1, tree.columns[0], "cell");
- EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, eventObj, win);
- EventUtils.synthesizeMouseAtCenter(deleteButton, {}, win);
-
- // count cookies should be matches-3
- is(win.gCookiesWindow._view.rowCount, matches-3, "Deleted selected two adjacent cookies");
-
- // "delete all cookies" should be enabled
- isDisabled(win, false);
-
- // delete all cookies and count
- var deleteAllButton = win.document.getElementById("removeAllCookies");
- EventUtils.synthesizeMouseAtCenter(deleteAllButton, {}, win);
- is(win.gCookiesWindow._view.rowCount, 0, "Deleted all matching cookies");
-
- // "delete all cookies" should be disabled
- isDisabled(win, true);
-
- // clear filter and count should be cookies-matches
- win.gCookiesWindow.setFilter("");
- is(win.gCookiesWindow._view.rowCount, cookies-matches, "Unmatched cookies remain");
-
- // "delete all cookies" should be enabled
- isDisabled(win, false);
-
- // delete all cookies and count should be 0
- EventUtils.synthesizeMouseAtCenter(deleteAllButton, {}, win);
- is(win.gCookiesWindow._view.rowCount, 0, "Deleted all cookies");
-
- // check that datastore is also at 0
- var remainingCookies = 0,
- remainingEnumerator = cm.enumerator;
- while (remainingEnumerator.hasMoreElements()) {
- remainingCookies++;
- remainingEnumerator.getNext();
- }
- is(remainingCookies, 0, "Zero cookies remain");
-
- // "delete all cookies" should be disabled
- isDisabled(win, true);
-
- // clean up
- win.close();
- finish();
-}
-
diff --git a/browser/components/preferences/in-content/tests/browser_bug731866.js b/browser/components/preferences/in-content/tests/browser_bug731866.js
deleted file mode 100644
index c1031d412..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug731866.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-
-function test() {
- waitForExplicitFinish();
- open_preferences(runTest);
-}
-
-var gElements;
-
-function checkElements(expectedPane) {
- for (let element of gElements) {
- // keyset and preferences elements fail is_element_visible checks because they are never visible.
- // special-case the drmGroup item because its visibility depends on pref + OS version
- if (element.nodeName == "keyset" ||
- element.nodeName == "preferences" ||
- element.id === "drmGroup") {
- continue;
- }
- let attributeValue = element.getAttribute("data-category");
- let suffix = " (id=" + element.id + ")";
- if (attributeValue == "pane" + expectedPane) {
- is_element_visible(element, expectedPane + " elements should be visible" + suffix);
- } else {
- is_element_hidden(element, "Elements not in " + expectedPane + " should be hidden" + suffix);
- }
- }
-}
-
-function runTest(win) {
- is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded");
-
- let tab = win.document;
- gElements = tab.getElementById("mainPrefPane").children;
-
- let panes = [
- "General", "Search", "Content", "Applications",
- "Privacy", "Security", "Sync", "Advanced",
- ];
-
- for (let pane of panes) {
- win.gotoPref("pane" + pane);
- checkElements(pane);
- }
-
- gBrowser.removeCurrentTab();
- win.close();
- finish();
-}
diff --git a/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js b/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js
deleted file mode 100644
index 21f92db8d..000000000
--- a/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-
-function test() {
- waitForExplicitFinish();
-
- let prefs = [
- "browser.cache.offline.enable",
- "browser.cache.disk.enable",
- "browser.cache.memory.enable",
- ];
-
- registerCleanupFunction(function() {
- for (let pref of prefs) {
- Services.prefs.clearUserPref(pref);
- }
- });
-
- for (let pref of prefs) {
- Services.prefs.setBoolPref(pref, false);
- }
-
- open_preferences(runTest);
-}
-
-function runTest(win) {
- is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded");
-
- let tab = win.document;
- let elements = tab.getElementById("mainPrefPane").children;
-
- // Test if advanced pane is opened correctly
- win.gotoPref("paneAdvanced");
- for (let element of elements) {
- if (element.nodeName == "preferences") {
- continue;
- }
- let attributeValue = element.getAttribute("data-category");
- if (attributeValue == "paneAdvanced") {
- is_element_visible(element, "Advanced elements should be visible");
- } else {
- is_element_hidden(element, "Non-Advanced elements should be hidden");
- }
- }
-
- gBrowser.removeCurrentTab();
- win.close();
- finish();
-}
diff --git a/browser/components/preferences/in-content/tests/browser_change_app_handler.js b/browser/components/preferences/in-content/tests/browser_change_app_handler.js
deleted file mode 100644
index f66cdfd37..000000000
--- a/browser/components/preferences/in-content/tests/browser_change_app_handler.js
+++ /dev/null
@@ -1,98 +0,0 @@
-var gMimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
-var gHandlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
-
-SimpleTest.requestCompleteLog();
-
-function setupFakeHandler() {
- let info = gMimeSvc.getFromTypeAndExtension("text/plain", "foo.txt");
- ok(info.possibleLocalHandlers.length, "Should have at least one known handler");
- let handler = info.possibleLocalHandlers.queryElementAt(0, Ci.nsILocalHandlerApp);
-
- let infoToModify = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null);
- infoToModify.possibleApplicationHandlers.appendElement(handler, false);
-
- gHandlerSvc.store(infoToModify);
-}
-
-add_task(function*() {
- setupFakeHandler();
- yield openPreferencesViaOpenPreferencesAPI("applications", null, {leaveOpen: true});
- info("Preferences page opened on the applications pane.");
- let win = gBrowser.selectedBrowser.contentWindow;
-
- let container = win.document.getElementById("handlersView");
- let ourItem = container.querySelector("richlistitem[type='text/x-test-handler']");
- ok(ourItem, "handlersView is present");
- ourItem.scrollIntoView();
- container.selectItem(ourItem);
- ok(ourItem.selected, "Should be able to select our item.");
-
- let list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu"));
- info("Got list after item was selected");
-
- let chooseItem = list.firstChild.querySelector(".choose-app-item");
- let dialogLoadedPromise = promiseLoadSubDialog("chrome://global/content/appPicker.xul");
- let cmdEvent = win.document.createEvent("xulcommandevent");
- cmdEvent.initCommandEvent("command", true, true, win, 0, false, false, false, false, null);
- chooseItem.dispatchEvent(cmdEvent);
-
- let dialog = yield dialogLoadedPromise;
- info("Dialog loaded");
-
- let dialogDoc = dialog.document;
- let dialogList = dialogDoc.getElementById("app-picker-listbox");
- dialogList.selectItem(dialogList.firstChild);
- let selectedApp = dialogList.firstChild.handlerApp;
- dialogDoc.documentElement.acceptDialog();
-
- // Verify results are correct in mime service:
- let mimeInfo = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null);
- ok(mimeInfo.preferredApplicationHandler.equals(selectedApp), "App should be set as preferred.");
-
- // Check that we display this result:
- list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu"));
- info("Got list after item was selected");
- ok(list.selectedItem, "Should have a selected item");
- ok(mimeInfo.preferredApplicationHandler.equals(list.selectedItem.handlerApp),
- "App should be visible as preferred item.");
-
-
- // Now try to 'manage' this list:
- dialogLoadedPromise = promiseLoadSubDialog("chrome://browser/content/preferences/applicationManager.xul");
-
- let manageItem = list.firstChild.querySelector(".manage-app-item");
- cmdEvent = win.document.createEvent("xulcommandevent");
- cmdEvent.initCommandEvent("command", true, true, win, 0, false, false, false, false, null);
- manageItem.dispatchEvent(cmdEvent);
-
- dialog = yield dialogLoadedPromise;
- info("Dialog loaded the second time");
-
- dialogDoc = dialog.document;
- dialogList = dialogDoc.getElementById("appList");
- let itemToRemove = dialogList.querySelector('listitem[label="' + selectedApp.name + '"]');
- dialogList.selectItem(itemToRemove);
- let itemsBefore = dialogList.children.length;
- dialogDoc.getElementById("remove").click();
- ok(!itemToRemove.parentNode, "Item got removed from DOM");
- is(dialogList.children.length, itemsBefore - 1, "Item got removed");
- dialogDoc.documentElement.acceptDialog();
-
- // Verify results are correct in mime service:
- mimeInfo = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null);
- ok(!mimeInfo.preferredApplicationHandler, "App should no longer be set as preferred.");
-
- // Check that we display this result:
- list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu"));
- ok(list.selectedItem, "Should have a selected item");
- ok(!list.selectedItem.handlerApp,
- "No app should be visible as preferred item.");
-
- gBrowser.removeCurrentTab();
-});
-
-registerCleanupFunction(function() {
- let infoToModify = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null);
- gHandlerSvc.remove(infoToModify);
-});
-
diff --git a/browser/components/preferences/in-content/tests/browser_connection.js b/browser/components/preferences/in-content/tests/browser_connection.js
deleted file mode 100644
index 50438aed1..000000000
--- a/browser/components/preferences/in-content/tests/browser_connection.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* 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/. */
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function test() {
- waitForExplicitFinish();
-
- // network.proxy.type needs to be backed up and restored because mochitest
- // changes this setting from the default
- let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type");
- registerCleanupFunction(function() {
- Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType);
- Services.prefs.clearUserPref("network.proxy.no_proxies_on");
- Services.prefs.clearUserPref("browser.preferences.instantApply");
- });
-
- let connectionURL = "chrome://browser/content/preferences/connection.xul";
-
- /*
- The connection dialog alone won't save onaccept since it uses type="child",
- so it has to be opened as a sub dialog of the main pref tab.
- Open the main tab here.
- */
- open_preferences(Task.async(function* tabOpened(aContentWindow) {
- is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded");
- let dialog = yield openAndLoadSubDialog(connectionURL);
- let dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing");
-
- ok(dialog, "connection window opened");
- runConnectionTests(dialog);
- dialog.document.documentElement.acceptDialog();
-
- let dialogClosingEvent = yield dialogClosingPromise;
- ok(dialogClosingEvent, "connection window closed");
- // runConnectionTests will have changed this pref - make sure it was
- // sanitized correctly when the dialog was accepted
- is(Services.prefs.getCharPref("network.proxy.no_proxies_on"),
- ".a.com,.b.com,.c.com", "no_proxies_on pref has correct value");
- gBrowser.removeCurrentTab();
- finish();
- }));
-}
-
-// run a bunch of tests on the window containing connection.xul
-function runConnectionTests(win) {
- let doc = win.document;
- let networkProxyNone = doc.getElementById("networkProxyNone");
- let networkProxyNonePref = doc.getElementById("network.proxy.no_proxies_on");
- let networkProxyTypePref = doc.getElementById("network.proxy.type");
-
- // make sure the networkProxyNone textbox is formatted properly
- is(networkProxyNone.getAttribute("multiline"), "true",
- "networkProxyNone textbox is multiline");
- is(networkProxyNone.getAttribute("rows"), "2",
- "networkProxyNone textbox has two rows");
-
- // check if sanitizing the given input for the no_proxies_on pref results in
- // expected string
- function testSanitize(input, expected, errorMessage) {
- networkProxyNonePref.value = input;
- win.gConnectionsDialog.sanitizeNoProxiesPref();
- is(networkProxyNonePref.value, expected, errorMessage);
- }
-
- // change this pref so proxy exceptions are actually configurable
- networkProxyTypePref.value = 1;
- is(networkProxyNone.disabled, false, "networkProxyNone textbox is enabled");
-
- testSanitize(".a.com", ".a.com",
- "sanitize doesn't mess up single filter");
- testSanitize(".a.com, .b.com, .c.com", ".a.com, .b.com, .c.com",
- "sanitize doesn't mess up multiple comma/space sep filters");
- testSanitize(".a.com\n.b.com", ".a.com,.b.com",
- "sanitize turns line break into comma");
- testSanitize(".a.com,\n.b.com", ".a.com,.b.com",
- "sanitize doesn't add duplicate comma after comma");
- testSanitize(".a.com\n,.b.com", ".a.com,.b.com",
- "sanitize doesn't add duplicate comma before comma");
- testSanitize(".a.com,\n,.b.com", ".a.com,,.b.com",
- "sanitize doesn't add duplicate comma surrounded by commas");
- testSanitize(".a.com, \n.b.com", ".a.com, .b.com",
- "sanitize doesn't add comma after comma/space");
- testSanitize(".a.com\n .b.com", ".a.com, .b.com",
- "sanitize adds comma before space");
- testSanitize(".a.com\n\n\n;;\n;\n.b.com", ".a.com,.b.com",
- "sanitize only adds one comma per substring of bad chars");
- testSanitize(".a.com,,.b.com", ".a.com,,.b.com",
- "duplicate commas from user are untouched");
- testSanitize(".a.com\n.b.com\n.c.com,\n.d.com,\n.e.com",
- ".a.com,.b.com,.c.com,.d.com,.e.com",
- "sanitize replaces things globally");
-
- // will check that this was sanitized properly after window closes
- networkProxyNonePref.value = ".a.com;.b.com\n.c.com";
-}
diff --git a/browser/components/preferences/in-content/tests/browser_connection_bug388287.js b/browser/components/preferences/in-content/tests/browser_connection_bug388287.js
deleted file mode 100644
index 5a348876e..000000000
--- a/browser/components/preferences/in-content/tests/browser_connection_bug388287.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function test() {
- waitForExplicitFinish();
- const connectionURL = "chrome://browser/content/preferences/connection.xul";
- let closeable = false;
- let finalTest = false;
-
- // The changed preferences need to be backed up and restored because this mochitest
- // changes them setting from the default
- let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type");
- registerCleanupFunction(function() {
- Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType);
- Services.prefs.clearUserPref("network.proxy.share_proxy_settings");
- for (let proxyType of ["http", "ssl", "ftp", "socks"]) {
- Services.prefs.clearUserPref("network.proxy." + proxyType);
- Services.prefs.clearUserPref("network.proxy." + proxyType + "_port");
- if (proxyType == "http") {
- continue;
- }
- Services.prefs.clearUserPref("network.proxy.backup." + proxyType);
- Services.prefs.clearUserPref("network.proxy.backup." + proxyType + "_port");
- }
- });
-
- /*
- The connection dialog alone won't save onaccept since it uses type="child",
- so it has to be opened as a sub dialog of the main pref tab.
- Open the main tab here.
- */
- open_preferences(Task.async(function* tabOpened(aContentWindow) {
- let dialog, dialogClosingPromise;
- let doc, proxyTypePref, sharePref, httpPref, httpPortPref, ftpPref, ftpPortPref;
-
- // Convenient function to reset the variables for the new window
- function* setDoc() {
- if (closeable) {
- let dialogClosingEvent = yield dialogClosingPromise;
- ok(dialogClosingEvent, "Connection dialog closed");
- }
-
- if (finalTest) {
- gBrowser.removeCurrentTab();
- finish();
- return;
- }
-
- dialog = yield openAndLoadSubDialog(connectionURL);
- dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing");
-
- doc = dialog.document;
- proxyTypePref = doc.getElementById("network.proxy.type");
- sharePref = doc.getElementById("network.proxy.share_proxy_settings");
- httpPref = doc.getElementById("network.proxy.http");
- httpPortPref = doc.getElementById("network.proxy.http_port");
- ftpPref = doc.getElementById("network.proxy.ftp");
- ftpPortPref = doc.getElementById("network.proxy.ftp_port");
- }
-
- // This batch of tests should not close the dialog
- yield setDoc();
-
- // Testing HTTP port 0 with share on
- proxyTypePref.value = 1;
- sharePref.value = true;
- httpPref.value = "localhost";
- httpPortPref.value = 0;
- doc.documentElement.acceptDialog();
-
- // Testing HTTP port 0 + FTP port 80 with share off
- sharePref.value = false;
- ftpPref.value = "localhost";
- ftpPortPref.value = 80;
- doc.documentElement.acceptDialog();
-
- // Testing HTTP port 80 + FTP port 0 with share off
- httpPortPref.value = 80;
- ftpPortPref.value = 0;
- doc.documentElement.acceptDialog();
-
- // From now on, the dialog should close since we are giving it legitimate inputs.
- // The test will timeout if the onbeforeaccept kicks in erroneously.
- closeable = true;
-
- // Both ports 80, share on
- httpPortPref.value = 80;
- ftpPortPref.value = 80;
- doc.documentElement.acceptDialog();
-
- // HTTP 80, FTP 0, with share on
- yield setDoc();
- proxyTypePref.value = 1;
- sharePref.value = true;
- ftpPref.value = "localhost";
- httpPref.value = "localhost";
- httpPortPref.value = 80;
- ftpPortPref.value = 0;
- doc.documentElement.acceptDialog();
-
- // HTTP host empty, port 0 with share on
- yield setDoc();
- proxyTypePref.value = 1;
- sharePref.value = true;
- httpPref.value = "";
- httpPortPref.value = 0;
- doc.documentElement.acceptDialog();
-
- // HTTP 0, but in no proxy mode
- yield setDoc();
- proxyTypePref.value = 0;
- sharePref.value = true;
- httpPref.value = "localhost";
- httpPortPref.value = 0;
-
- // This is the final test, don't spawn another connection window
- finalTest = true;
- doc.documentElement.acceptDialog();
- yield setDoc();
- }));
-}
diff --git a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js
deleted file mode 100644
index 89313d736..000000000
--- a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js
+++ /dev/null
@@ -1,348 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(3);
- testRunner.runTests();
-}
-
-var testRunner = {
-
- tests:
- [
- {
- test: function(params) {
- params.url.value = "test.com";
- params.btnAllow.doCommand();
- is(params.tree.view.rowCount, 1, "added exception shows up in treeview");
- is(params.tree.view.getCellText(0, params.nameCol), "http://test.com",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission text should be set correctly");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://test.com", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "test.com";
- params.btnBlock.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "http://test.com",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.denyText,
- "permission should change to deny in UI");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://test.com", data: "changed",
- capability: Ci.nsIPermissionManager.DENY_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "test.com";
- params.btnAllow.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "http://test.com",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission should revert back to allow");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://test.com", data: "changed",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "test.com";
- params.btnRemove.doCommand();
- is(params.tree.view.rowCount, 0, "exception should be removed");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://test.com", data: "deleted" }],
- },
- {
- expectPermObservancesDuringTestFunction: true,
- test: function(params) {
- let uri = params.ioService.newURI("http://test.com", null, null);
- params.pm.add(uri, "popup", Ci.nsIPermissionManager.DENY_ACTION);
- is(params.tree.view.rowCount, 0, "adding unrelated permission should not change display");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "popup", origin: "http://test.com", data: "added",
- capability: Ci.nsIPermissionManager.DENY_ACTION }],
- cleanUp: function(params) {
- let uri = params.ioService.newURI("http://test.com", null, null);
- params.pm.remove(uri, "popup");
- },
- },
- {
- test: function(params) {
- params.url.value = "https://test.com:12345";
- params.btnAllow.doCommand();
- is(params.tree.view.rowCount, 1, "added exception shows up in treeview");
- is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission text should be set correctly");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "https://test.com:12345", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "https://test.com:12345";
- params.btnBlock.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.denyText,
- "permission should change to deny in UI");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "https://test.com:12345", data: "changed",
- capability: Ci.nsIPermissionManager.DENY_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "https://test.com:12345";
- params.btnAllow.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission should revert back to allow");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "https://test.com:12345", data: "changed",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "https://test.com:12345";
- params.btnRemove.doCommand();
- is(params.tree.view.rowCount, 0, "exception should be removed");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "https://test.com:12345", data: "deleted" }],
- },
- {
- test: function(params) {
- params.url.value = "localhost:12345";
- params.btnAllow.doCommand();
- is(params.tree.view.rowCount, 1, "added exception shows up in treeview");
- is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission text should be set correctly");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://localhost:12345", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "localhost:12345";
- params.btnBlock.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.denyText,
- "permission should change to deny in UI");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://localhost:12345", data: "changed",
- capability: Ci.nsIPermissionManager.DENY_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "localhost:12345";
- params.btnAllow.doCommand();
- is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345",
- "origin name should be set correctly");
- is(params.tree.view.getCellText(0, params.statusCol), params.allowText,
- "permission should revert back to allow");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://localhost:12345", data: "changed",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- },
- {
- test: function(params) {
- params.url.value = "localhost:12345";
- params.btnRemove.doCommand();
- is(params.tree.view.rowCount, 0, "exception should be removed");
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://localhost:12345", data: "deleted" }],
- },
- {
- expectPermObservancesDuringTestFunction: true,
- test(params) {
- for (let URL of ["http://a", "http://z", "http://b"]) {
- let URI = params.ioService.newURI(URL, null, null);
- params.pm.add(URI, "cookie", Ci.nsIPermissionManager.ALLOW_ACTION);
- }
-
- is(params.tree.view.rowCount, 3, "Three permissions should be present");
- is(params.tree.view.getCellText(0, params.nameCol), "http://a",
- "site should be sorted. 'a' should be first");
- is(params.tree.view.getCellText(1, params.nameCol), "http://b",
- "site should be sorted. 'b' should be second");
- is(params.tree.view.getCellText(2, params.nameCol), "http://z",
- "site should be sorted. 'z' should be third");
-
- // Sort descending then check results in cleanup since sorting isn't synchronous.
- EventUtils.synthesizeMouseAtCenter(params.doc.getElementById("siteCol"), {},
- params.doc.defaultView);
- params.btnApplyChanges.doCommand();
- },
- observances: [{ type: "cookie", origin: "http://a", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION },
- { type: "cookie", origin: "http://z", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION },
- { type: "cookie", origin: "http://b", data: "added",
- capability: Ci.nsIPermissionManager.ALLOW_ACTION }],
- cleanUp(params) {
- is(params.tree.view.getCellText(0, params.nameCol), "http://z",
- "site should be sorted. 'z' should be first");
- is(params.tree.view.getCellText(1, params.nameCol), "http://b",
- "site should be sorted. 'b' should be second");
- is(params.tree.view.getCellText(2, params.nameCol), "http://a",
- "site should be sorted. 'a' should be third");
-
- for (let URL of ["http://a", "http://z", "http://b"]) {
- let uri = params.ioService.newURI(URL, null, null);
- params.pm.remove(uri, "cookie");
- }
- },
- },
- ],
-
- _currentTest: -1,
-
- runTests: function() {
- this._currentTest++;
-
- info("Running test #" + (this._currentTest + 1) + "\n");
- let that = this;
- let p = this.runCurrentTest(this._currentTest + 1);
- p.then(function() {
- if (that._currentTest == that.tests.length - 1) {
- finish();
- }
- else {
- that.runTests();
- }
- });
- },
-
- runCurrentTest: function(testNumber) {
- return new Promise(function(resolve, reject) {
-
- let helperFunctions = {
- windowLoad: function(win) {
- let doc = win.document;
- let params = {
- doc,
- tree: doc.getElementById("permissionsTree"),
- nameCol: doc.getElementById("permissionsTree").treeBoxObject.columns.getColumnAt(0),
- statusCol: doc.getElementById("permissionsTree").treeBoxObject.columns.getColumnAt(1),
- url: doc.getElementById("url"),
- btnAllow: doc.getElementById("btnAllow"),
- btnBlock: doc.getElementById("btnBlock"),
- btnApplyChanges: doc.getElementById("btnApplyChanges"),
- btnRemove: doc.getElementById("removePermission"),
- pm: Cc["@mozilla.org/permissionmanager;1"]
- .getService(Ci.nsIPermissionManager),
- ioService: Cc["@mozilla.org/network/io-service;1"]
- .getService(Ci.nsIIOService),
- allowText: win.gPermissionManager._getCapabilityString(
- Ci.nsIPermissionManager.ALLOW_ACTION),
- denyText: win.gPermissionManager._getCapabilityString(
- Ci.nsIPermissionManager.DENY_ACTION),
- allow: Ci.nsIPermissionManager.ALLOW_ACTION,
- deny: Ci.nsIPermissionManager.DENY_ACTION,
- };
-
- let permObserver = {
- observe: function(aSubject, aTopic, aData) {
- if (aTopic != "perm-changed")
- return;
-
- if (testRunner.tests[testRunner._currentTest].observances.length == 0) {
- // Should fail here as we are not expecting a notification, but we don't.
- // See bug 1063410.
- return;
- }
-
- let permission = aSubject.QueryInterface(Ci.nsIPermission);
- let expected = testRunner.tests[testRunner._currentTest].observances.shift();
-
- is(aData, expected.data, "type of message should be the same");
- for (let prop of ["type", "capability"]) {
- if (expected[prop])
- is(permission[prop], expected[prop],
- "property: \"" + prop + "\" should be equal");
- }
-
- if (expected.origin) {
- is(permission.principal.origin, expected.origin,
- "property: \"origin\" should be equal");
- }
-
- os.removeObserver(permObserver, "perm-changed");
-
- let test = testRunner.tests[testRunner._currentTest];
- if (!test.expectPermObservancesDuringTestFunction) {
- if (test.cleanUp) {
- test.cleanUp(params);
- }
-
- gBrowser.removeCurrentTab();
- resolve();
- }
- },
- };
-
- let os = Cc["@mozilla.org/observer-service;1"]
- .getService(Ci.nsIObserverService);
-
- os.addObserver(permObserver, "perm-changed", false);
-
- if (testRunner._currentTest == 0) {
- is(params.tree.view.rowCount, 0, "no cookie exceptions");
- }
-
- try {
- let test = testRunner.tests[testRunner._currentTest];
- test.test(params);
- if (test.expectPermObservancesDuringTestFunction) {
- if (test.cleanUp) {
- test.cleanUp(params);
- }
-
- gBrowser.removeCurrentTab();
- resolve();
- }
- } catch (ex) {
- ok(false, "exception while running test #" +
- testNumber + ": " + ex);
- }
- },
- };
-
- openPreferencesViaOpenPreferencesAPI("panePrivacy", null, {leaveOpen: true}).then(function() {
- let doc = gBrowser.contentDocument;
- let historyMode = doc.getElementById("historyMode");
- historyMode.value = "custom";
- historyMode.doCommand();
- doc.getElementById("cookieExceptions").doCommand();
-
- let subDialogURL = "chrome://browser/content/preferences/permissions.xul";
- promiseLoadSubDialog(subDialogURL).then(function(win) {
- helperFunctions.windowLoad(win);
- });
- });
- });
- },
-};
diff --git a/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js b/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js
deleted file mode 100644
index b30b6d9e2..000000000
--- a/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js
+++ /dev/null
@@ -1,103 +0,0 @@
-"use strict";
-
-const CHECK_DEFAULT_INITIAL = Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser");
-
-add_task(function* clicking_make_default_checks_alwaysCheck_checkbox() {
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences");
-
- yield test_with_mock_shellservice({isDefault: false}, function*() {
- let setDefaultPane = content.document.getElementById("setDefaultPane");
- Assert.equal(setDefaultPane.selectedIndex, "0",
- "The 'make default' pane should be visible when not default");
- let alwaysCheck = content.document.getElementById("alwaysCheckDefault");
- Assert.ok(!alwaysCheck.checked, "Always Check is unchecked by default");
- Assert.ok(!Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"),
- "alwaysCheck pref should be false by default in test runs");
-
- let setDefaultButton = content.document.getElementById("setDefaultButton");
- setDefaultButton.click();
- content.window.gMainPane.updateSetDefaultBrowser();
-
- yield ContentTaskUtils.waitForCondition(() => alwaysCheck.checked,
- "'Always Check' checkbox should get checked after clicking the 'Set Default' button");
-
- Assert.ok(alwaysCheck.checked,
- "Clicking 'Make Default' checks the 'Always Check' checkbox");
- Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"),
- "Checking the checkbox should set the pref to true");
- Assert.ok(alwaysCheck.disabled,
- "'Always Check' checkbox is locked with default browser and alwaysCheck=true");
- Assert.equal(setDefaultPane.selectedIndex, "1",
- "The 'make default' pane should not be visible when default");
- Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"),
- "checkDefaultBrowser pref is now enabled");
- });
-
- gBrowser.removeCurrentTab();
- Services.prefs.clearUserPref("browser.shell.checkDefaultBrowser");
-});
-
-add_task(function* clicking_make_default_checks_alwaysCheck_checkbox() {
- Services.prefs.lockPref("browser.shell.checkDefaultBrowser");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences");
-
- yield test_with_mock_shellservice({isDefault: false}, function*() {
- let setDefaultPane = content.document.getElementById("setDefaultPane");
- Assert.equal(setDefaultPane.selectedIndex, "0",
- "The 'make default' pane should be visible when not default");
- let alwaysCheck = content.document.getElementById("alwaysCheckDefault");
- Assert.ok(alwaysCheck.disabled, "Always Check is disabled when locked");
- Assert.ok(alwaysCheck.checked,
- "Always Check is checked because defaultPref is true and pref is locked");
- Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"),
- "alwaysCheck pref should ship with 'true' by default");
-
- let setDefaultButton = content.document.getElementById("setDefaultButton");
- setDefaultButton.click();
- content.window.gMainPane.updateSetDefaultBrowser();
-
- yield ContentTaskUtils.waitForCondition(() => setDefaultPane.selectedIndex == "1",
- "Browser is now default");
-
- Assert.ok(alwaysCheck.checked,
- "'Always Check' is still checked because it's locked");
- Assert.ok(alwaysCheck.disabled,
- "'Always Check is disabled because it's locked");
- Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"),
- "The pref is locked and so doesn't get changed");
- });
-
- Services.prefs.unlockPref("browser.shell.checkDefaultBrowser");
- gBrowser.removeCurrentTab();
-});
-
-registerCleanupFunction(function() {
- Services.prefs.unlockPref("browser.shell.checkDefaultBrowser");
- Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", CHECK_DEFAULT_INITIAL);
-});
-
-function* test_with_mock_shellservice(options, testFn) {
- yield ContentTask.spawn(gBrowser.selectedBrowser, options, function*(options) {
- let doc = content.document;
- let win = doc.defaultView;
- win.oldShellService = win.getShellService();
- let mockShellService = {
- _isDefault: false,
- isDefaultBrowser() {
- return this._isDefault;
- },
- setDefaultBrowser() {
- this._isDefault = true;
- },
- };
- win.getShellService = function() {
- return mockShellService;
- }
- mockShellService._isDefault = options.isDefault;
- win.gMainPane.updateSetDefaultBrowser();
- });
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, null, testFn);
-
- Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", CHECK_DEFAULT_INITIAL);
-}
diff --git a/browser/components/preferences/in-content/tests/browser_healthreport.js b/browser/components/preferences/in-content/tests/browser_healthreport.js
deleted file mode 100644
index bbfae9707..000000000
--- a/browser/components/preferences/in-content/tests/browser_healthreport.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
-
-function runPaneTest(fn) {
- open_preferences((win) => {
- let doc = win.document;
- win.gotoPref("paneAdvanced");
- let advancedPrefs = doc.getElementById("advancedPrefs");
- let tab = doc.getElementById("dataChoicesTab");
- advancedPrefs.selectedTab = tab;
- fn(win, doc);
- });
-}
-
-function test() {
- waitForExplicitFinish();
- resetPreferences();
- registerCleanupFunction(resetPreferences);
- runPaneTest(testBasic);
-}
-
-function testBasic(win, doc) {
- is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), true,
- "Health Report upload enabled on app first run.");
-
- let checkbox = doc.getElementById("submitHealthReportBox");
- ok(checkbox);
- is(checkbox.checked, true, "Health Report checkbox is checked on app first run.");
-
- checkbox.checked = false;
- checkbox.doCommand();
- is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), false,
- "Unchecking checkbox opts out of FHR upload.");
-
- checkbox.checked = true;
- checkbox.doCommand();
- is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), true,
- "Checking checkbox allows FHR upload.");
-
- win.close();
- Services.prefs.lockPref(FHR_UPLOAD_ENABLED);
- runPaneTest(testUploadDisabled);
-}
-
-function testUploadDisabled(win, doc) {
- ok(Services.prefs.prefIsLocked(FHR_UPLOAD_ENABLED), "Upload enabled flag is locked.");
- let checkbox = doc.getElementById("submitHealthReportBox");
- is(checkbox.getAttribute("disabled"), "true", "Checkbox is disabled if upload flag is locked.");
- Services.prefs.unlockPref(FHR_UPLOAD_ENABLED);
-
- win.close();
- finish();
-}
-
-function resetPreferences() {
- Services.prefs.clearUserPref(FHR_UPLOAD_ENABLED);
-}
-
diff --git a/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js b/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js
deleted file mode 100644
index 366454fcc..000000000
--- a/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js
+++ /dev/null
@@ -1,20 +0,0 @@
-add_task(function*() {
- is(gBrowser.currentURI.spec, "about:blank", "Test starts with about:blank open");
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home");
- yield openPreferencesViaOpenPreferencesAPI("paneGeneral", null, {leaveOpen: true});
- let doc = gBrowser.contentDocument;
- is(gBrowser.currentURI.spec, "about:preferences#general",
- "#general should be in the URI for about:preferences");
- let oldHomepagePref = Services.prefs.getCharPref("browser.startup.homepage");
-
- let useCurrent = doc.getElementById("useCurrent");
- useCurrent.click();
-
- is(gBrowser.tabs.length, 3, "Three tabs should be open");
- is(Services.prefs.getCharPref("browser.startup.homepage"), "about:blank|about:home",
- "about:blank and about:home should be the only homepages set");
-
- Services.prefs.setCharPref("browser.startup.homepage", oldHomepagePref);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
diff --git a/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js b/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js
deleted file mode 100644
index 68f9653f6..000000000
--- a/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-registerCleanupFunction(function() {
- while (gBrowser.tabs[1])
- gBrowser.removeTab(gBrowser.tabs[1]);
-});
-
-add_task(function*() {
- let prefs = yield openPreferencesViaOpenPreferencesAPI("paneContent", undefined, {leaveOpen: true});
- is(prefs.selectedPane, "paneContent", "Content pane was selected");
-
- let doc = gBrowser.contentDocument;
- let notificationsDoNotDisturbRow = doc.getElementById("notificationsDoNotDisturbRow");
- if (notificationsDoNotDisturbRow.hidden) {
- todo(false, "Do not disturb is not available on this platform");
- return;
- }
-
- let alertService;
- try {
- alertService = Cc["@mozilla.org/alerts-service;1"]
- .getService(Ci.nsIAlertsService)
- .QueryInterface(Ci.nsIAlertsDoNotDisturb);
- } catch (ex) {
- ok(true, "Do not disturb is not available on this platform: " + ex.message);
- return;
- }
-
- let checkbox = doc.getElementById("notificationsDoNotDisturb");
- ok(!checkbox.checked, "Checkbox should not be checked by default");
- ok(!alertService.manualDoNotDisturb, "Do not disturb should be off by default");
-
- let checkboxChanged = waitForEvent(checkbox, "command")
- checkbox.click();
- yield checkboxChanged;
- ok(alertService.manualDoNotDisturb, "Do not disturb should be enabled when checked");
-
- checkboxChanged = waitForEvent(checkbox, "command")
- checkbox.click();
- yield checkboxChanged;
- ok(!alertService.manualDoNotDisturb, "Do not disturb should be disabled when unchecked");
-});
diff --git a/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js b/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js
deleted file mode 100644
index d9253735a..000000000
--- a/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-const PERMISSIONS_URL = "chrome://browser/content/preferences/permissions.xul";
-
-add_task(function* urlFieldVisibleForPopupPermissions(finish) {
- yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true});
- let win = gBrowser.selectedBrowser.contentWindow;
- let doc = win.document;
- let popupPolicyCheckbox = doc.getElementById("popupPolicy");
- ok(!popupPolicyCheckbox.checked, "popupPolicyCheckbox should be unchecked by default");
- popupPolicyCheckbox.click();
- let popupPolicyButton = doc.getElementById("popupPolicyButton");
- ok(popupPolicyButton, "popupPolicyButton found");
- let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL);
- popupPolicyButton.click();
- let dialog = yield dialogPromise;
- ok(dialog, "dialog loaded");
-
- let urlLabel = dialog.document.getElementById("urlLabel");
- ok(!urlLabel.hidden, "urlLabel should be visible when one of block/session/allow visible");
- let url = dialog.document.getElementById("url");
- ok(!url.hidden, "url should be visible when one of block/session/allow visible");
-
- popupPolicyCheckbox.click();
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* urlFieldHiddenForNotificationPermissions() {
- yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true});
- let win = gBrowser.selectedBrowser.contentWindow;
- let doc = win.document;
- let notificationsPolicyButton = doc.getElementById("notificationsPolicyButton");
- ok(notificationsPolicyButton, "notificationsPolicyButton found");
- let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL);
- notificationsPolicyButton.click();
- let dialog = yield dialogPromise;
- ok(dialog, "dialog loaded");
-
- let urlLabel = dialog.document.getElementById("urlLabel");
- ok(urlLabel.hidden, "urlLabel should be hidden as requested");
- let url = dialog.document.getElementById("url");
- ok(url.hidden, "url should be hidden as requested");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_1.js b/browser/components/preferences/in-content/tests/browser_privacypane_1.js
deleted file mode 100644
index 0df60c6ac..000000000
--- a/browser/components/preferences/in-content/tests/browser_privacypane_1.js
+++ /dev/null
@@ -1,18 +0,0 @@
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-
-let rootDir = getRootDirectory(gTestPath);
-let jar = getJar(rootDir);
-if (jar) {
- let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
-}
-loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-
-run_test_subset([
- test_pane_visibility,
- test_dependent_elements,
- test_dependent_cookie_elements,
- test_dependent_clearonclose_elements,
- test_dependent_prefs,
-]);
diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_3.js b/browser/components/preferences/in-content/tests/browser_privacypane_3.js
deleted file mode 100644
index 8fe6f0825..000000000
--- a/browser/components/preferences/in-content/tests/browser_privacypane_3.js
+++ /dev/null
@@ -1,17 +0,0 @@
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-let rootDir = getRootDirectory(gTestPath);
-let jar = getJar(rootDir);
-if (jar) {
- let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
-}
-loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-
-run_test_subset([
- test_custom_retention("rememberHistory", "remember"),
- test_custom_retention("rememberHistory", "custom"),
- test_custom_retention("rememberForms", "remember"),
- test_custom_retention("rememberForms", "custom"),
- test_historymode_retention("remember", "remember"),
-]);
diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_4.js b/browser/components/preferences/in-content/tests/browser_privacypane_4.js
deleted file mode 100644
index b7ef3deda..000000000
--- a/browser/components/preferences/in-content/tests/browser_privacypane_4.js
+++ /dev/null
@@ -1,25 +0,0 @@
-requestLongerTimeout(2);
-
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-let rootDir = getRootDirectory(gTestPath);
-let jar = getJar(rootDir);
-if (jar) {
- let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
-}
-loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
-
-run_test_subset([
- test_custom_retention("acceptCookies", "remember"),
- test_custom_retention("acceptCookies", "custom"),
- test_custom_retention("acceptThirdPartyMenu", "remember", "visited"),
- test_custom_retention("acceptThirdPartyMenu", "custom", "always"),
- test_custom_retention("keepCookiesUntil", "remember", 1),
- test_custom_retention("keepCookiesUntil", "custom", 2),
- test_custom_retention("keepCookiesUntil", "custom", 0),
- test_custom_retention("alwaysClear", "remember"),
- test_custom_retention("alwaysClear", "custom"),
- test_historymode_retention("remember", "remember"),
-]);
diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_5.js b/browser/components/preferences/in-content/tests/browser_privacypane_5.js
deleted file mode 100644
index a07530010..000000000
--- a/browser/components/preferences/in-content/tests/browser_privacypane_5.js
+++ /dev/null
@@ -1,17 +0,0 @@
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-let rootDir = getRootDirectory(gTestPath);
-let jar = getJar(rootDir);
-if (jar) {
- let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
-}
-loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-
-run_test_subset([
- test_locbar_suggestion_retention("history", true),
- test_locbar_suggestion_retention("bookmark", true),
- test_locbar_suggestion_retention("openpage", false),
- test_locbar_suggestion_retention("history", true),
- test_locbar_suggestion_retention("history", false),
-]);
diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_8.js b/browser/components/preferences/in-content/tests/browser_privacypane_8.js
deleted file mode 100644
index 756b19a2f..000000000
--- a/browser/components/preferences/in-content/tests/browser_privacypane_8.js
+++ /dev/null
@@ -1,26 +0,0 @@
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-let rootDir = getRootDirectory(gTestPath);
-let jar = getJar(rootDir);
-if (jar) {
- let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
-}
-loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-
-run_test_subset([
- // history mode should be initialized to remember
- test_historymode_retention("remember", undefined),
-
- // history mode should remain remember; toggle acceptCookies checkbox
- test_custom_retention("acceptCookies", "remember"),
-
- // history mode should now be custom; set history mode to dontremember
- test_historymode_retention("dontremember", "custom"),
-
- // history mode should remain custom; set history mode to remember
- test_historymode_retention("remember", "custom"),
-
- // history mode should now be remember
- test_historymode_retention("remember", "remember"),
-]);
diff --git a/browser/components/preferences/in-content/tests/browser_proxy_backup.js b/browser/components/preferences/in-content/tests/browser_proxy_backup.js
deleted file mode 100644
index 3ad24c7ec..000000000
--- a/browser/components/preferences/in-content/tests/browser_proxy_backup.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* 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/. */
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function test() {
- waitForExplicitFinish();
-
- // network.proxy.type needs to be backed up and restored because mochitest
- // changes this setting from the default
- let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type");
- registerCleanupFunction(function() {
- Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType);
- Services.prefs.clearUserPref("browser.preferences.instantApply");
- Services.prefs.clearUserPref("network.proxy.share_proxy_settings");
- for (let proxyType of ["http", "ssl", "ftp", "socks"]) {
- Services.prefs.clearUserPref("network.proxy." + proxyType);
- Services.prefs.clearUserPref("network.proxy." + proxyType + "_port");
- if (proxyType == "http") {
- continue;
- }
- Services.prefs.clearUserPref("network.proxy.backup." + proxyType);
- Services.prefs.clearUserPref("network.proxy.backup." + proxyType + "_port");
- }
- });
-
- let connectionURL = "chrome://browser/content/preferences/connection.xul";
-
- // Set a shared proxy and a SOCKS backup
- Services.prefs.setIntPref("network.proxy.type", 1);
- Services.prefs.setBoolPref("network.proxy.share_proxy_settings", true);
- Services.prefs.setCharPref("network.proxy.http", "example.com");
- Services.prefs.setIntPref("network.proxy.http_port", 1200);
- Services.prefs.setCharPref("network.proxy.socks", "example.com");
- Services.prefs.setIntPref("network.proxy.socks_port", 1200);
- Services.prefs.setCharPref("network.proxy.backup.socks", "127.0.0.1");
- Services.prefs.setIntPref("network.proxy.backup.socks_port", 9050);
-
- /*
- The connection dialog alone won't save onaccept since it uses type="child",
- so it has to be opened as a sub dialog of the main pref tab.
- Open the main tab here.
- */
- open_preferences(Task.async(function* tabOpened(aContentWindow) {
- is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded");
- let dialog = yield openAndLoadSubDialog(connectionURL);
- let dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing");
-
- ok(dialog, "connection window opened");
- dialog.document.documentElement.acceptDialog();
-
- let dialogClosingEvent = yield dialogClosingPromise;
- ok(dialogClosingEvent, "connection window closed");
-
- // The SOCKS backup should not be replaced by the shared value
- is(Services.prefs.getCharPref("network.proxy.backup.socks"), "127.0.0.1", "Shared proxy backup shouldn't be replaced");
- is(Services.prefs.getIntPref("network.proxy.backup.socks_port"), 9050, "Shared proxy port backup shouldn't be replaced");
-
- gBrowser.removeCurrentTab();
- finish();
- }));
-}
diff --git a/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js b/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js
deleted file mode 100644
index 6b587e036..000000000
--- a/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js
+++ /dev/null
@@ -1,37 +0,0 @@
-"use strict";
-
-function switchToCustomHistoryMode(doc) {
- // Select the last item in the menulist.
- let menulist = doc.getElementById("historyMode");
- menulist.focus();
- EventUtils.sendKey("UP");
-}
-
-function testPrefStateMatchesLockedState() {
- let win = gBrowser.contentWindow;
- let doc = win.document;
- switchToCustomHistoryMode(doc);
-
- let checkbox = doc.getElementById("alwaysClear");
- let preference = doc.getElementById("privacy.sanitize.sanitizeOnShutdown");
- is(checkbox.disabled, preference.locked, "Always Clear checkbox should be enabled when preference is not locked.");
-
- gBrowser.removeCurrentTab();
-}
-
-add_task(function setup() {
- registerCleanupFunction(function resetPreferences() {
- Services.prefs.unlockPref("privacy.sanitize.sanitizeOnShutdown");
- });
-});
-
-add_task(function* test_preference_enabled_when_unlocked() {
- yield openPreferencesViaOpenPreferencesAPI("panePrivacy", undefined, {leaveOpen: true});
- testPrefStateMatchesLockedState();
-});
-
-add_task(function* test_preference_disabled_when_locked() {
- Services.prefs.lockPref("privacy.sanitize.sanitizeOnShutdown");
- yield openPreferencesViaOpenPreferencesAPI("panePrivacy", undefined, {leaveOpen: true});
- testPrefStateMatchesLockedState();
-});
diff --git a/browser/components/preferences/in-content/tests/browser_searchsuggestions.js b/browser/components/preferences/in-content/tests/browser_searchsuggestions.js
deleted file mode 100644
index 0185a23b9..000000000
--- a/browser/components/preferences/in-content/tests/browser_searchsuggestions.js
+++ /dev/null
@@ -1,43 +0,0 @@
-var original = Services.prefs.getBoolPref("browser.search.suggest.enabled");
-
-registerCleanupFunction(() => {
- Services.prefs.setBoolPref("browser.search.suggest.enabled", original);
-});
-
-// Open with suggestions enabled
-add_task(function*() {
- Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
-
- yield openPreferencesViaOpenPreferencesAPI("search", undefined, { leaveOpen: true });
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let urlbarBox = doc.getElementById("urlBarSuggestion");
- ok(!urlbarBox.disabled, "Checkbox should be enabled");
-
- Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
-
- ok(urlbarBox.disabled, "Checkbox should be disabled");
-
- gBrowser.removeCurrentTab();
-});
-
-// Open with suggestions disabled
-add_task(function*() {
- Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
-
- yield openPreferencesViaOpenPreferencesAPI("search", undefined, { leaveOpen: true });
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let urlbarBox = doc.getElementById("urlBarSuggestion");
- ok(urlbarBox.disabled, "Checkbox should be disabled");
-
- Services.prefs.setBoolPref("browser.search.suggest.enabled", true);
-
- ok(!urlbarBox.disabled, "Checkbox should be enabled");
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function*() {
- Services.prefs.setBoolPref("browser.search.suggest.enabled", original);
-});
diff --git a/browser/components/preferences/in-content/tests/browser_security.js b/browser/components/preferences/in-content/tests/browser_security.js
deleted file mode 100644
index e6eb2a91d..000000000
--- a/browser/components/preferences/in-content/tests/browser_security.js
+++ /dev/null
@@ -1,130 +0,0 @@
-const PREFS = [
- "browser.safebrowsing.phishing.enabled",
- "browser.safebrowsing.malware.enabled",
-
- "browser.safebrowsing.downloads.enabled",
-
- "browser.safebrowsing.downloads.remote.block_potentially_unwanted",
- "browser.safebrowsing.downloads.remote.block_uncommon"
-];
-
-let originals = PREFS.map(pref => [pref, Services.prefs.getBoolPref(pref)])
-let originalMalwareTable = Services.prefs.getCharPref("urlclassifier.malwareTable");
-registerCleanupFunction(function() {
- originals.forEach(([pref, val]) => Services.prefs.setBoolPref(pref, val))
- Services.prefs.setCharPref("urlclassifier.malwareTable", originalMalwareTable);
-});
-
-// test the safebrowsing preference
-add_task(function*() {
- function* checkPrefSwitch(val1, val2) {
- Services.prefs.setBoolPref("browser.safebrowsing.phishing.enabled", val1);
- Services.prefs.setBoolPref("browser.safebrowsing.malware.enabled", val2);
-
- yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true });
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let checkbox = doc.getElementById("enableSafeBrowsing");
- let blockDownloads = doc.getElementById("blockDownloads");
- let blockUncommon = doc.getElementById("blockUncommonUnwanted");
- let checked = checkbox.checked;
- is(checked, val1 && val2, "safebrowsing preference is initialized correctly");
- // should be disabled when checked is false (= pref is turned off)
- is(blockDownloads.hasAttribute("disabled"), !checked, "block downloads checkbox is set correctly");
- is(blockUncommon.hasAttribute("disabled"), !checked, "block uncommon checkbox is set correctly");
-
- // click the checkbox
- EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow);
-
- // check that both settings are now turned on or off
- is(Services.prefs.getBoolPref("browser.safebrowsing.phishing.enabled"), !checked,
- "safebrowsing.enabled is set correctly");
- is(Services.prefs.getBoolPref("browser.safebrowsing.malware.enabled"), !checked,
- "safebrowsing.malware.enabled is set correctly");
-
- // check if the other checkboxes have updated
- checked = checkbox.checked;
- is(blockDownloads.hasAttribute("disabled"), !checked, "block downloads checkbox is set correctly");
- is(blockUncommon.hasAttribute("disabled"), !checked || !blockDownloads.checked, "block uncommon checkbox is set correctly");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
-
- yield checkPrefSwitch(true, true);
- yield checkPrefSwitch(false, true);
- yield checkPrefSwitch(true, false);
- yield checkPrefSwitch(false, false);
-});
-
-// test the download protection preference
-add_task(function*() {
- function* checkPrefSwitch(val) {
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.enabled", val);
-
- yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true });
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let checkbox = doc.getElementById("blockDownloads");
- let blockUncommon = doc.getElementById("blockUncommonUnwanted");
- let checked = checkbox.checked;
- is(checked, val, "downloads preference is initialized correctly");
- // should be disabled when val is false (= pref is turned off)
- is(blockUncommon.hasAttribute("disabled"), !val, "block uncommon checkbox is set correctly");
-
- // click the checkbox
- EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow);
-
- // check that setting is now turned on or off
- is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.enabled"), !checked,
- "safebrowsing.downloads preference is set correctly");
-
- // check if the uncommon warning checkbox has updated
- is(blockUncommon.hasAttribute("disabled"), val, "block uncommon checkbox is set correctly");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
-
- yield checkPrefSwitch(true);
- yield checkPrefSwitch(false);
-});
-
-// test the unwanted/uncommon software warning preference
-add_task(function*() {
- function* checkPrefSwitch(val1, val2) {
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", val1);
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.remote.block_uncommon", val2);
-
- yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true });
-
- let doc = gBrowser.selectedBrowser.contentDocument;
- let checkbox = doc.getElementById("blockUncommonUnwanted");
- let checked = checkbox.checked;
- is(checked, val1 && val2, "unwanted/uncommon preference is initialized correctly");
-
- // click the checkbox
- EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow);
-
- // check that both settings are now turned on or off
- is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.remote.block_potentially_unwanted"), !checked,
- "block_potentially_unwanted is set correctly");
- is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.remote.block_uncommon"), !checked,
- "block_uncommon is set correctly");
-
- // when the preference is on, the malware table should include these ids
- let malwareTable = Services.prefs.getCharPref("urlclassifier.malwareTable").split(",");
- is(malwareTable.includes("goog-unwanted-shavar"), !checked,
- "malware table doesn't include goog-unwanted-shavar");
- is(malwareTable.includes("test-unwanted-simple"), !checked,
- "malware table doesn't include test-unwanted-simple");
- let sortedMalware = malwareTable.slice(0);
- sortedMalware.sort();
- Assert.deepEqual(malwareTable, sortedMalware, "malware table has been sorted");
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- }
-
- yield* checkPrefSwitch(true, true);
- yield* checkPrefSwitch(false, true);
- yield* checkPrefSwitch(true, false);
- yield* checkPrefSwitch(false, false);
-});
diff --git a/browser/components/preferences/in-content/tests/browser_subdialogs.js b/browser/components/preferences/in-content/tests/browser_subdialogs.js
deleted file mode 100644
index ff0c1f8ae..000000000
--- a/browser/components/preferences/in-content/tests/browser_subdialogs.js
+++ /dev/null
@@ -1,293 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Tests for the sub-dialog infrastructure, not for actual sub-dialog functionality.
- */
-
-const gDialogURL = getRootDirectory(gTestPath) + "subdialog.xul";
-const gDialogURL2 = getRootDirectory(gTestPath) + "subdialog2.xul";
-
-function* open_subdialog_and_test_generic_start_state(browser, domcontentloadedFn, url = gDialogURL) {
- let domcontentloadedFnStr = domcontentloadedFn ?
- "(" + domcontentloadedFn.toString() + ")()" :
- "";
- return ContentTask.spawn(browser, {url, domcontentloadedFnStr}, function*(args) {
- let {url, domcontentloadedFnStr} = args;
- let rv = { acceptCount: 0 };
- let win = content.window;
- let subdialog = win.gSubDialog;
- subdialog.open(url, null, rv);
-
- info("waiting for subdialog DOMFrameContentLoaded");
- yield ContentTaskUtils.waitForEvent(win, "DOMFrameContentLoaded", true);
- let result;
- if (domcontentloadedFnStr) {
- result = eval(domcontentloadedFnStr);
- }
-
- info("waiting for subdialog load");
- yield ContentTaskUtils.waitForEvent(subdialog._frame, "load");
- info("subdialog window is loaded");
-
- let expectedStyleSheetURLs = subdialog._injectedStyleSheets.slice(0);
- for (let styleSheet of subdialog._frame.contentDocument.styleSheets) {
- let index = expectedStyleSheetURLs.indexOf(styleSheet.href);
- if (index >= 0) {
- expectedStyleSheetURLs.splice(index, 1);
- }
- }
-
- Assert.ok(!!subdialog._frame.contentWindow, "The dialog should be non-null");
- Assert.notEqual(subdialog._frame.contentWindow.location.toString(), "about:blank",
- "Subdialog URL should not be about:blank");
- Assert.equal(win.getComputedStyle(subdialog._overlay, "").visibility, "visible",
- "Overlay should be visible");
- Assert.equal(expectedStyleSheetURLs.length, 0,
- "No stylesheets that were expected are missing");
- return result;
- });
-}
-
-function* close_subdialog_and_test_generic_end_state(browser, closingFn, closingButton, acceptCount, options) {
- let dialogclosingPromise = ContentTask.spawn(browser, {closingButton, acceptCount}, function*(expectations) {
- let win = content.window;
- let subdialog = win.gSubDialog;
- let frame = subdialog._frame;
- info("waiting for dialogclosing");
- let closingEvent =
- yield ContentTaskUtils.waitForEvent(frame.contentWindow, "dialogclosing");
- let closingButton = closingEvent.detail.button;
- let actualAcceptCount = frame.contentWindow.arguments &&
- frame.contentWindow.arguments[0].acceptCount;
-
- info("waiting for about:blank load");
- yield ContentTaskUtils.waitForEvent(frame, "load");
-
- Assert.notEqual(win.getComputedStyle(subdialog._overlay, "").visibility, "visible",
- "overlay is not visible");
- Assert.equal(frame.getAttribute("style"), "", "inline styles should be cleared");
- Assert.equal(frame.contentWindow.location.href.toString(), "about:blank",
- "sub-dialog should be unloaded");
- Assert.equal(closingButton, expectations.closingButton,
- "closing event should indicate button was '" + expectations.closingButton + "'");
- Assert.equal(actualAcceptCount, expectations.acceptCount,
- "should be 1 if accepted, 0 if canceled, undefined if closed w/out button");
- });
-
- if (options && options.runClosingFnOutsideOfContentTask) {
- yield closingFn();
- } else {
- ContentTask.spawn(browser, null, closingFn);
- }
-
- yield dialogclosingPromise;
-}
-
-let tab;
-
-add_task(function* test_initialize() {
- tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences");
-});
-
-add_task(function* check_titlebar_focus_returnval_titlechanges_accepting() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- let domtitlechangedPromise = BrowserTestUtils.waitForEvent(tab.linkedBrowser, "DOMTitleChanged");
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- let dialog = content.window.gSubDialog._frame.contentWindow;
- let dialogTitleElement = content.document.getElementById("dialogTitle");
- Assert.equal(dialogTitleElement.textContent, "Sample sub-dialog",
- "Title should be correct initially");
- Assert.equal(dialog.document.activeElement.value, "Default text",
- "Textbox with correct text is focused");
- dialog.document.title = "Updated title";
- });
-
- info("waiting for DOMTitleChanged event");
- yield domtitlechangedPromise;
-
- ContentTask.spawn(tab.linkedBrowser, null, function*() {
- let dialogTitleElement = content.document.getElementById("dialogTitle");
- Assert.equal(dialogTitleElement.textContent, "Updated title",
- "subdialog should have updated title");
- });
-
- // Accept the dialog
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); },
- "accept", 1);
-});
-
-add_task(function* check_canceling_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentDocument.documentElement.cancelDialog(); },
- "cancel", 0);
-});
-
-add_task(function* check_reopening_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
- info("opening another dialog which will close the first");
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, "", gDialogURL2);
- info("closing as normal");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); },
- "accept", 1);
-});
-
-add_task(function* check_opening_while_closing() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
- info("closing");
- content.window.gSubDialog.close();
- info("reopening immediately after calling .close()");
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); },
- "accept", 1);
-
-});
-
-add_task(function* window_close_on_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
- null, 0);
-});
-
-add_task(function* click_close_button_on_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { return BrowserTestUtils.synthesizeMouseAtCenter("#dialogClose", {}, tab.linkedBrowser); },
- null, 0, {runClosingFnOutsideOfContentTask: true});
-});
-
-add_task(function* back_navigation_on_subdialog_should_close_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.goBack(); },
- null, undefined);
-});
-
-add_task(function* back_navigation_on_browser_tab_should_close_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { tab.linkedBrowser.goBack(); },
- null, undefined, {runClosingFnOutsideOfContentTask: true});
-});
-
-add_task(function* escape_should_close_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- info("canceling the dialog");
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { return BrowserTestUtils.synthesizeKey("VK_ESCAPE", {}, tab.linkedBrowser); },
- "cancel", 0, {runClosingFnOutsideOfContentTask: true});
-});
-
-add_task(function* correct_width_and_height_should_be_used_for_dialog() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- let frameStyle = content.window.gSubDialog._frame.style;
- Assert.equal(frameStyle.width, "32em",
- "Width should be set on the frame from the dialog");
- Assert.equal(frameStyle.height, "5em",
- "Height should be set on the frame from the dialog");
- });
-
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
- null, 0);
-});
-
-add_task(function* wrapped_text_in_dialog_should_have_expected_scrollHeight() {
- let oldHeight = yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() {
- let frame = content.window.gSubDialog._frame;
- let doc = frame.contentDocument;
- let oldHeight = doc.documentElement.scrollHeight;
- doc.documentElement.style.removeProperty("height");
- doc.getElementById("desc").textContent = `
- Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
- laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
- architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
- sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione
- laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
- architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
- sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione
- laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
- architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
- sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione
- voluptatem sequi nesciunt.`
- return oldHeight;
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, oldHeight, function*(oldHeight) {
- let frame = content.window.gSubDialog._frame;
- let docEl = frame.contentDocument.documentElement;
- Assert.equal(frame.style.width, "32em",
- "Width should be set on the frame from the dialog");
- Assert.ok(docEl.scrollHeight > oldHeight,
- "Content height increased (from " + oldHeight + " to " + docEl.scrollHeight + ").");
- Assert.equal(frame.style.height, docEl.scrollHeight + "px",
- "Height on the frame should be higher now");
- });
-
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
- null, 0);
-});
-
-add_task(function* dialog_too_tall_should_get_reduced_in_height() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() {
- let frame = content.window.gSubDialog._frame;
- frame.contentDocument.documentElement.style.height = '100000px';
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- let frame = content.window.gSubDialog._frame;
- Assert.equal(frame.style.width, "32em", "Width should be set on the frame from the dialog");
- Assert.ok(parseInt(frame.style.height, 10) < content.window.innerHeight,
- "Height on the frame should be smaller than window's innerHeight");
- });
-
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
- null, 0);
-});
-
-add_task(function* scrollWidth_and_scrollHeight_from_subdialog_should_size_the_browser() {
- yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() {
- let frame = content.window.gSubDialog._frame;
- frame.contentDocument.documentElement.style.removeProperty("height");
- frame.contentDocument.documentElement.style.removeProperty("width");
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
- let frame = content.window.gSubDialog._frame;
- Assert.ok(frame.style.width.endsWith("px"),
- "Width (" + frame.style.width + ") should be set to a px value of the scrollWidth from the dialog");
- Assert.ok(frame.style.height.endsWith("px"),
- "Height (" + frame.style.height + ") should be set to a px value of the scrollHeight from the dialog");
- });
-
- yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
- function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
- null, 0);
-});
-
-add_task(function* test_shutdown() {
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/preferences/in-content/tests/browser_telemetry.js b/browser/components/preferences/in-content/tests/browser_telemetry.js
deleted file mode 100644
index d8139d87a..000000000
--- a/browser/components/preferences/in-content/tests/browser_telemetry.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const PREF_TELEMETRY_ENABLED = "toolkit.telemetry.enabled";
-
-function runPaneTest(fn) {
- open_preferences((win) => {
- let doc = win.document;
- win.gotoPref("paneAdvanced");
- let advancedPrefs = doc.getElementById("advancedPrefs");
- let tab = doc.getElementById("dataChoicesTab");
- advancedPrefs.selectedTab = tab;
- fn(win, doc);
- });
-}
-
-function test() {
- waitForExplicitFinish();
- resetPreferences();
- registerCleanupFunction(resetPreferences);
- runPaneTest(testTelemetryState);
-}
-
-function testTelemetryState(win, doc) {
- let fhrCheckbox = doc.getElementById("submitHealthReportBox");
- Assert.ok(fhrCheckbox.checked, "Health Report checkbox is checked on app first run.");
-
- let telmetryCheckbox = doc.getElementById("submitTelemetryBox");
- Assert.ok(!telmetryCheckbox.disabled,
- "Telemetry checkbox must be enabled if FHR is checked.");
- Assert.ok(Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED),
- "Telemetry must be enabled if the checkbox is ticked.");
-
- // Uncheck the FHR checkbox and make sure that Telemetry checkbox gets disabled.
- fhrCheckbox.click();
-
- Assert.ok(telmetryCheckbox.disabled,
- "Telemetry checkbox must be disabled if FHR is unchecked.");
- Assert.ok(!Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED),
- "Telemetry must be disabled if the checkbox is unticked.");
-
- win.close();
- finish();
-}
-
-function resetPreferences() {
- Services.prefs.clearUserPref("datareporting.healthreport.uploadEnabled");
- Services.prefs.clearUserPref(PREF_TELEMETRY_ENABLED);
-}
-
diff --git a/browser/components/preferences/in-content/tests/head.js b/browser/components/preferences/in-content/tests/head.js
deleted file mode 100644
index 0ed811e94..000000000
--- a/browser/components/preferences/in-content/tests/head.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/Promise.jsm");
-
-const kDefaultWait = 2000;
-
-function is_hidden(aElement) {
- var style = aElement.ownerGlobal.getComputedStyle(aElement);
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
-
- // Hiding a parent element will hide all its children
- if (aElement.parentNode != aElement.ownerDocument)
- return is_hidden(aElement.parentNode);
-
- return false;
-}
-
-function is_element_visible(aElement, aMsg) {
- isnot(aElement, null, "Element should not be null, when checking visibility");
- ok(!is_hidden(aElement), aMsg);
-}
-
-function is_element_hidden(aElement, aMsg) {
- isnot(aElement, null, "Element should not be null, when checking visibility");
- ok(is_hidden(aElement), aMsg);
-}
-
-function open_preferences(aCallback) {
- gBrowser.selectedTab = gBrowser.addTab("about:preferences");
- let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
- newTabBrowser.addEventListener("Initialized", function () {
- newTabBrowser.removeEventListener("Initialized", arguments.callee, true);
- aCallback(gBrowser.contentWindow);
- }, true);
-}
-
-function openAndLoadSubDialog(aURL, aFeatures = null, aParams = null, aClosingCallback = null) {
- let promise = promiseLoadSubDialog(aURL);
- content.gSubDialog.open(aURL, aFeatures, aParams, aClosingCallback);
- return promise;
-}
-
-function promiseLoadSubDialog(aURL) {
- return new Promise((resolve, reject) => {
- content.gSubDialog._frame.addEventListener("load", function load(aEvent) {
- if (aEvent.target.contentWindow.location == "about:blank")
- return;
- content.gSubDialog._frame.removeEventListener("load", load);
-
- is(content.gSubDialog._frame.contentWindow.location.toString(), aURL,
- "Check the proper URL is loaded");
-
- // Check visibility
- is_element_visible(content.gSubDialog._overlay, "Overlay is visible");
-
- // Check that stylesheets were injected
- let expectedStyleSheetURLs = content.gSubDialog._injectedStyleSheets.slice(0);
- for (let styleSheet of content.gSubDialog._frame.contentDocument.styleSheets) {
- let i = expectedStyleSheetURLs.indexOf(styleSheet.href);
- if (i >= 0) {
- info("found " + styleSheet.href);
- expectedStyleSheetURLs.splice(i, 1);
- }
- }
- is(expectedStyleSheetURLs.length, 0, "All expectedStyleSheetURLs should have been found");
-
- resolve(content.gSubDialog._frame.contentWindow);
- });
- });
-}
-
-/**
- * Waits a specified number of miliseconds for a specified event to be
- * fired on a specified element.
- *
- * Usage:
- * let receivedEvent = waitForEvent(element, "eventName");
- * // Do some processing here that will cause the event to be fired
- * // ...
- * // Now yield until the Promise is fulfilled
- * yield receivedEvent;
- * if (receivedEvent && !(receivedEvent instanceof Error)) {
- * receivedEvent.msg == "eventName";
- * // ...
- * }
- *
- * @param aSubject the element that should receive the event
- * @param aEventName the event to wait for
- * @param aTimeoutMs the number of miliseconds to wait before giving up
- * @returns a Promise that resolves to the received event, or to an Error
- */
-function waitForEvent(aSubject, aEventName, aTimeoutMs, aTarget) {
- let eventDeferred = Promise.defer();
- let timeoutMs = aTimeoutMs || kDefaultWait;
- let stack = new Error().stack;
- let timerID = setTimeout(function wfe_canceller() {
- aSubject.removeEventListener(aEventName, listener);
- eventDeferred.reject(new Error(aEventName + " event timeout at " + stack));
- }, timeoutMs);
-
- var listener = function (aEvent) {
- if (aTarget && aTarget !== aEvent.target)
- return;
-
- // stop the timeout clock and resume
- clearTimeout(timerID);
- eventDeferred.resolve(aEvent);
- };
-
- function cleanup(aEventOrError) {
- // unhook listener in case of success or failure
- aSubject.removeEventListener(aEventName, listener);
- return aEventOrError;
- }
- aSubject.addEventListener(aEventName, listener, false);
- return eventDeferred.promise.then(cleanup, cleanup);
-}
-
-function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) {
- let deferred = Promise.defer();
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- openPreferences(aPane, aAdvancedTab ? {advancedTab: aAdvancedTab} : undefined);
- let newTabBrowser = gBrowser.selectedBrowser;
-
- newTabBrowser.addEventListener("Initialized", function PrefInit() {
- newTabBrowser.removeEventListener("Initialized", PrefInit, true);
- newTabBrowser.contentWindow.addEventListener("load", function prefLoad() {
- newTabBrowser.contentWindow.removeEventListener("load", prefLoad);
- let win = gBrowser.contentWindow;
- let selectedPane = win.history.state;
- let doc = win.document;
- let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id;
- if (!aOptions || !aOptions.leaveOpen)
- gBrowser.removeCurrentTab();
- deferred.resolve({selectedPane: selectedPane, selectedAdvancedTab: selectedAdvancedTab});
- });
- }, true);
-
- return deferred.promise;
-}
-
-function waitForCondition(aConditionFn, aMaxTries=50, aCheckInterval=100) {
- return new Promise((resolve, reject) => {
- function tryNow() {
- tries++;
- let rv = aConditionFn();
- if (rv) {
- resolve(rv);
- } else if (tries < aMaxTries) {
- tryAgain();
- } else {
- reject("Condition timed out: " + aConditionFn.toSource());
- }
- }
- function tryAgain() {
- setTimeout(tryNow, aCheckInterval);
- }
- let tries = 0;
- tryAgain();
- });
-}
diff --git a/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js b/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js
deleted file mode 100644
index 53c6d7d8a..000000000
--- a/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js
+++ /dev/null
@@ -1,330 +0,0 @@
-function* runTestOnPrivacyPrefPane(testFunc) {
- info("runTestOnPrivacyPrefPane entered");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences", true, true);
- let browser = tab.linkedBrowser;
- info("loaded about:preferences");
- browser.contentWindow.gotoPref("panePrivacy");
- info("viewing privacy pane, executing testFunc");
- testFunc(browser.contentWindow);
- yield BrowserTestUtils.removeTab(tab);
-}
-
-function controlChanged(element) {
- element.doCommand();
-}
-
-// We can only test the panes that don't trigger a preference update
-function test_pane_visibility(win) {
- let modes = {
- "remember": "historyRememberPane",
- "custom": "historyCustomPane"
- };
-
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
- let historypane = win.document.getElementById("historyPane");
- ok(historypane, "history mode pane should exist");
-
- for (let mode in modes) {
- historymode.value = mode;
- controlChanged(historymode);
- is(historypane.selectedPanel, win.document.getElementById(modes[mode]),
- "The correct pane should be selected for the " + mode + " mode");
- is_element_visible(historypane.selectedPanel,
- "Correct pane should be visible for the " + mode + " mode");
- }
-}
-
-function test_dependent_elements(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
- let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
- ok(pbautostart, "the private browsing auto-start checkbox should exist");
- let controls = [
- win.document.getElementById("rememberHistory"),
- win.document.getElementById("rememberForms"),
- win.document.getElementById("keepUntil"),
- win.document.getElementById("keepCookiesUntil"),
- win.document.getElementById("alwaysClear"),
- ];
- controls.forEach(function(control) {
- ok(control, "the dependent controls should exist");
- });
- let independents = [
- win.document.getElementById("acceptCookies"),
- win.document.getElementById("acceptThirdPartyLabel"),
- win.document.getElementById("acceptThirdPartyMenu")
- ];
- independents.forEach(function(control) {
- ok(control, "the independent controls should exist");
- });
- let cookieexceptions = win.document.getElementById("cookieExceptions");
- ok(cookieexceptions, "the cookie exceptions button should exist");
- let keepuntil = win.document.getElementById("keepCookiesUntil");
- ok(keepuntil, "the keep cookies until menulist should exist");
- let alwaysclear = win.document.getElementById("alwaysClear");
- ok(alwaysclear, "the clear data on close checkbox should exist");
- let rememberhistory = win.document.getElementById("rememberHistory");
- ok(rememberhistory, "the remember history checkbox should exist");
- let rememberforms = win.document.getElementById("rememberForms");
- ok(rememberforms, "the remember forms checkbox should exist");
- let alwaysclearsettings = win.document.getElementById("clearDataSettings");
- ok(alwaysclearsettings, "the clear data settings button should exist");
-
- function expect_disabled(disabled) {
- controls.forEach(function(control) {
- is(control.disabled, disabled,
- control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
- });
- is(keepuntil.value, disabled ? 2 : 0,
- "the keep cookies until menulist value should be as expected");
- if (disabled) {
- ok(!alwaysclear.checked,
- "the clear data on close checkbox value should be as expected");
- ok(!rememberhistory.checked,
- "the remember history checkbox value should be as expected");
- ok(!rememberforms.checked,
- "the remember forms checkbox value should be as expected");
- }
- }
- function check_independents(expected) {
- independents.forEach(function(control) {
- is(control.disabled, expected,
- control.getAttribute("id") + " should " + (expected ? "" : "not ") + "be disabled");
- });
-
- ok(!cookieexceptions.disabled,
- "the cookie exceptions button should never be disabled");
- ok(alwaysclearsettings.disabled,
- "the clear data settings button should always be disabled");
- }
-
- // controls should only change in custom mode
- historymode.value = "remember";
- controlChanged(historymode);
- expect_disabled(false);
- check_independents(false);
-
- // setting the mode to custom shouldn't change anything
- historymode.value = "custom";
- controlChanged(historymode);
- expect_disabled(false);
- check_independents(false);
-}
-
-function test_dependent_cookie_elements(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
- let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
- ok(pbautostart, "the private browsing auto-start checkbox should exist");
- let controls = [
- win.document.getElementById("acceptThirdPartyLabel"),
- win.document.getElementById("acceptThirdPartyMenu"),
- win.document.getElementById("keepUntil"),
- win.document.getElementById("keepCookiesUntil"),
- ];
- controls.forEach(function(control) {
- ok(control, "the dependent cookie controls should exist");
- });
- let acceptcookies = win.document.getElementById("acceptCookies");
- ok(acceptcookies, "the accept cookies checkbox should exist");
-
- function expect_disabled(disabled) {
- controls.forEach(function(control) {
- is(control.disabled, disabled,
- control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
- });
- }
-
- historymode.value = "custom";
- controlChanged(historymode);
- pbautostart.checked = false;
- controlChanged(pbautostart);
- expect_disabled(false);
-
- acceptcookies.checked = false;
- controlChanged(acceptcookies);
- expect_disabled(true);
-
- acceptcookies.checked = true;
- controlChanged(acceptcookies);
- expect_disabled(false);
-
- let accessthirdparty = controls.shift();
- acceptcookies.checked = false;
- controlChanged(acceptcookies);
- expect_disabled(true);
- ok(accessthirdparty.disabled, "access third party button should be disabled");
-
- pbautostart.checked = false;
- controlChanged(pbautostart);
- expect_disabled(true);
- ok(accessthirdparty.disabled, "access third party button should be disabled");
-
- acceptcookies.checked = true;
- controlChanged(acceptcookies);
- expect_disabled(false);
- ok(!accessthirdparty.disabled, "access third party button should be enabled");
-}
-
-function test_dependent_clearonclose_elements(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
- let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
- ok(pbautostart, "the private browsing auto-start checkbox should exist");
- let alwaysclear = win.document.getElementById("alwaysClear");
- ok(alwaysclear, "the clear data on close checkbox should exist");
- let alwaysclearsettings = win.document.getElementById("clearDataSettings");
- ok(alwaysclearsettings, "the clear data settings button should exist");
-
- function expect_disabled(disabled) {
- is(alwaysclearsettings.disabled, disabled,
- "the clear data settings should " + (disabled ? "" : "not ") + "be disabled");
- }
-
- historymode.value = "custom";
- controlChanged(historymode);
- pbautostart.checked = false;
- controlChanged(pbautostart);
- alwaysclear.checked = false;
- controlChanged(alwaysclear);
- expect_disabled(true);
-
- alwaysclear.checked = true;
- controlChanged(alwaysclear);
- expect_disabled(false);
-
- alwaysclear.checked = false;
- controlChanged(alwaysclear);
- expect_disabled(true);
-}
-
-function test_dependent_prefs(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
- let controls = [
- win.document.getElementById("rememberHistory"),
- win.document.getElementById("rememberForms"),
- win.document.getElementById("acceptCookies")
- ];
- controls.forEach(function(control) {
- ok(control, "the micro-management controls should exist");
- });
-
- let thirdPartyCookieMenu = win.document.getElementById("acceptThirdPartyMenu");
- ok(thirdPartyCookieMenu, "the third-party cookie control should exist");
-
- function expect_checked(checked) {
- controls.forEach(function(control) {
- is(control.checked, checked,
- control.getAttribute("id") + " should " + (checked ? "not " : "") + "be checked");
- });
-
- is(thirdPartyCookieMenu.value == "always" || thirdPartyCookieMenu.value == "visited", checked, "third-party cookies should " + (checked ? "not " : "") + "be limited");
- }
-
- // controls should be checked in remember mode
- historymode.value = "remember";
- controlChanged(historymode);
- expect_checked(true);
-
- // even if they're unchecked in custom mode
- historymode.value = "custom";
- controlChanged(historymode);
- thirdPartyCookieMenu.value = "never";
- controlChanged(thirdPartyCookieMenu);
- controls.forEach(function(control) {
- control.checked = false;
- controlChanged(control);
- });
- expect_checked(false);
- historymode.value = "remember";
- controlChanged(historymode);
- expect_checked(true);
-}
-
-function test_historymode_retention(mode, expect) {
- return function test_historymode_retention_fn(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
-
- if ((historymode.value == "remember" && mode == "dontremember") ||
- (historymode.value == "dontremember" && mode == "remember") ||
- (historymode.value == "custom" && mode == "dontremember")) {
- return;
- }
-
- if (expect !== undefined) {
- is(historymode.value, expect,
- "history mode is expected to remain " + expect);
- }
-
- historymode.value = mode;
- controlChanged(historymode);
- };
-}
-
-function test_custom_retention(controlToChange, expect, valueIncrement) {
- return function test_custom_retention_fn(win) {
- let historymode = win.document.getElementById("historyMode");
- ok(historymode, "history mode menulist should exist");
-
- if (expect !== undefined) {
- is(historymode.value, expect,
- "history mode is expected to remain " + expect);
- }
-
- historymode.value = "custom";
- controlChanged(historymode);
-
- controlToChange = win.document.getElementById(controlToChange);
- ok(controlToChange, "the control to change should exist");
- switch (controlToChange.localName) {
- case "checkbox":
- controlToChange.checked = !controlToChange.checked;
- break;
- case "textbox":
- controlToChange.value = parseInt(controlToChange.value) + valueIncrement;
- break;
- case "menulist":
- controlToChange.value = valueIncrement;
- break;
- }
- controlChanged(controlToChange);
- };
-}
-
-function test_locbar_suggestion_retention(suggestion, autocomplete) {
- return function(win) {
- let elem = win.document.getElementById(suggestion + "Suggestion");
- ok(elem, "Suggest " + suggestion + " checkbox should exist.");
- elem.click();
-
- is(Services.prefs.getBoolPref("browser.urlbar.autocomplete.enabled"), autocomplete,
- "browser.urlbar.autocomplete.enabled pref should be " + autocomplete);
- };
-}
-
-const gPrefCache = new Map();
-
-function cache_preferences(win) {
- let prefs = win.document.querySelectorAll("#privacyPreferences > preference");
- for (let pref of prefs)
- gPrefCache.set(pref.name, pref.value);
-}
-
-function reset_preferences(win) {
- let prefs = win.document.querySelectorAll("#privacyPreferences > preference");
- for (let pref of prefs)
- pref.value = gPrefCache.get(pref.name);
-}
-
-function run_test_subset(subset) {
- info("subset: " + Array.from(subset, x => x.name).join(",") + "\n");
- SpecialPowers.pushPrefEnv({"set": [["browser.preferences.instantApply", true]]});
-
- let tests = [cache_preferences, ...subset, reset_preferences];
- for (let test of tests) {
- add_task(runTestOnPrivacyPrefPane.bind(undefined, test));
- }
-}
diff --git a/browser/components/preferences/in-content/tests/subdialog.xul b/browser/components/preferences/in-content/tests/subdialog.xul
deleted file mode 100644
index 48d297b73..000000000
--- a/browser/components/preferences/in-content/tests/subdialog.xul
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<dialog id="subDialog"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Sample sub-dialog" style="width: 32em; height: 5em;"
- onload="document.getElementById('textbox').focus();"
- ondialogaccept="acceptSubdialog();">
- <script>
- function acceptSubdialog() {
- window.arguments[0].acceptCount++;
- }
- </script>
-
- <description id="desc">A sample sub-dialog for testing</description>
-
- <textbox id="textbox" value="Default text" />
-
- <separator class="thin"/>
-
- <button oncommand="close();" icon="close" label="Close" />
-
-</dialog>
diff --git a/browser/components/preferences/in-content/tests/subdialog2.xul b/browser/components/preferences/in-content/tests/subdialog2.xul
deleted file mode 100644
index 89803c250..000000000
--- a/browser/components/preferences/in-content/tests/subdialog2.xul
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<dialog id="subDialog"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- title="Sample sub-dialog #2" style="width: 32em; height: 5em;"
- onload="document.getElementById('textbox').focus();"
- ondialogaccept="acceptSubdialog();">
- <script>
- function acceptSubdialog() {
- window.arguments[0].acceptCount++;
- }
- </script>
-
- <description id="desc">A sample sub-dialog for testing</description>
-
- <textbox id="textbox" value="Default text" />
-
- <separator class="thin"/>
-
- <button oncommand="close();" icon="close" label="Close" />
-
-</dialog>
diff --git a/browser/components/privatebrowsing/test/browser/.eslintrc.js b/browser/components/privatebrowsing/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/privatebrowsing/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/privatebrowsing/test/browser/browser.ini b/browser/components/privatebrowsing/test/browser/browser.ini
deleted file mode 100644
index 5efca4c0e..000000000
--- a/browser/components/privatebrowsing/test/browser/browser.ini
+++ /dev/null
@@ -1,54 +0,0 @@
-[DEFAULT]
-tags = openwindow
-support-files =
- browser_privatebrowsing_concurrent_page.html
- browser_privatebrowsing_geoprompt_page.html
- browser_privatebrowsing_localStorage_before_after_page.html
- browser_privatebrowsing_localStorage_before_after_page2.html
- browser_privatebrowsing_localStorage_page1.html
- browser_privatebrowsing_localStorage_page2.html
- browser_privatebrowsing_placesTitleNoUpdate.html
- browser_privatebrowsing_protocolhandler_page.html
- browser_privatebrowsing_windowtitle_page.html
- head.js
- popup.html
- title.sjs
- empty_file.html
- file_favicon.html
- file_favicon.png
- file_favicon.png^headers^
-
-[browser_privatebrowsing_DownloadLastDirWithCPS.js]
-[browser_privatebrowsing_about.js]
-tags = trackingprotection
-[browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js]
-[browser_privatebrowsing_aboutSessionRestore.js]
-[browser_privatebrowsing_cache.js]
-[browser_privatebrowsing_certexceptionsui.js]
-[browser_privatebrowsing_concurrent.js]
-[browser_privatebrowsing_context_and_chromeFlags.js]
-[browser_privatebrowsing_crh.js]
-[browser_privatebrowsing_downloadLastDir.js]
-[browser_privatebrowsing_downloadLastDir_c.js]
-[browser_privatebrowsing_downloadLastDir_toggle.js]
-[browser_privatebrowsing_favicon.js]
-[browser_privatebrowsing_geoprompt.js]
-[browser_privatebrowsing_lastpbcontextexited.js]
-[browser_privatebrowsing_localStorage.js]
-[browser_privatebrowsing_localStorage_before_after.js]
-[browser_privatebrowsing_noSessionRestoreMenuOption.js]
-[browser_privatebrowsing_nonbrowser.js]
-[browser_privatebrowsing_opendir.js]
-[browser_privatebrowsing_placesTitleNoUpdate.js]
-[browser_privatebrowsing_placestitle.js]
-[browser_privatebrowsing_popupblocker.js]
-[browser_privatebrowsing_protocolhandler.js]
-[browser_privatebrowsing_sidebar.js]
-[browser_privatebrowsing_theming.js]
-[browser_privatebrowsing_ui.js]
-[browser_privatebrowsing_urlbarfocus.js]
-[browser_privatebrowsing_windowtitle.js]
-[browser_privatebrowsing_zoom.js]
-[browser_privatebrowsing_zoomrestore.js]
-[browser_privatebrowsing_newtab_from_popup.js]
-[browser_privatebrowsing_blobUrl.js]
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js
deleted file mode 100644
index bcd19b192..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js
+++ /dev/null
@@ -1,282 +0,0 @@
-/* -*- 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/. */
-
-var gTests;
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(2);
- gTests = runTest();
- gTests.next();
-}
-
-/*
- * ================
- * Helper functions
- * ================
- */
-
-function moveAlong(aResult) {
- try {
- gTests.send(aResult);
- } catch (x if x instanceof StopIteration) {
- finish();
- }
-}
-
-function createWindow(aOptions) {
- whenNewWindowLoaded(aOptions, function(win) {
- moveAlong(win);
- });
-}
-
-function getFile(downloadLastDir, aURI) {
- downloadLastDir.getFileAsync(aURI, function(result) {
- moveAlong(result);
- });
-}
-
-function setFile(downloadLastDir, aURI, aValue) {
- downloadLastDir.setFile(aURI, aValue);
- executeSoon(moveAlong);
-}
-
-function clearHistoryAndWait() {
- clearHistory();
- executeSoon(() => executeSoon(moveAlong));
-}
-
-/*
- * ===================
- * Function with tests
- * ===================
- */
-
-function runTest() {
- let FileUtils =
- Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;
- let DownloadLastDir =
- Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir;
-
- let tmpDir = FileUtils.getDir("TmpD", [], true);
- let dir1 = newDirectory();
- let dir2 = newDirectory();
- let dir3 = newDirectory();
-
- let uri1 = Services.io.newURI("http://test1.com/", null, null);
- let uri2 = Services.io.newURI("http://test2.com/", null, null);
- let uri3 = Services.io.newURI("http://test3.com/", null, null);
- let uri4 = Services.io.newURI("http://test4.com/", null, null);
-
- // cleanup functions registration
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");
- Services.prefs.clearUserPref("browser.download.lastDir");
- [dir1, dir2, dir3].forEach(dir => dir.remove(true));
- win.close();
- pbWin.close();
- });
-
- function checkDownloadLastDir(gDownloadLastDir, aLastDir) {
- is(gDownloadLastDir.file.path, aLastDir.path,
- "gDownloadLastDir should point to the expected last directory");
- getFile(gDownloadLastDir, uri1);
- }
-
- function checkDownloadLastDirNull(gDownloadLastDir) {
- is(gDownloadLastDir.file, null, "gDownloadLastDir should be null");
- getFile(gDownloadLastDir, uri1);
- }
-
- /*
- * ================================
- * Create a regular and a PB window
- * ================================
- */
-
- let win = yield createWindow({private: false});
- let pbWin = yield createWindow({private: true});
-
- let downloadLastDir = new DownloadLastDir(win);
- let pbDownloadLastDir = new DownloadLastDir(pbWin);
-
- /*
- * ==================
- * Beginning of tests
- * ==================
- */
-
- is(typeof downloadLastDir, "object",
- "downloadLastDir should be a valid object");
- is(downloadLastDir.file, null,
- "LastDir pref should be null to start with");
-
- // set up last dir
- yield setFile(downloadLastDir, null, tmpDir);
- is(downloadLastDir.file.path, tmpDir.path,
- "LastDir should point to the tmpDir");
- isnot(downloadLastDir.file, tmpDir,
- "downloadLastDir.file should not be pointing to tmpDir");
-
- // set uri1 to dir1, all should now return dir1
- // also check that a new object is returned
- yield setFile(downloadLastDir, uri1, dir1);
- is(downloadLastDir.file.path, dir1.path,
- "downloadLastDir should return dir1");
- isnot(downloadLastDir.file, dir1,
- "downloadLastDir.file should not return dir1");
- is((yield getFile(downloadLastDir, uri1)).path, dir1.path,
- "uri1 should return dir1"); // set in CPS
- isnot((yield getFile(downloadLastDir, uri1)), dir1,
- "getFile on uri1 should not return dir1");
- is((yield getFile(downloadLastDir, uri2)).path, dir1.path,
- "uri2 should return dir1"); // fallback
- isnot((yield getFile(downloadLastDir, uri2)), dir1,
- "getFile on uri2 should not return dir1");
- is((yield getFile(downloadLastDir, uri3)).path, dir1.path,
- "uri3 should return dir1"); // fallback
- isnot((yield getFile(downloadLastDir, uri3)), dir1,
- "getFile on uri3 should not return dir1");
- is((yield getFile(downloadLastDir, uri4)).path, dir1.path,
- "uri4 should return dir1"); // fallback
- isnot((yield getFile(downloadLastDir, uri4)), dir1,
- "getFile on uri4 should not return dir1");
-
- // set uri2 to dir2, all except uri1 should now return dir2
- yield setFile(downloadLastDir, uri2, dir2);
- is(downloadLastDir.file.path, dir2.path,
- "downloadLastDir should point to dir2");
- is((yield getFile(downloadLastDir, uri1)).path, dir1.path,
- "uri1 should return dir1"); // set in CPS
- is((yield getFile(downloadLastDir, uri2)).path, dir2.path,
- "uri2 should return dir2"); // set in CPS
- is((yield getFile(downloadLastDir, uri3)).path, dir2.path,
- "uri3 should return dir2"); // fallback
- is((yield getFile(downloadLastDir, uri4)).path, dir2.path,
- "uri4 should return dir2"); // fallback
-
- // set uri3 to dir3, all except uri1 and uri2 should now return dir3
- yield setFile(downloadLastDir, uri3, dir3);
- is(downloadLastDir.file.path, dir3.path,
- "downloadLastDir should point to dir3");
- is((yield getFile(downloadLastDir, uri1)).path, dir1.path,
- "uri1 should return dir1"); // set in CPS
- is((yield getFile(downloadLastDir, uri2)).path, dir2.path,
- "uri2 should return dir2"); // set in CPS
- is((yield getFile(downloadLastDir, uri3)).path, dir3.path,
- "uri3 should return dir3"); // set in CPS
- is((yield getFile(downloadLastDir, uri4)).path, dir3.path,
- "uri4 should return dir4"); // fallback
-
- // set uri1 to dir2, all except uri3 should now return dir2
- yield setFile(downloadLastDir, uri1, dir2);
- is(downloadLastDir.file.path, dir2.path,
- "downloadLastDir should point to dir2");
- is((yield getFile(downloadLastDir, uri1)).path, dir2.path,
- "uri1 should return dir2"); // set in CPS
- is((yield getFile(downloadLastDir, uri2)).path, dir2.path,
- "uri2 should return dir2"); // set in CPS
- is((yield getFile(downloadLastDir, uri3)).path, dir3.path,
- "uri3 should return dir3"); // set in CPS
- is((yield getFile(downloadLastDir, uri4)).path, dir2.path,
- "uri4 should return dir2"); // fallback
-
- yield clearHistoryAndWait();
-
- // check clearHistory removes all data
- is(downloadLastDir.file, null, "clearHistory removes all data");
- //is(Services.contentPrefs.hasPref(uri1, "browser.download.lastDir", null),
- // false, "LastDir preference should be absent");
- is((yield getFile(downloadLastDir, uri1)), null, "uri1 should point to null");
- is((yield getFile(downloadLastDir, uri2)), null, "uri2 should point to null");
- is((yield getFile(downloadLastDir, uri3)), null, "uri3 should point to null");
- is((yield getFile(downloadLastDir, uri4)), null, "uri4 should point to null");
-
- yield setFile(downloadLastDir, null, tmpDir);
-
- // check data set outside PB mode is remembered
- is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDir(downloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");
- yield clearHistoryAndWait();
-
- yield setFile(downloadLastDir, uri1, dir1);
-
- // check data set using CPS outside PB mode is remembered
- is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");
- yield clearHistoryAndWait();
-
- // check data set inside PB mode is forgotten
- yield setFile(pbDownloadLastDir, null, tmpDir);
-
- is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");
-
- yield clearHistoryAndWait();
-
- // check data set using CPS inside PB mode is forgotten
- yield setFile(pbDownloadLastDir, uri1, dir1);
-
- is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");
-
- // check data set outside PB mode but changed inside is remembered correctly
- yield setFile(downloadLastDir, uri1, dir1);
- yield setFile(pbDownloadLastDir, uri1, dir2);
- is((yield checkDownloadLastDir(pbDownloadLastDir, dir2)).path, dir2.path, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");
-
- /*
- * ====================
- * Create new PB window
- * ====================
- */
-
- // check that the last dir store got cleared in a new PB window
- pbWin.close();
- // And give it time to close
- executeSoon(moveAlong);
- yield;
- pbWin = yield createWindow({private: true});
- pbDownloadLastDir = new DownloadLastDir(pbWin);
-
- is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");
-
- yield clearHistoryAndWait();
-
- // check clearHistory inside PB mode clears data outside PB mode
- yield setFile(pbDownloadLastDir, uri1, dir2);
-
- yield clearHistoryAndWait();
-
- is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");
- is((yield checkDownloadLastDirNull(pbDownloadLastDir)), null, "uri1 should return the expected last directory");
-
- // check that disabling CPS works
- Services.prefs.setBoolPref("browser.download.lastDir.savePerSite", false);
-
- yield setFile(downloadLastDir, uri1, dir1);
- is(downloadLastDir.file.path, dir1.path, "LastDir should be set to dir1");
- is((yield getFile(downloadLastDir, uri1)).path, dir1.path, "uri1 should return dir1");
- is((yield getFile(downloadLastDir, uri2)).path, dir1.path, "uri2 should return dir1");
- is((yield getFile(downloadLastDir, uri3)).path, dir1.path, "uri3 should return dir1");
- is((yield getFile(downloadLastDir, uri4)).path, dir1.path, "uri4 should return dir1");
-
- downloadLastDir.setFile(uri2, dir2);
- is(downloadLastDir.file.path, dir2.path, "LastDir should be set to dir2");
- is((yield getFile(downloadLastDir, uri1)).path, dir2.path, "uri1 should return dir2");
- is((yield getFile(downloadLastDir, uri2)).path, dir2.path, "uri2 should return dir2");
- is((yield getFile(downloadLastDir, uri3)).path, dir2.path, "uri3 should return dir2");
- is((yield getFile(downloadLastDir, uri4)).path, dir2.path, "uri4 should return dir2");
-
- Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");
-
- // check that passing null to setFile clears the stored value
- yield setFile(downloadLastDir, uri3, dir3);
- is((yield getFile(downloadLastDir, uri3)).path, dir3.path, "LastDir should be set to dir3");
- yield setFile(downloadLastDir, uri3, null);
- is((yield getFile(downloadLastDir, uri3)), null, "uri3 should return null");
-
- yield clearHistoryAndWait();
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js
deleted file mode 100644
index e00f3f67a..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* 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/. */
-
-/**
- * Opens a new private window and loads "about:privatebrowsing" there.
- */
-function* openAboutPrivateBrowsing() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- let tab = win.gBrowser.selectedBrowser;
- tab.loadURI("about:privatebrowsing");
- yield BrowserTestUtils.browserLoaded(tab);
- return { win, tab };
-}
-
-/**
- * Clicks the given link and checks this opens a new tab with the given URI.
- */
-function* testLinkOpensTab({ win, tab, elementId, expectedUrl }) {
- let newTabPromise = BrowserTestUtils.waitForNewTab(win.gBrowser, expectedUrl);
- yield ContentTask.spawn(tab, { elementId }, function* ({ elementId }) {
- content.document.getElementById(elementId).click();
- });
- let newTab = yield newTabPromise;
- ok(true, `Clicking ${elementId} opened ${expectedUrl} in a new tab.`);
- yield BrowserTestUtils.removeTab(newTab);
-}
-
-/**
- * Clicks the given link and checks this opens the given URI in the same tab.
- *
- * This function does not return to the previous page.
- */
-function* testLinkOpensUrl({ win, tab, elementId, expectedUrl }) {
- let loadedPromise = BrowserTestUtils.browserLoaded(tab);
- yield ContentTask.spawn(tab, { elementId }, function* ({ elementId }) {
- content.document.getElementById(elementId).click();
- });
- yield loadedPromise;
- is(tab.currentURI.spec, expectedUrl,
- `Clicking ${elementId} opened ${expectedUrl} in the same tab.`);
-}
-
-/**
- * Tests the links in "about:privatebrowsing".
- */
-add_task(function* test_links() {
- // Use full version and change the remote URLs to prevent network access.
- Services.prefs.setCharPref("app.support.baseURL", "https://example.com/");
- Services.prefs.setCharPref("privacy.trackingprotection.introURL",
- "https://example.com/tour");
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("privacy.trackingprotection.introURL");
- Services.prefs.clearUserPref("app.support.baseURL");
- });
-
- let { win, tab } = yield openAboutPrivateBrowsing();
-
- yield testLinkOpensTab({ win, tab,
- elementId: "learnMore",
- expectedUrl: "https://example.com/private-browsing",
- });
-
- yield testLinkOpensUrl({ win, tab,
- elementId: "startTour",
- expectedUrl: "https://example.com/tour",
- });
-
- yield BrowserTestUtils.closeWindow(win);
-});
-
-/**
- * Tests the action to disable and re-enable Tracking Protection in
- * "about:privatebrowsing".
- */
-add_task(function* test_toggleTrackingProtection() {
- // Use tour version but disable Tracking Protection.
- Services.prefs.setBoolPref("privacy.trackingprotection.pbmode.enabled",
- true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("privacy.trackingprotection.pbmode.enabled");
- });
-
- let { win, tab } = yield openAboutPrivateBrowsing();
-
- // Set up the observer for the preference change before triggering the action.
- let prefBranch =
- Services.prefs.getBranch("privacy.trackingprotection.pbmode.");
- let waitForPrefChanged = () => new Promise(resolve => {
- let prefObserver = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
- observe: function () {
- prefBranch.removeObserver("enabled", prefObserver);
- resolve();
- },
- };
- prefBranch.addObserver("enabled", prefObserver, false);
- });
-
- let promisePrefChanged = waitForPrefChanged();
- yield ContentTask.spawn(tab, {}, function* () {
- content.document.getElementById("tpButton").click();
- });
- yield promisePrefChanged;
- ok(!prefBranch.getBoolPref("enabled"), "Tracking Protection is disabled.");
-
- promisePrefChanged = waitForPrefChanged();
- yield ContentTask.spawn(tab, {}, function* () {
- content.document.getElementById("tpButton").click();
- });
- yield promisePrefChanged;
- ok(prefBranch.getBoolPref("enabled"), "Tracking Protection is enabled.");
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js
deleted file mode 100644
index 6f52f7719..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* 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/. */
-
-// This test checks that the Session Restore "Restore Previous Session"
-// button on about:home is disabled in private mode
-add_task(function* test_no_sessionrestore_button() {
- // Opening, then closing, a private window shouldn't create session data.
- (yield BrowserTestUtils.openNewBrowserWindow({private: true})).close();
-
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let tab = win.gBrowser.addTab("about:home");
- let browser = tab.linkedBrowser;
-
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- let button = content.document.getElementById("restorePreviousSession");
- Assert.equal(content.getComputedStyle(button).display, "none",
- "The Session Restore about:home button should be disabled");
- });
-
- win.close();
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js
deleted file mode 100644
index 5f6a91836..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* 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/. */
-
-// This test checks that the session restore button from about:sessionrestore
-// is disabled in private mode
-add_task(function* testNoSessionRestoreButton() {
- // Opening, then closing, a private window shouldn't create session data.
- (yield BrowserTestUtils.openNewBrowserWindow({private: true})).close();
-
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let tab = win.gBrowser.addTab("about:sessionrestore");
- let browser = tab.linkedBrowser;
-
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield ContentTask.spawn(browser, null, function* () {
- Assert.ok(content.document.getElementById("errorTryAgain").disabled,
- "The Restore about:sessionrestore button should be disabled");
- });
-
- win.close();
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js
deleted file mode 100644
index 2ceb1032b..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-// Here we want to test that blob URLs are not available between private and
-// non-private browsing.
-
-const BASE_URI = "http://mochi.test:8888/browser/browser/components/"
- + "privatebrowsing/test/browser/empty_file.html";
-
-add_task(function* test() {
- info("Creating a normal window...");
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let tab = win.gBrowser.selectedBrowser;
- tab.loadURI(BASE_URI);
- yield BrowserTestUtils.browserLoaded(tab);
-
- let blobURL;
-
- info("Creating a blob URL...");
- yield ContentTask.spawn(tab, null, function() {
- return Promise.resolve(content.window.URL.createObjectURL(new content.window.Blob([123])));
- }).then(newURL => { blobURL = newURL });
-
- info("Blob URL: " + blobURL);
-
- info("Creating a private window...");
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- let privateTab = privateWin.gBrowser.selectedBrowser;
- privateTab.loadURI(BASE_URI);
- yield BrowserTestUtils.browserLoaded(privateTab);
-
- yield ContentTask.spawn(privateTab, blobURL, function(url) {
- return new Promise(resolve => {
- var xhr = new content.window.XMLHttpRequest();
- xhr.onerror = function() { resolve("SendErrored"); }
- xhr.onload = function() { resolve("SendLoaded"); }
- xhr.open("GET", url);
- xhr.send();
- });
- }).then(status => {
- is(status, "SendErrored", "Using a blob URI from one user context id in another should not work");
- });
-
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(privateWin);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js
deleted file mode 100644
index 4990f6d3b..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js
+++ /dev/null
@@ -1,138 +0,0 @@
-/* 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/. */
-
-// Check about:cache after private browsing
-// This test covers MozTrap test 6047
-// bug 880621
-
-var {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", null);
-
-var tmp = {};
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tmp);
-
-var Sanitizer = tmp.Sanitizer;
-
-function test() {
-
- waitForExplicitFinish();
-
- sanitizeCache();
-
- let nrEntriesR1 = getStorageEntryCount("regular", function(nrEntriesR1) {
- is(nrEntriesR1, 0, "Disk cache reports 0KB and has no entries");
-
- get_cache_for_private_window();
- });
-}
-
-function cleanup() {
- let prefs = Services.prefs.getBranch("privacy.cpd.");
-
- prefs.clearUserPref("history");
- prefs.clearUserPref("downloads");
- prefs.clearUserPref("cache");
- prefs.clearUserPref("cookies");
- prefs.clearUserPref("formdata");
- prefs.clearUserPref("offlineApps");
- prefs.clearUserPref("passwords");
- prefs.clearUserPref("sessions");
- prefs.clearUserPref("siteSettings");
-}
-
-function sanitizeCache() {
-
- let s = new Sanitizer();
- s.ignoreTimespan = false;
- s.prefDomain = "privacy.cpd.";
-
- let prefs = gPrefService.getBranch(s.prefDomain);
- prefs.setBoolPref("history", false);
- prefs.setBoolPref("downloads", false);
- prefs.setBoolPref("cache", true);
- prefs.setBoolPref("cookies", false);
- prefs.setBoolPref("formdata", false);
- prefs.setBoolPref("offlineApps", false);
- prefs.setBoolPref("passwords", false);
- prefs.setBoolPref("sessions", false);
- prefs.setBoolPref("siteSettings", false);
-
- s.sanitize();
-}
-
-function get_cache_service() {
- return Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Components.interfaces.nsICacheStorageService);
-}
-
-function getStorageEntryCount(device, goon) {
- var cs = get_cache_service();
-
- var storage;
- switch (device) {
- case "private":
- storage = cs.diskCacheStorage(LoadContextInfo.private, false);
- break;
- case "regular":
- storage = cs.diskCacheStorage(LoadContextInfo.default, false);
- break;
- default:
- throw "Unknown device " + device + " at getStorageEntryCount";
- }
-
- var visitor = {
- entryCount: 0,
- onCacheStorageInfo: function (aEntryCount, aConsumption) {
- },
- onCacheEntryInfo: function(uri)
- {
- var urispec = uri.asciiSpec;
- info(device + ":" + urispec + "\n");
- if (urispec.match(/^http:\/\/example.org\//))
- ++this.entryCount;
- },
- onCacheEntryVisitCompleted: function()
- {
- goon(this.entryCount);
- }
- };
-
- storage.asyncVisitStorage(visitor, true);
-}
-
-function get_cache_for_private_window () {
- let win = whenNewWindowLoaded({private: true}, function() {
-
- executeSoon(function() {
-
- ok(true, "The private window got loaded");
-
- let tab = win.gBrowser.addTab("http://example.org");
- win.gBrowser.selectedTab = tab;
- let newTabBrowser = win.gBrowser.getBrowserForTab(tab);
-
- newTabBrowser.addEventListener("load", function eventHandler() {
- newTabBrowser.removeEventListener("load", eventHandler, true);
-
- executeSoon(function() {
-
- getStorageEntryCount("private", function(nrEntriesP) {
- ok(nrEntriesP >= 1, "Memory cache reports some entries from example.org domain");
-
- getStorageEntryCount("regular", function(nrEntriesR2) {
- is(nrEntriesR2, 0, "Disk cache reports 0KB and has no entries");
-
- cleanup();
-
- win.close();
- finish();
- });
- });
- });
- }, true);
- });
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js
deleted file mode 100644
index 519f43475..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* 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/. */
-
-// This test makes sure that certificate exceptions UI behaves correctly
-// in private browsing windows, based on whether it's opened from the prefs
-// window or from the SSL error page (see bug 461627).
-
-function test() {
- const EXCEPTIONS_DLG_URL = 'chrome://pippki/content/exceptionDialog.xul';
- const EXCEPTIONS_DLG_FEATURES = 'chrome,centerscreen';
- const INVALID_CERT_LOCATION = 'https://nocert.example.com/';
- waitForExplicitFinish();
-
- // open a private browsing window
- var pbWin = OpenBrowserWindow({private: true});
- pbWin.addEventListener("load", function onLoad() {
- pbWin.removeEventListener("load", onLoad, false);
- doTest();
- }, false);
-
- // Test the certificate exceptions dialog
- function doTest() {
- let params = {
- exceptionAdded : false,
- location: INVALID_CERT_LOCATION,
- prefetchCert: true,
- };
- function testCheckbox() {
- win.removeEventListener("load", testCheckbox, false);
- Services.obs.addObserver(function onCertUI(aSubject, aTopic, aData) {
- Services.obs.removeObserver(onCertUI, "cert-exception-ui-ready");
- ok(win.gCert, "The certificate information should be available now");
-
- let checkbox = win.document.getElementById("permanent");
- ok(checkbox.hasAttribute("disabled"),
- "the permanent checkbox should be disabled when handling the private browsing mode");
- ok(!checkbox.hasAttribute("checked"),
- "the permanent checkbox should not be checked when handling the private browsing mode");
- win.close();
- cleanup();
- }, "cert-exception-ui-ready", false);
- }
- var win = pbWin.openDialog(EXCEPTIONS_DLG_URL, "", EXCEPTIONS_DLG_FEATURES, params);
- win.addEventListener("load", testCheckbox, false);
- }
-
- function cleanup() {
- // close the private browsing window
- pbWin.close();
- finish();
- }
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js
deleted file mode 100644
index b73bbf219..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/* 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/. */
-
-// Test opening two tabs that share a localStorage, but keep one in private mode.
-// Ensure that values from one don't leak into the other, and that values from
-// earlier private storage sessions aren't visible later.
-
-// Step 1: create new tab, load a page that sets test=value in non-private storage
-// Step 2: create a new tab, load a page that sets test2=value2 in private storage
-// Step 3: load a page in the tab from step 1 that checks the value of test2 is value2 and the total count in non-private storage is 1
-// Step 4: load a page in the tab from step 2 that checks the value of test is value and the total count in private storage is 1
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-});
-
-add_task(function test() {
- let prefix = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html';
-
- function getElts(browser) {
- return browser.contentTitle.split('|');
- };
-
- // Step 1
- let non_private_browser = gBrowser.selectedBrowser;
- non_private_browser.loadURI(prefix + '?action=set&name=test&value=value&initial=true');
- yield BrowserTestUtils.browserLoaded(non_private_browser);
-
-
- // Step 2
- let private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : true });
- let private_browser = private_window.getBrowser().selectedBrowser;
- private_browser.loadURI(prefix + '?action=set&name=test2&value=value2');
- yield BrowserTestUtils.browserLoaded(private_browser);
-
-
- // Step 3
- non_private_browser.loadURI(prefix + '?action=get&name=test2');
- yield BrowserTestUtils.browserLoaded(non_private_browser);
- let elts = yield getElts(non_private_browser);
- isnot(elts[0], 'value2', "public window shouldn't see private storage");
- is(elts[1], '1', "public window should only see public items");
-
-
- // Step 4
- private_browser.loadURI(prefix + '?action=get&name=test');
- yield BrowserTestUtils.browserLoaded(private_browser);
- elts = yield getElts(private_browser);
- isnot(elts[0], 'value', "private window shouldn't see public storage");
- is(elts[1], '1', "private window should only see private items");
-
-
- // Reopen the private window again, without privateBrowsing, which should clear the
- // the private storage.
- private_window.close();
- private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : false });
- private_browser = null;
- yield new Promise(resolve => Cu.schedulePreciseGC(resolve));
- private_browser = private_window.getBrowser().selectedBrowser;
-
- private_browser.loadURI(prefix + '?action=get&name=test2');
- yield BrowserTestUtils.browserLoaded(private_browser);
- elts = yield getElts(private_browser);
- isnot(elts[0], 'value2', "public window shouldn't see cleared private storage");
- is(elts[1], '1', "public window should only see public items");
-
-
- // Making it private again should clear the storage and it shouldn't
- // be able to see the old private storage as well.
- private_window.close();
- private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : true });
- private_browser = null;
- yield new Promise(resolve => Cu.schedulePreciseGC(resolve));
- private_browser = private_window.getBrowser().selectedBrowser;
-
- private_browser.loadURI(prefix + '?action=set&name=test3&value=value3');
- yield BrowserTestUtils.browserLoaded(private_browser);
- elts = yield getElts(private_browser);
- is(elts[1], '1', "private window should only see new private items");
-
- // Cleanup.
- non_private_browser.loadURI(prefix + '?final=true');
- yield BrowserTestUtils.browserLoaded(non_private_browser);
- private_window.close();
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html
deleted file mode 100644
index db35b114d..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<script type="text/javascript">
- var oGetVars = {};
-
- if (window.location.search.length > 1) {
- for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&");
- nKeyId < aCouples.length;
- nKeyId++) {
- aItKey = aCouples[nKeyId].split("=");
- oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
- }
- }
-
- if (oGetVars.initial == 'true') {
- localStorage.clear();
- }
-
- if (oGetVars.action == 'set') {
- localStorage.setItem(oGetVars.name, oGetVars.value);
- document.title = localStorage.getItem(oGetVars.name) + "|" + localStorage.length;
- } else if (oGetVars.action == 'get') {
- document.title = localStorage.getItem(oGetVars.name) + "|" + localStorage.length;
- }
-
- if (oGetVars.final == 'true') {
- localStorage.clear();
- }
-</script>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js
deleted file mode 100644
index 30f7ee025..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js
+++ /dev/null
@@ -1,60 +0,0 @@
-"use strict";
-
-/**
- * Given some window in the parent process, ensure that
- * the nsIXULWindow has the CHROME_PRIVATE_WINDOW chromeFlag,
- * and that the usePrivateBrowsing property is set to true on
- * both the window's nsILoadContext, as well as on the initial
- * browser's content docShell nsILoadContext.
- *
- * @param win (nsIDOMWindow)
- * An nsIDOMWindow in the parent process.
- * @return Promise
- */
-function assertWindowIsPrivate(win) {
- let winDocShell = win.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDocShell);
- let chromeFlags = winDocShell.QueryInterface(Ci.nsIDocShellTreeItem)
- .treeOwner
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIXULWindow)
- .chromeFlags;
-
- if (!win.gBrowser.selectedBrowser.hasContentOpener) {
- Assert.ok(chromeFlags & Ci.nsIWebBrowserChrome.CHROME_PRIVATE_WINDOW,
- "Should have the private window chrome flag");
- }
-
- let loadContext = winDocShell.QueryInterface(Ci.nsILoadContext);
- Assert.ok(loadContext.usePrivateBrowsing,
- "The parent window should be using private browsing");
-
- return ContentTask.spawn(win.gBrowser.selectedBrowser, null, function*() {
- let loadContext = docShell.QueryInterface(Ci.nsILoadContext);
- Assert.ok(loadContext.usePrivateBrowsing,
- "Content docShell should be using private browsing");
- });
-}
-
-/**
- * Tests that chromeFlags bits and the nsILoadContext.usePrivateBrowsing
- * attribute are properly set when opening a new private browsing
- * window.
- */
-add_task(function* test_context_and_chromeFlags() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- yield assertWindowIsPrivate(win);
-
- let browser = win.gBrowser.selectedBrowser;
-
- let newWinPromise = BrowserTestUtils.waitForNewWindow();
- yield ContentTask.spawn(browser, null, function*() {
- content.open("http://example.com", "_blank", "width=100,height=100");
- });
-
- let win2 = yield newWinPromise;
- yield assertWindowIsPrivate(win2);
-
- yield BrowserTestUtils.closeWindow(win2);
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js
deleted file mode 100644
index cd316d1fb..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the Clear Recent History menu item and command
-// is disabled inside the private browsing mode.
-
-add_task(function test() {
- function checkDisableOption(aPrivateMode, aWindow) {
- let crhCommand = aWindow.document.getElementById("Tools:Sanitize");
- ok(crhCommand, "The clear recent history command should exist");
-
- is(PrivateBrowsingUtils.isWindowPrivate(aWindow), aPrivateMode,
- "PrivateBrowsingUtils should report the correct per-window private browsing status");
- is(crhCommand.hasAttribute("disabled"), aPrivateMode,
- "Clear Recent History command should be disabled according to the private browsing mode");
- };
-
- let testURI = "http://mochi.test:8888/";
-
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let privateBrowser = privateWin.gBrowser.selectedBrowser;
- privateBrowser.loadURI(testURI);
- yield BrowserTestUtils.browserLoaded(privateBrowser);
-
- info("Test on private window");
- checkDisableOption(true, privateWin);
-
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let browser = win.gBrowser.selectedBrowser;
- browser.loadURI(testURI);
- yield BrowserTestUtils.browserLoaded(browser);
-
- info("Test on public window");
- checkDisableOption(false, win);
-
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(privateWin);
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js
deleted file mode 100644
index 81b2943ee..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* -*- 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- let FileUtils =
- Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;
- let DownloadLastDir =
- Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir;
- let MockFilePicker = SpecialPowers.MockFilePicker;
- let launcher = {
- source: Services.io.newURI("http://test1.com/file", null, null)
- };
-
- MockFilePicker.init(window);
- MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
-
- let prefs = Services.prefs.getBranch("browser.download.");
- let launcherDialog =
- Cc["@mozilla.org/helperapplauncherdialog;1"].
- getService(Ci.nsIHelperAppLauncherDialog);
- let tmpDir = FileUtils.getDir("TmpD", [], true);
- let dir1 = newDirectory();
- let dir2 = newDirectory();
- let dir3 = newDirectory();
- let file1 = newFileInDirectory(dir1);
- let file2 = newFileInDirectory(dir2);
- let file3 = newFileInDirectory(dir3);
-
- // cleanup functions registration
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.download.lastDir");
- [dir1, dir2, dir3].forEach(dir => dir.remove(true));
- MockFilePicker.cleanup();
- });
- prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir);
-
- function testOnWindow(aPrivate, aCallback) {
- whenNewWindowLoaded({private: aPrivate}, function(win) {
- let gDownloadLastDir = new DownloadLastDir(win);
- aCallback(win, gDownloadLastDir);
- gDownloadLastDir.cleanupPrivateFile();
- });
- }
-
- function testDownloadDir(aWin, gDownloadLastDir, aFile, aDisplayDir, aLastDir,
- aGlobalLastDir, aCallback) {
- // Check lastDir preference.
- is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aDisplayDir.path,
- "LastDir should be the expected display dir");
- // Check gDownloadLastDir value.
- is(gDownloadLastDir.file.path, aDisplayDir.path,
- "gDownloadLastDir should be the expected display dir");
-
- MockFilePicker.returnFiles = [aFile];
- MockFilePicker.displayDirectory = null;
-
- launcher.saveDestinationAvailable = function (file) {
- ok(!!file, "promptForSaveToFile correctly returned a file");
-
- // File picker should start with expected display dir.
- is(MockFilePicker.displayDirectory.path, aDisplayDir.path,
- "File picker should start with browser.download.lastDir");
- // browser.download.lastDir should be modified on not private windows
- is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aLastDir.path,
- "LastDir should be the expected last dir");
- // gDownloadLastDir should be usable outside of private windows
- is(gDownloadLastDir.file.path, aGlobalLastDir.path,
- "gDownloadLastDir should be the expected global last dir");
-
- launcher.saveDestinationAvailable = null;
- aWin.close();
- aCallback();
- };
-
- launcherDialog.promptForSaveToFileAsync(launcher, aWin, null, null, null);
- }
-
- testOnWindow(false, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file1, tmpDir, dir1, dir1, function() {
- testOnWindow(true, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file2, dir1, dir1, dir2, function() {
- testOnWindow(false, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file3, dir1, dir3, dir3, finish);
- });
- });
- });
- });
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js
deleted file mode 100644
index 5a04d1999..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- let FileUtils =
- Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;
- let DownloadLastDir =
- Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir;
- let MockFilePicker = SpecialPowers.MockFilePicker;
-
- MockFilePicker.init(window);
- MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
-
- let validateFileNameToRestore = validateFileName;
- let prefs = Services.prefs.getBranch("browser.download.");
- let tmpDir = FileUtils.getDir("TmpD", [], true);
- let dir1 = newDirectory();
- let dir2 = newDirectory();
- let dir3 = newDirectory();
- let file1 = newFileInDirectory(dir1);
- let file2 = newFileInDirectory(dir2);
- let file3 = newFileInDirectory(dir3);
-
- // cleanup function registration
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.download.lastDir");
- [dir1, dir2, dir3].forEach(dir => dir.remove(true));
- MockFilePicker.cleanup();
- validateFileName = validateFileNameToRestore;
- });
-
- // Overwrite validateFileName to validate everything
- validateFileName = foo => foo;
-
- let params = {
- fileInfo: new FileInfo("test.txt", "test.txt", "test", "txt", "http://mozilla.org/test.txt"),
- contentType: "text/plain",
- saveMode: SAVEMODE_FILEONLY,
- saveAsType: kSaveAsType_Complete,
- file: null
- };
-
- prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir);
-
- function testOnWindow(aPrivate, aCallback) {
- whenNewWindowLoaded({private: aPrivate}, function(win) {
- let gDownloadLastDir = new DownloadLastDir(win);
- aCallback(win, gDownloadLastDir);
- });
- }
-
- function testDownloadDir(aWin, gDownloadLastDir, aFile, aDisplayDir, aLastDir,
- aGlobalLastDir, aCallback) {
- // Check lastDir preference.
- is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aDisplayDir.path,
- "LastDir should be the expected display dir");
- // Check gDownloadLastDir value.
- is(gDownloadLastDir.file.path, aDisplayDir.path,
- "gDownloadLastDir should be the expected display dir");
-
- MockFilePicker.returnFiles = [aFile];
- MockFilePicker.displayDirectory = null;
- aWin.promiseTargetFile(params).then(function() {
- // File picker should start with expected display dir.
- is(MockFilePicker.displayDirectory.path, aDisplayDir.path,
- "File picker should start with browser.download.lastDir");
- // browser.download.lastDir should be modified on not private windows
- is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aLastDir.path,
- "LastDir should be the expected last dir");
- // gDownloadLastDir should be usable outside of private windows
- is(gDownloadLastDir.file.path, aGlobalLastDir.path,
- "gDownloadLastDir should be the expected global last dir");
-
- gDownloadLastDir.cleanupPrivateFile();
- aWin.close();
- aCallback();
- }).then(null, function() { ok(false); });
- }
-
- testOnWindow(false, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file1, tmpDir, dir1, dir1, function() {
- testOnWindow(true, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file2, dir1, dir1, dir2, function() {
- testOnWindow(false, function(win, downloadDir) {
- testDownloadDir(win, downloadDir, file3, dir1, dir3, dir3, finish);
- });
- });
- });
- });
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js
deleted file mode 100644
index b192c08f7..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js
+++ /dev/null
@@ -1,105 +0,0 @@
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/DownloadLastDir.jsm");
-
-/**
- * Tests how the browser remembers the last download folder
- * from download to download, with a particular emphasis
- * on how it behaves when private browsing windows open.
- */
-add_task(function* test_downloads_last_dir_toggle() {
- let tmpDir = FileUtils.getDir("TmpD", [], true);
- let dir1 = newDirectory();
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.download.lastDir");
- dir1.remove(true);
- });
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let gDownloadLastDir = new DownloadLastDir(win);
- is(typeof gDownloadLastDir, "object",
- "gDownloadLastDir should be a valid object");
- is(gDownloadLastDir.file, null,
- "gDownloadLastDir.file should be null to start with");
-
- gDownloadLastDir.file = tmpDir;
- is(gDownloadLastDir.file.path, tmpDir.path,
- "LastDir should point to the temporary directory");
- isnot(gDownloadLastDir.file, tmpDir,
- "gDownloadLastDir.file should not be pointing to the tmpDir");
-
- gDownloadLastDir.file = 1; // not an nsIFile
- is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null");
-
- gDownloadLastDir.file = tmpDir;
- clearHistory();
- is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null");
-
- gDownloadLastDir.file = tmpDir;
- yield BrowserTestUtils.closeWindow(win);
-
- info("Opening the first private window");
- yield testHelper({ private: true, expectedDir: tmpDir });
- info("Opening a non-private window");
- yield testHelper({ private: false, expectedDir: tmpDir });
- info("Opening a private window and setting download directory");
- yield testHelper({ private: true, setDir: dir1, expectedDir: dir1 });
- info("Opening a non-private window and checking download directory");
- yield testHelper({ private: false, expectedDir: tmpDir });
- info("Opening private window and clearing history");
- yield testHelper({ private: true, clearHistory: true, expectedDir: null });
- info("Opening a non-private window and checking download directory");
- yield testHelper({ private: true, expectedDir: null });
-});
-
-/**
- * Opens a new window and performs some test actions on it based
- * on the options object that have been passed in.
- *
- * @param options (Object)
- * An object with the following properties:
- *
- * clearHistory (bool, optional):
- * Whether or not to simulate clearing session history.
- * Defaults to false.
- *
- * setDir (nsIFile, optional):
- * An nsIFile for setting the last download directory.
- * If not set, the load download directory is not changed.
- *
- * expectedDir (nsIFile, expectedDir):
- * An nsIFile for what we expect the last download directory
- * should be. The nsIFile is not compared directly - only
- * paths are compared. If expectedDir is not set, then the
- * last download directory is expected to be null.
- *
- * @returns Promise
- */
-function testHelper(options) {
- return new Task.spawn(function() {
- let win = yield BrowserTestUtils.openNewBrowserWindow(options);
- let gDownloadLastDir = new DownloadLastDir(win);
-
- if (options.clearHistory) {
- clearHistory();
- }
-
- if (options.setDir) {
- gDownloadLastDir.file = options.setDir;
- }
-
- let expectedDir = options.expectedDir;
-
- if (expectedDir) {
- is(gDownloadLastDir.file.path, expectedDir.path,
- "gDownloadLastDir should point to the expected last directory");
- isnot(gDownloadLastDir.file, expectedDir,
- "gDownloadLastDir.file should not be pointing to the last directory");
- } else {
- is(gDownloadLastDir.file, null, "gDownloadLastDir should be null");
- }
-
- gDownloadLastDir.cleanupPrivateFile();
- yield BrowserTestUtils.closeWindow(win);
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js
deleted file mode 100644
index 86f714082..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js
+++ /dev/null
@@ -1,293 +0,0 @@
-/* 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/. */
-
-// This test make sure that the favicon of the private browsing is isolated.
-
-const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
-
-const TEST_SITE = "http://mochi.test:8888";
-const TEST_CACHE_SITE = "http://www.example.com";
-const TEST_DIRECTORY = "/browser/browser/components/privatebrowsing/test/browser/";
-
-const TEST_PAGE = TEST_SITE + TEST_DIRECTORY + "file_favicon.html";
-const TEST_CACHE_PAGE = TEST_CACHE_SITE + TEST_DIRECTORY + "file_favicon.html";
-const FAVICON_URI = TEST_SITE + TEST_DIRECTORY + "file_favicon.png";
-const FAVICON_CACHE_URI = TEST_CACHE_SITE + TEST_DIRECTORY + "file_favicon.png";
-
-let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
-let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI;
-
-function clearAllImageCaches() {
- let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"]
- .getService(SpecialPowers.Ci.imgITools);
- let imageCache = tools.getImgCacheForDocument(window.document);
- imageCache.clearCache(true); // true=chrome
- imageCache.clearCache(false); // false=content
-}
-
-function clearAllPlacesFavicons() {
- let faviconService = Cc["@mozilla.org/browser/favicon-service;1"]
- .getService(Ci.nsIFaviconService);
-
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- if (aTopic === "places-favicons-expired") {
- resolve();
- Services.obs.removeObserver(observer, "places-favicons-expired", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "places-favicons-expired", false);
- faviconService.expireAllFavicons();
- });
-}
-
-function observeFavicon(aIsPrivate, aExpectedCookie, aPageURI) {
- let faviconReqXUL = false;
- let faviconReqPlaces = false;
- let attr = {};
-
- if (aIsPrivate) {
- attr.privateBrowsingId = 1;
- }
-
- let expectedPrincipal = Services.scriptSecurityManager
- .createCodebasePrincipal(aPageURI, attr);
-
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- // Make sure that the topic is 'http-on-modify-request'.
- if (aTopic === "http-on-modify-request") {
- // We check the privateBrowsingId for the originAttributes of the loading
- // channel. All requests for the favicon should contain the correct
- // privateBrowsingId. There are two requests for a favicon loading, one
- // from the Places library and one from the XUL image. The difference
- // of them is the loading principal. The Places will use the content
- // principal and the XUL image will use the system principal.
-
- let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
- let reqLoadInfo = httpChannel.loadInfo;
- let loadingPrincipal = reqLoadInfo.loadingPrincipal;
- let triggeringPrincipal = reqLoadInfo.triggeringPrincipal;
-
- // Make sure this is a favicon request.
- if (httpChannel.URI.spec !== FAVICON_URI) {
- return;
- }
-
- // Check the privateBrowsingId.
- if (aIsPrivate) {
- is(reqLoadInfo.originAttributes.privateBrowsingId, 1, "The loadInfo has correct privateBrowsingId");
- } else {
- is(reqLoadInfo.originAttributes.privateBrowsingId, 0, "The loadInfo has correct privateBrowsingId");
- }
-
- if (loadingPrincipal.equals(systemPrincipal)) {
- faviconReqXUL = true;
- ok(triggeringPrincipal.equals(expectedPrincipal),
- "The triggeringPrincipal of favicon loading from XUL should be the content principal.");
- } else {
- faviconReqPlaces = true;
- ok(loadingPrincipal.equals(expectedPrincipal),
- "The loadingPrincipal of favicon loading from Places should be the content prinicpal");
- }
-
- let faviconCookie = httpChannel.getRequestHeader("cookie");
-
- is(faviconCookie, aExpectedCookie, "The cookie of the favicon loading is correct.");
- } else {
- ok(false, "Received unexpected topic: ", aTopic);
- }
-
- if (faviconReqXUL && faviconReqPlaces) {
- resolve();
- Services.obs.removeObserver(observer, "http-on-modify-request", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "http-on-modify-request", false);
- });
-}
-
-function waitOnFaviconResponse(aFaviconURL) {
- return new Promise(resolve => {
- let observer = {
- observe(aSubject, aTopic, aData) {
- if (aTopic === "http-on-examine-response" ||
- aTopic === "http-on-examine-cached-response") {
-
- let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
- let loadInfo = httpChannel.loadInfo;
-
- if (httpChannel.URI.spec !== aFaviconURL) {
- return;
- }
-
- let result = {
- topic: aTopic,
- privateBrowsingId: loadInfo.originAttributes.privateBrowsingId
- };
-
- resolve(result);
- Services.obs.removeObserver(observer, "http-on-examine-response", false);
- Services.obs.removeObserver(observer, "http-on-examine-cached-response", false);
- }
- }
- };
-
- Services.obs.addObserver(observer, "http-on-examine-response", false);
- Services.obs.addObserver(observer, "http-on-examine-cached-response", false);
- });
-}
-
-function waitOnFaviconLoaded(aFaviconURL) {
- return new Promise(resolve => {
- let observer = {
- onPageChanged(uri, attr, value, id) {
-
- if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON &&
- value === aFaviconURL) {
- resolve();
- PlacesUtils.history.removeObserver(observer, false);
- }
- },
- };
-
- PlacesUtils.history.addObserver(observer, false);
- });
-}
-
-function* assignCookies(aBrowser, aURL, aCookieValue){
- let tabInfo = yield openTab(aBrowser, aURL);
-
- yield ContentTask.spawn(tabInfo.browser, aCookieValue, function* (value) {
- content.document.cookie = value;
- });
-
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-}
-
-function* openTab(aBrowser, aURL) {
- let tab = aBrowser.addTab(aURL);
-
- // Select tab and make sure its browser is focused.
- aBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = aBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return {tab, browser};
-}
-
-// A clean up function to prevent affecting other tests.
-registerCleanupFunction(() => {
- // Clear all cookies.
- let cookieMgr = Cc["@mozilla.org/cookiemanager;1"]
- .getService(Ci.nsICookieManager);
- cookieMgr.removeAll();
-
- // Clear all image caches and network caches.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-});
-
-add_task(function* test_favicon_privateBrowsing() {
- // Clear all image caches before running the test.
- clearAllImageCaches();
-
- // Clear all favicons in Places.
- yield clearAllPlacesFavicons();
-
- // Create a private browsing window.
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- let pageURI = makeURI(TEST_PAGE);
-
- // Generate two random cookies for non-private window and private window
- // respectively.
- let cookies = [];
- cookies.push(Math.random().toString());
- cookies.push(Math.random().toString());
-
- // Open a tab in private window and add a cookie into it.
- yield assignCookies(privateWindow.gBrowser, TEST_SITE, cookies[0]);
-
- // Open a tab in non-private window and add a cookie into it.
- yield assignCookies(gBrowser, TEST_SITE, cookies[1]);
-
- // Add the observer earlier in case we don't capture events in time.
- let promiseObserveFavicon = observeFavicon(true, cookies[0], pageURI);
-
- // Open a tab for the private window.
- let tabInfo = yield openTab(privateWindow.gBrowser, TEST_PAGE);
-
- // Waiting until favicon requests are all made.
- yield promiseObserveFavicon;
-
- // Close the tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
-
- // Add the observer earlier in case we don't capture events in time.
- promiseObserveFavicon = observeFavicon(false, cookies[1], pageURI);
-
- // Open a tab for the non-private window.
- tabInfo = yield openTab(gBrowser, TEST_PAGE);
-
- // Waiting until favicon requests are all made.
- yield promiseObserveFavicon;
-
- // Close the tab.
- yield BrowserTestUtils.removeTab(tabInfo.tab);
- yield BrowserTestUtils.closeWindow(privateWindow);
-});
-
-add_task(function* test_favicon_cache_privateBrowsing() {
- // Clear all image cahces and network cache before running the test.
- clearAllImageCaches();
-
- let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- networkCache.clear();
-
- // Clear all favicons in Places.
- yield clearAllPlacesFavicons();
-
- // Add an observer for making sure the favicon has been loaded and cached.
- let promiseFaviconLoaded = waitOnFaviconLoaded(FAVICON_CACHE_URI);
-
- // Open a tab for the non-private window.
- let tabInfoNonPrivate = yield openTab(gBrowser, TEST_CACHE_PAGE);
-
- let response = yield waitOnFaviconResponse(FAVICON_CACHE_URI);
-
- yield promiseFaviconLoaded;
-
- // Check that the favicon response has come from the network and it has the
- // correct privateBrowsingId.
- is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network.");
- is(response.privateBrowsingId, 0, "We should observe the network response for the non-private tab.");
-
- // Create a private browsing window.
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
-
- // Open a tab for the private window.
- let tabInfoPrivate = yield openTab(privateWindow.gBrowser, TEST_CACHE_PAGE);
-
- // Wait for the favicon response of the private tab.
- response = yield waitOnFaviconResponse(FAVICON_CACHE_URI);
-
- // Make sure the favicon is loaded through the network and its privateBrowsingId is correct.
- is(response.topic, "http-on-examine-response", "The favicon image should be loaded through the network again.");
- is(response.privateBrowsingId, 1, "We should observe the network response for the private tab.");
-
- yield BrowserTestUtils.removeTab(tabInfoPrivate.tab);
- yield BrowserTestUtils.removeTab(tabInfoNonPrivate.tab);
- yield BrowserTestUtils.closeWindow(privateWindow);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js
deleted file mode 100644
index 3a078ffc1..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the geolocation prompt does not show a remember
-// control inside the private browsing mode.
-
-add_task(function* test() {
- const testPageURL = "http://mochi.test:8888/browser/" +
- "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html";
-
- function checkGeolocation(aPrivateMode, aWindow) {
- return Task.spawn(function* () {
- aWindow.gBrowser.selectedTab = aWindow.gBrowser.addTab(testPageURL);
- yield BrowserTestUtils.browserLoaded(aWindow.gBrowser.selectedBrowser);
-
- let notification = aWindow.PopupNotifications.getNotification("geolocation");
-
- // Wait until the notification is available.
- while (!notification){
- yield new Promise(resolve => { executeSoon(resolve); });
- let notification = aWindow.PopupNotifications.getNotification("geolocation");
- }
-
- if (aPrivateMode) {
- // Make sure the notification is correctly displayed without a remember control
- is(notification.secondaryActions.length, 0, "Secondary actions shouldn't exist (always/never remember)");
- } else {
- ok(notification.secondaryActions.length > 1, "Secondary actions should exist (always/never remember)");
- }
- notification.remove();
-
- aWindow.gBrowser.removeCurrentTab();
- });
- };
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let browser = win.gBrowser.selectedBrowser;
- browser.loadURI(testPageURL);
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield checkGeolocation(false, win);
-
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let privateBrowser = privateWin.gBrowser.selectedBrowser;
- privateBrowser.loadURI(testPageURL);
- yield BrowserTestUtils.browserLoaded(privateBrowser);
-
- yield checkGeolocation(true, privateWin);
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(privateWin);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html
deleted file mode 100644
index 36d5e3cec..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <title>Geolocation invoker</title>
- </head>
- <body>
- <script type="text/javascript">
- navigator.geolocation.getCurrentPosition(function (pos) {
- // ignore
- });
- </script>
- </body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js
deleted file mode 100644
index dbe8ed060..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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/. */
-
-function test() {
- // We need to open a new window for this so that its docshell would get destroyed
- // when clearing the PB mode flag.
- function runTest(aCloseWindow, aCallback) {
- let newWin = OpenBrowserWindow({private: true});
- SimpleTest.waitForFocus(function() {
- let expectedExiting = true;
- let expectedExited = false;
- let observerExiting = {
- observe: function(aSubject, aTopic, aData) {
- is(aTopic, "last-pb-context-exiting", "Correct topic should be dispatched (exiting)");
- is(expectedExiting, true, "notification not expected yet (exiting)");
- expectedExited = true;
- Services.obs.removeObserver(observerExiting, "last-pb-context-exiting");
- }
- };
- let observerExited = {
- observe: function(aSubject, aTopic, aData) {
- is(aTopic, "last-pb-context-exited", "Correct topic should be dispatched (exited)");
- is(expectedExited, true, "notification not expected yet (exited)");
- Services.obs.removeObserver(observerExited, "last-pb-context-exited");
- aCallback();
- }
- };
- Services.obs.addObserver(observerExiting, "last-pb-context-exiting", false);
- Services.obs.addObserver(observerExited, "last-pb-context-exited", false);
- expectedExiting = true;
- aCloseWindow(newWin);
- newWin = null;
- SpecialPowers.forceGC();
- }, newWin);
- }
-
- waitForExplicitFinish();
-
- runTest(function(newWin) {
- // Simulate pressing the window close button
- newWin.document.getElementById("cmd_closeWindow").doCommand();
- }, function () {
- runTest(function(newWin) {
- // Simulate closing the last tab
- newWin.document.getElementById("cmd_close").doCommand();
- }, finish);
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js
deleted file mode 100644
index acccb5e2d..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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/. */
-
- add_task(function test() {
- requestLongerTimeout(2);
- const page1 = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/' +
- 'browser_privatebrowsing_localStorage_page1.html'
-
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- let tab = win.gBrowser.selectedTab = win.gBrowser.addTab(page1);
- let browser = win.gBrowser.selectedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- browser.loadURI(
- 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/' +
- 'browser_privatebrowsing_localStorage_page2.html');
- yield BrowserTestUtils.browserLoaded(browser);
-
- is(browser.contentTitle, '2', "localStorage should contain 2 items");
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(win);
- });
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js
deleted file mode 100644
index 3bcb6e5c9..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* 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/. */
-
-// Ensure that a storage instance used by both private and public sessions at different times does not
-// allow any data to leak due to cached values.
-
-// Step 1: Load browser_privatebrowsing_localStorage_before_after_page.html in a private tab, causing a storage
-// item to exist. Close the tab.
-// Step 2: Load the same page in a non-private tab, ensuring that the storage instance reports only one item
-// existing.
-
-add_task(function test() {
- let testURI = "about:blank";
- let prefix = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/';
-
- // Step 1.
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let privateBrowser = privateWin.gBrowser.addTab(
- prefix + 'browser_privatebrowsing_localStorage_before_after_page.html').linkedBrowser;
- yield BrowserTestUtils.browserLoaded(privateBrowser);
-
- is(privateBrowser.contentTitle, '1', "localStorage should contain 1 item");
-
- // Step 2.
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let browser = win.gBrowser.addTab(
- prefix + 'browser_privatebrowsing_localStorage_before_after_page2.html').linkedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- is(browser.contentTitle, 'null|0', 'localStorage should contain 0 items');
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(privateWin);
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html
deleted file mode 100644
index 143fea4e7..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<script type="text/javascript">
- localStorage.clear();
- localStorage.setItem('zzztest', 'zzzvalue');
- document.title = localStorage.length;
-</script>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html
deleted file mode 100644
index 9a7e2da63..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<script type="text/javascript">
- document.title = localStorage.getItem('zzztest', 'zzzvalue') + '|' + localStorage.length;
- localStorage.clear();
-</script>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html
deleted file mode 100644
index 3e79a01bf..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<script type="text/javascript">
- localStorage.clear();
- localStorage.setItem('test1', 'value1');
-</script>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html
deleted file mode 100644
index 8c9b28fd8..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<script type="text/javascript">
- localStorage.setItem('test2', 'value2');
- document.title = localStorage.length;
-</script>
-</head>
-<body>
-</body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js
deleted file mode 100644
index b09ec0368..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * Tests that a popup window in private browsing window opens
- * new tab links in the original private browsing window as
- * new tabs.
- *
- * This is a regression test for bug 1202634.
- */
-
-// We're able to sidestep some quote-escaping issues when
-// nesting data URI's by encoding the second data URI in
-// base64.
-const POPUP_BODY_BASE64 = btoa(`<a href="http://example.com/" target="_blank"
- id="second">
- Now click this
- </a>`);
-const POPUP_LINK = `data:text/html;charset=utf-8;base64,${POPUP_BODY_BASE64}`;
-const WINDOW_BODY = `data:text/html,
- <a href="%23" id="first"
- onclick="window.open('${POPUP_LINK}', '_blank',
- 'width=630,height=500')">
- First click this.
- </a>`;
-
-add_task(function* test_private_popup_window_opens_private_tabs() {
- let privWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
-
- // Sanity check - this browser better be private.
- ok(PrivateBrowsingUtils.isWindowPrivate(privWin),
- "Opened a private browsing window.");
-
- // First, open a private browsing window, and load our
- // testing page.
- let privBrowser = privWin.gBrowser.selectedBrowser;
- yield BrowserTestUtils.loadURI(privBrowser, WINDOW_BODY);
- yield BrowserTestUtils.browserLoaded(privBrowser);
-
- // Next, click on the link in the testing page, and ensure
- // that a private popup window is opened.
- let openedPromise = BrowserTestUtils.waitForNewWindow(true, POPUP_LINK);
-
- yield BrowserTestUtils.synthesizeMouseAtCenter("#first", {}, privBrowser);
- let popupWin = yield openedPromise;
- ok(PrivateBrowsingUtils.isWindowPrivate(popupWin),
- "Popup window was private.");
-
- // Now click on the link in the popup, and ensure that a new
- // tab is opened in the original private browsing window.
- let newTabPromise = BrowserTestUtils.waitForNewTab(privWin.gBrowser);
- let popupBrowser = popupWin.gBrowser.selectedBrowser;
- yield BrowserTestUtils.synthesizeMouseAtCenter("#second", {}, popupBrowser);
- let newPrivTab = yield newTabPromise;
-
- // Ensure that the newly created tab's browser is private.
- ok(PrivateBrowsingUtils.isBrowserPrivate(newPrivTab.linkedBrowser),
- "Newly opened tab should be private.");
-
- // Clean up
- yield BrowserTestUtils.removeTab(newPrivTab);
- yield BrowserTestUtils.closeWindow(popupWin);
- yield BrowserTestUtils.closeWindow(privWin);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js
deleted file mode 100644
index ae6e8a6a3..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js
+++ /dev/null
@@ -1,23 +0,0 @@
-"use strict";
-
-/**
- * Tests that if we open a tab within a private browsing window, and then
- * close that private browsing window, that subsequent private browsing
- * windows do not allow the command for restoring the last session.
- */
-add_task(function* test_no_session_restore_menu_option() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- ok(true, "The first private window got loaded");
- win.gBrowser.addTab("about:mozilla");
- yield BrowserTestUtils.closeWindow(win);
-
- win = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- let srCommand = win.document.getElementById("Browser:RestoreLastSession");
- ok(srCommand, "The Session Restore command should exist");
- is(PrivateBrowsingUtils.isWindowPrivate(win), true,
- "PrivateBrowsingUtils should report the correct per-window private browsing status");
- is(srCommand.hasAttribute("disabled"), true,
- "The Session Restore command should be disabled in private browsing mode");
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js
deleted file mode 100644
index d2a69dd4e..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js
+++ /dev/null
@@ -1,19 +0,0 @@
-"use strict";
-
-/**
- * Tests that we fire the last-pb-context-exited observer notification
- * when the last private browsing window closes, even if a chrome window
- * was opened from that private browsing window.
- */
-add_task(function* () {
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- let chromeWin = win.open("chrome://browser/content/places/places.xul", "_blank",
- "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
- yield BrowserTestUtils.waitForEvent(chromeWin, "load");
- let obsPromise = TestUtils.topicObserved("last-pb-context-exited");
- yield BrowserTestUtils.closeWindow(win);
- yield obsPromise;
- Assert.ok(true, "Got the last-pb-context-exited notification");
- chromeWin.close();
-});
-
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js
deleted file mode 100644
index 0b1369b11..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the last open directory used inside the private
-// browsing mode is not remembered after leaving that mode.
-
-var windowsToClose = [];
-function testOnWindow(options, callback) {
- var win = OpenBrowserWindow(options);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- windowsToClose.push(win);
- callback(win);
- }, false);
-}
-
-registerCleanupFunction(function() {
- windowsToClose.forEach(function(win) {
- win.close();
- });
-});
-
-function test() {
- // initialization
- waitForExplicitFinish();
- let ds = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
- let dir1 = ds.get("ProfD", Ci.nsIFile);
- let dir2 = ds.get("TmpD", Ci.nsIFile);
- let file = dir2.clone();
- file.append("pbtest.file");
- file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
-
- const kPrefName = "browser.open.lastDir";
-
- function setupCleanSlate(win) {
- win.gLastOpenDirectory.reset();
- gPrefService.clearUserPref(kPrefName);
- }
-
- setupCleanSlate(window);
-
- // open one regular and one private window
- testOnWindow(undefined, function(nonPrivateWindow) {
- setupCleanSlate(nonPrivateWindow);
- testOnWindow({private: true}, function(privateWindow) {
- setupCleanSlate(privateWindow);
-
- // Test 1: general workflow test
-
- // initial checks
- ok(!nonPrivateWindow.gLastOpenDirectory.path,
- "Last open directory path should be initially empty");
- nonPrivateWindow.gLastOpenDirectory.path = dir2;
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir2.path,
- "The path should be successfully set");
- nonPrivateWindow.gLastOpenDirectory.path = null;
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir2.path,
- "The path should be not change when assigning it to null");
- nonPrivateWindow.gLastOpenDirectory.path = dir1;
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The path should be successfully outside of the private browsing mode");
-
- // test the private window
- is(privateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The path should not change when entering the private browsing mode");
- privateWindow.gLastOpenDirectory.path = dir2;
- is(privateWindow.gLastOpenDirectory.path.path, dir2.path,
- "The path should successfully change inside the private browsing mode");
-
- // test the non-private window
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The path should be reset to the same path as before entering the private browsing mode");
-
- setupCleanSlate(nonPrivateWindow);
- setupCleanSlate(privateWindow);
-
- // Test 2: the user first tries to open a file inside the private browsing mode
-
- // test the private window
- ok(!privateWindow.gLastOpenDirectory.path,
- "No original path should exist inside the private browsing mode");
- privateWindow.gLastOpenDirectory.path = dir1;
- is(privateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The path should be successfully set inside the private browsing mode");
- // test the non-private window
- ok(!nonPrivateWindow.gLastOpenDirectory.path,
- "The path set inside the private browsing mode should not leak when leaving that mode");
-
- setupCleanSlate(nonPrivateWindow);
- setupCleanSlate(privateWindow);
-
- // Test 3: the last open directory is set from a previous session, it should be used
- // in normal mode
-
- gPrefService.setComplexValue(kPrefName, Ci.nsILocalFile, dir1);
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The pref set from last session should take effect outside the private browsing mode");
-
- setupCleanSlate(nonPrivateWindow);
- setupCleanSlate(privateWindow);
-
- // Test 4: the last open directory is set from a previous session, it should be used
- // in private browsing mode mode
-
- gPrefService.setComplexValue(kPrefName, Ci.nsILocalFile, dir1);
- // test the private window
- is(privateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The pref set from last session should take effect inside the private browsing mode");
- // test the non-private window
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path,
- "The pref set from last session should remain in effect after leaving the private browsing mode");
-
- setupCleanSlate(nonPrivateWindow);
- setupCleanSlate(privateWindow);
-
- // Test 5: setting the path to a file shouldn't work
-
- nonPrivateWindow.gLastOpenDirectory.path = file;
- ok(!nonPrivateWindow.gLastOpenDirectory.path,
- "Setting the path to a file shouldn't work when it's originally null");
- nonPrivateWindow.gLastOpenDirectory.path = dir1;
- nonPrivateWindow.gLastOpenDirectory.path = file;
- is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path,
- "Setting the path to a file shouldn't work when it's not originally null");
-
- // cleanup
- file.remove(false);
- finish();
- });
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html
deleted file mode 100644
index f5bb3212f..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <title>Title 1</title>
- </head>
- <body>
- </body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js
deleted file mode 100644
index 32436b3cc..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* 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/. */
-
-// Test to make sure that the visited page titles do not get updated inside the
-// private browsing mode.
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-add_task(function* test() {
- const TEST_URL = "http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html"
- const TEST_URI = Services.io.newURI(TEST_URL, null, null);
- const TITLE_1 = "Title 1";
- const TITLE_2 = "Title 2";
-
- function waitForTitleChanged() {
- return new Promise(resolve => {
- let historyObserver = {
- onTitleChanged: function(uri, pageTitle) {
- PlacesUtils.history.removeObserver(historyObserver, false);
- resolve({uri: uri, pageTitle: pageTitle});
- },
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function() {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
-
- PlacesUtils.history.addObserver(historyObserver, false);
- });
- };
-
- yield PlacesTestUtils.clearHistory();
-
- let tabToClose = gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
- yield waitForTitleChanged();
- is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_1, "The title matches the orignal title after first visit");
-
- let place = {
- uri: TEST_URI,
- title: TITLE_2,
- visits: [{
- visitDate: Date.now() * 1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK
- }]
- };
- PlacesUtils.asyncHistory.updatePlaces(place, {
- handleError: () => ok(false, "Unexpected error in adding visit."),
- handleResult: function () { },
- handleCompletion: function () {}
- });
-
- yield waitForTitleChanged();
- is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_2, "The title matches the updated title after updating visit");
-
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private:true});
- yield BrowserTestUtils.browserLoaded(privateWin.gBrowser.addTab(TEST_URL).linkedBrowser);
-
- is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_2, "The title remains the same after visiting in private window");
- yield PlacesTestUtils.clearHistory();
-
- // Cleanup
- BrowserTestUtils.closeWindow(privateWin);
- gBrowser.removeTab(tabToClose);
-});
-
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js
deleted file mode 100644
index a70019976..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the title of existing history entries does not
-// change inside a private window.
-
-add_task(function* test() {
- const TEST_URL = "http://mochi.test:8888/browser/browser/components/" +
- "privatebrowsing/test/browser/title.sjs";
- let cm = Services.cookies;
-
- function cleanup() {
- // delete all cookies
- cm.removeAll();
- // delete all history items
- return PlacesTestUtils.clearHistory();
- }
-
- yield cleanup();
-
- let deferredFirst = PromiseUtils.defer();
- let deferredSecond = PromiseUtils.defer();
- let deferredThird = PromiseUtils.defer();
-
- let testNumber = 0;
- let historyObserver = {
- onTitleChanged: function(aURI, aPageTitle) {
- if (aURI.spec != TEST_URL)
- return;
- switch (++testNumber) {
- case 1:
- // The first time that the page is loaded
- deferredFirst.resolve(aPageTitle);
- break;
- case 2:
- // The second time that the page is loaded
- deferredSecond.resolve(aPageTitle);
- break;
- case 3:
- // After clean up
- deferredThird.resolve(aPageTitle);
- break;
- default:
- // Checks that opening the page in a private window should not fire a
- // title change.
- ok(false, "Title changed. Unexpected pass: " + testNumber);
- }
- },
-
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function() {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL);
- let aPageTitle = yield deferredFirst.promise;
- // The first time that the page is loaded
- is(aPageTitle, "No Cookie",
- "The page should be loaded without any cookie for the first time");
-
- win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL);
- aPageTitle = yield deferredSecond.promise;
- // The second time that the page is loaded
- is(aPageTitle, "Cookie",
- "The page should be loaded with a cookie for the second time");
-
- yield cleanup();
-
- win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL);
- aPageTitle = yield deferredThird.promise;
- // After clean up
- is(aPageTitle, "No Cookie",
- "The page should be loaded without any cookie again");
-
- let win2 = yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- let private_tab = win2.gBrowser.addTab(TEST_URL);
- win2.gBrowser.selectedTab = private_tab;
- yield BrowserTestUtils.browserLoaded(private_tab.linkedBrowser);
-
- // Cleanup
- yield cleanup();
- PlacesUtils.history.removeObserver(historyObserver);
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(win2);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js
deleted file mode 100644
index 71d85f296..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 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/. */
-
-// This test makes sure that private browsing mode disables the remember option
-// for the popup blocker menu.
-add_task(function* test() {
- let testURI = "http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/popup.html";
- let oldPopupPolicy = gPrefService.getBoolPref("dom.disable_open_during_load");
- gPrefService.setBoolPref("dom.disable_open_during_load", true);
-
- registerCleanupFunction(() => {
- gPrefService.setBoolPref("dom.disable_open_during_load", oldPopupPolicy);
- });
-
- function testPopupBlockerMenuItem(aExpectedDisabled, aWindow, aCallback) {
-
- aWindow.gBrowser.addEventListener("DOMUpdatePageReport", function() {
- aWindow.gBrowser.removeEventListener("DOMUpdatePageReport", arguments.callee, false);
-
- executeSoon(function() {
- let notification = aWindow.gBrowser.getNotificationBox().getNotificationWithValue("popup-blocked");
- ok(notification, "The notification box should be displayed");
-
- function checkMenuItem(callback) {
- dump("CMI: in\n");
- aWindow.document.addEventListener("popupshown", function(event) {
- dump("CMI: popupshown\n");
- aWindow.document.removeEventListener("popupshown", arguments.callee, false);
-
- if (aExpectedDisabled)
- is(aWindow.document.getElementById("blockedPopupAllowSite").getAttribute("disabled"), "true",
- "The allow popups menu item should be disabled");
-
- event.originalTarget.hidePopup();
- dump("CMI: calling back\n");
- callback();
- dump("CMI: called back\n");
- }, false);
- dump("CMI: out\n");
- }
-
- checkMenuItem(function() {
- aCallback();
- });
- notification.querySelector("button").doCommand();
- });
-
- }, false);
-
- aWindow.gBrowser.selectedBrowser.loadURI(testURI);
- }
-
- let win1 = yield BrowserTestUtils.openNewBrowserWindow();
- yield new Promise(resolve => waitForFocus(resolve, win1));
- yield new Promise(resolve => testPopupBlockerMenuItem(false, win1, resolve));
-
- let win2 = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield new Promise(resolve => waitForFocus(resolve, win2));
- yield new Promise(resolve => testPopupBlockerMenuItem(true, win2, resolve));
-
- let win3 = yield BrowserTestUtils.openNewBrowserWindow();
- yield new Promise(resolve => waitForFocus(resolve, win3));
- yield new Promise(resolve => testPopupBlockerMenuItem(false, win3, resolve));
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(win1);
- yield BrowserTestUtils.closeWindow(win2);
- yield BrowserTestUtils.closeWindow(win3);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js
deleted file mode 100644
index fe69a2234..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the web pages can't register protocol handlers
-// inside the private browsing mode.
-
-add_task(function* test() {
- let notificationValue = "Protocol Registration: testprotocol";
- let testURI = "http://example.com/browser/" +
- "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html";
-
- let doTest = Task.async(function* (aIsPrivateMode, aWindow) {
- let tab = aWindow.gBrowser.selectedTab = aWindow.gBrowser.addTab(testURI);
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- let promiseFinished = PromiseUtils.defer();
- setTimeout(function() {
- let notificationBox = aWindow.gBrowser.getNotificationBox();
- let notification = notificationBox.getNotificationWithValue(notificationValue);
-
- if (aIsPrivateMode) {
- // Make sure the notification is correctly displayed without a remember control
- ok(!notification, "Notification box should not be displayed inside of private browsing mode");
- } else {
- // Make sure the notification is correctly displayed with a remember control
- ok(notification, "Notification box should be displaying outside of private browsing mode");
- }
-
- promiseFinished.resolve();
- }, 100); // remember control is added in a setTimeout(0) call
-
- yield promiseFinished.promise;
- });
-
- // test first when not on private mode
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield doTest(false, win);
-
- // then test when on private mode
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield doTest(true, privateWin);
-
- // Cleanup
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(privateWin);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html
deleted file mode 100644
index 74f846d54..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <title>Protocol registrar page</title>
- </head>
- <body>
- <script type="text/javascript">
- navigator.registerProtocolHandler("testprotocol",
- "https://example.com/foobar?uri=%s",
- "Test Protocol");
- </script>
- </body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js
deleted file mode 100644
index dbd74029d..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/* 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/. */
-
-// This test makes sure that Sidebars do not migrate across windows with
-// different privacy states
-
-// See Bug 885054: https://bugzilla.mozilla.org/show_bug.cgi?id=885054
-
-function test() {
- waitForExplicitFinish();
-
- let { utils: Cu } = Components;
-
- let { Promise: { defer } } = Cu.import("resource://gre/modules/Promise.jsm", {});
-
- // opens a sidebar
- function openSidebar(win) {
- let { promise, resolve } = defer();
- let doc = win.document;
-
- let sidebarID = 'viewBookmarksSidebar';
-
- let sidebar = doc.getElementById('sidebar');
-
- let sidebarurl = doc.getElementById(sidebarID).getAttribute('sidebarurl');
-
- sidebar.addEventListener('load', function onSidebarLoad() {
- if (sidebar.contentWindow.location.href != sidebarurl)
- return;
- sidebar.removeEventListener('load', onSidebarLoad, true);
-
- resolve(win);
- }, true);
-
- win.SidebarUI.show(sidebarID);
-
- return promise;
- }
-
- let windowCache = [];
- function cacheWindow(w) {
- windowCache.push(w);
- return w;
- }
- function closeCachedWindows () {
- windowCache.forEach(w => w.close());
- }
-
- // Part 1: NON PRIVATE WINDOW -> PRIVATE WINDOW
- openWindow(window, {}, 1).
- then(cacheWindow).
- then(openSidebar).
- then(win => openWindow(win, { private: true })).
- then(cacheWindow).
- then(function({ document }) {
- let sidebarBox = document.getElementById("sidebar-box");
- is(sidebarBox.hidden, true, 'Opening a private window from reg window does not open the sidebar');
- }).
- // Part 2: NON PRIVATE WINDOW -> NON PRIVATE WINDOW
- then(() => openWindow(window)).
- then(cacheWindow).
- then(openSidebar).
- then(win => openWindow(win)).
- then(cacheWindow).
- then(function({ document }) {
- let sidebarBox = document.getElementById("sidebar-box");
- is(sidebarBox.hidden, false, 'Opening a reg window from reg window does open the sidebar');
- }).
- // Part 3: PRIVATE WINDOW -> NON PRIVATE WINDOW
- then(() => openWindow(window, { private: true })).
- then(cacheWindow).
- then(openSidebar).
- then(win => openWindow(win)).
- then(cacheWindow).
- then(function({ document }) {
- let sidebarBox = document.getElementById("sidebar-box");
- is(sidebarBox.hidden, true, 'Opening a reg window from a private window does not open the sidebar');
- }).
- // Part 4: PRIVATE WINDOW -> PRIVATE WINDOW
- then(() => openWindow(window, { private: true })).
- then(cacheWindow).
- then(openSidebar).
- then(win => openWindow(win, { private: true })).
- then(cacheWindow).
- then(function({ document }) {
- let sidebarBox = document.getElementById("sidebar-box");
- is(sidebarBox.hidden, false, 'Opening a private window from private window does open the sidebar');
- }).
- then(closeCachedWindows).
- then(finish);
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js
deleted file mode 100644
index e2b8593d6..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/. */
-
-// This test makes sure that privatebrowsingmode attribute of the window is correctly
-// adjusted based on whether the window is a private window.
-
-var windowsToClose = [];
-function testOnWindow(options, callback) {
- var win = OpenBrowserWindow(options);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- windowsToClose.push(win);
- executeSoon(() => callback(win));
- }, false);
-}
-
-registerCleanupFunction(function() {
- windowsToClose.forEach(function(win) {
- win.close();
- });
-});
-
-function test() {
- // initialization
- waitForExplicitFinish();
-
- ok(!document.documentElement.hasAttribute("privatebrowsingmode"),
- "privatebrowsingmode should not be present in normal mode");
-
- // open a private window
- testOnWindow({private: true}, function(win) {
- is(win.document.documentElement.getAttribute("privatebrowsingmode"), "temporary",
- "privatebrowsingmode should be \"temporary\" inside the private browsing mode");
-
- finish();
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js
deleted file mode 100644
index cbd2c60f8..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the gPrivateBrowsingUI object, the Private Browsing
-// menu item and its XUL <command> element work correctly.
-
-function test() {
- // initialization
- waitForExplicitFinish();
- let windowsToClose = [];
- let testURI = "about:blank";
- let pbMenuItem;
- let cmd;
-
- function doTest(aIsPrivateMode, aWindow, aCallback) {
- aWindow.gBrowser.selectedBrowser.addEventListener("load", function onLoad() {
- aWindow.gBrowser.selectedBrowser.removeEventListener("load", onLoad, true);
-
- ok(aWindow.gPrivateBrowsingUI, "The gPrivateBrowsingUI object exists");
-
- pbMenuItem = aWindow.document.getElementById("menu_newPrivateWindow");
- ok(pbMenuItem, "The Private Browsing menu item exists");
-
- cmd = aWindow.document.getElementById("Tools:PrivateBrowsing");
- isnot(cmd, null, "XUL command object for the private browsing service exists");
-
- is(pbMenuItem.getAttribute("label"), "New Private Window",
- "The Private Browsing menu item should read \"New Private Window\"");
- is(PrivateBrowsingUtils.isWindowPrivate(aWindow), aIsPrivateMode,
- "PrivateBrowsingUtils should report the correct per-window private browsing status (privateBrowsing should be " +
- aIsPrivateMode + ")");
-
- aCallback();
- }, true);
-
- aWindow.gBrowser.selectedBrowser.loadURI(testURI);
- };
-
- function openPrivateBrowsingModeByUI(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
- aSubject.addEventListener("load", function() {
- aSubject.removeEventListener("load", arguments.callee);
- Services.obs.removeObserver(observer, "domwindowopened");
- windowsToClose.push(aSubject);
- aCallback(aSubject);
- }, false);
- }, "domwindowopened", false);
-
- cmd = aWindow.document.getElementById("Tools:PrivateBrowsing");
- var func = new Function("", cmd.getAttribute("oncommand"));
- func.call(cmd);
- };
-
- function testOnWindow(aOptions, aCallback) {
- whenNewWindowLoaded(aOptions, function(aWin) {
- windowsToClose.push(aWin);
- // execute should only be called when need, like when you are opening
- // web pages on the test. If calling executeSoon() is not necesary, then
- // call whenNewWindowLoaded() instead of testOnWindow() on your test.
- executeSoon(() => aCallback(aWin));
- });
- };
-
- // this function is called after calling finish() on the test.
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- // test first when not on private mode
- testOnWindow({}, function(aWin) {
- doTest(false, aWin, function() {
- // then test when on private mode, opening a new private window from the
- // user interface.
- openPrivateBrowsingModeByUI(aWin, function(aPrivateWin) {
- doTest(true, aPrivateWin, finish);
- });
- });
- });
-}
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js
deleted file mode 100644
index 2be701bcd..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the URL bar is focused when entering the private window.
-
-"use strict";
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-let aboutNewTabService = Components.classes["@mozilla.org/browser/aboutnewtab-service;1"]
- .getService(Components.interfaces.nsIAboutNewTabService);
-
-function checkUrlbarFocus(win) {
- let urlbar = win.gURLBar;
- is(win.document.activeElement, urlbar.inputField, "URL Bar should be focused");
- is(urlbar.value, "", "URL Bar should be empty");
-}
-
-function openNewPrivateWindow() {
- let deferred = Promise.defer();
- whenNewWindowLoaded({private: true}, win => {
- executeSoon(() => deferred.resolve(win));
- });
- return deferred.promise;
-}
-
-add_task(function* () {
- let win = yield openNewPrivateWindow();
- checkUrlbarFocus(win);
- win.close();
-});
-
-add_task(function* () {
- aboutNewTabService.newTabURL = "about:blank";
- registerCleanupFunction(() => {
- aboutNewTabService.resetNewTabURL();
- });
-
- let win = yield openNewPrivateWindow();
- checkUrlbarFocus(win);
- win.close();
-
- aboutNewTabService.resetNewTabURL();
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js
deleted file mode 100644
index aca8d0c7b..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* 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/. */
-
-// This test makes sure that the window title changes correctly while switching
-// from and to private browsing mode.
-
-add_task(function test() {
- const testPageURL = "http://mochi.test:8888/browser/" +
- "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html";
- requestLongerTimeout(2);
-
- // initialization of expected titles
- let test_title = "Test title";
- let app_name = document.documentElement.getAttribute("title");
- const isOSX = ("nsILocalFileMac" in Ci);
- let page_with_title;
- let page_without_title;
- let about_pb_title;
- let pb_page_with_title;
- let pb_page_without_title;
- let pb_about_pb_title;
- if (isOSX) {
- page_with_title = test_title;
- page_without_title = app_name;
- about_pb_title = "Open a private window?";
- pb_page_with_title = test_title + " - (Private Browsing)";
- pb_page_without_title = app_name + " - (Private Browsing)";
- pb_about_pb_title = "Private Browsing - (Private Browsing)";
- }
- else {
- page_with_title = test_title + " - " + app_name;
- page_without_title = app_name;
- about_pb_title = "Open a private window?" + " - " + app_name;
- pb_page_with_title = test_title + " - " + app_name + " (Private Browsing)";
- pb_page_without_title = app_name + " (Private Browsing)";
- pb_about_pb_title = "Private Browsing - " + app_name + " (Private Browsing)";
- }
-
- function* testTabTitle(aWindow, url, insidePB, expected_title) {
- let tab = (yield BrowserTestUtils.openNewForegroundTab(aWindow.gBrowser));
- yield BrowserTestUtils.loadURI(tab.linkedBrowser, url);
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- yield BrowserTestUtils.waitForCondition(() => {
- return aWindow.document.title === expected_title;
- }, `Window title should be ${expected_title}, got ${aWindow.document.title}`);
-
- is(aWindow.document.title, expected_title, "The window title for " + url +
- " is correct (" + (insidePB ? "inside" : "outside") +
- " private browsing mode)");
-
- let win = aWindow.gBrowser.replaceTabWithWindow(tab);
- yield BrowserTestUtils.waitForEvent(win, "load", false);
-
- yield BrowserTestUtils.waitForCondition(() => {
- return win.document.title === expected_title;
- }, `Window title should be ${expected_title}, got ${aWindow.document.title}`);
-
- is(win.document.title, expected_title, "The window title for " + url +
- " detached tab is correct (" + (insidePB ? "inside" : "outside") +
- " private browsing mode)");
-
- yield Promise.all([ BrowserTestUtils.closeWindow(win),
- BrowserTestUtils.closeWindow(aWindow) ]);
- }
-
- function openWin(private) {
- return BrowserTestUtils.openNewBrowserWindow({ private });
- }
- yield Task.spawn(testTabTitle((yield openWin(false)), "about:blank", false, page_without_title));
- yield Task.spawn(testTabTitle((yield openWin(false)), testPageURL, false, page_with_title));
- yield Task.spawn(testTabTitle((yield openWin(false)), "about:privatebrowsing", false, about_pb_title));
- yield Task.spawn(testTabTitle((yield openWin(true)), "about:blank", true, pb_page_without_title));
- yield Task.spawn(testTabTitle((yield openWin(true)), testPageURL, true, pb_page_with_title));
- yield Task.spawn(testTabTitle((yield openWin(true)), "about:privatebrowsing", true, pb_about_pb_title));
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html
deleted file mode 100644
index 760bde7d1..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <title>Test title</title>
- </head>
- <body>
- Test page for the window title test
- </body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js
deleted file mode 100644
index f5afcbd61..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* 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/. */
-
-// This test makes sure that private browsing turns off doesn't cause zoom
-// settings to be reset on tab switch (bug 464962)
-
-add_task(function* test() {
- let win = (yield BrowserTestUtils.openNewBrowserWindow({ private: true }));
- let tabAbout = (yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:"));
- let tabMozilla = (yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:"));
-
- let mozillaZoom = win.ZoomManager.zoom;
-
- // change the zoom on the mozilla page
- win.FullZoom.enlarge();
- // make sure the zoom level has been changed
- isnot(win.ZoomManager.zoom, mozillaZoom, "Zoom level can be changed");
- mozillaZoom = win.ZoomManager.zoom;
-
- // switch to about: tab
- yield BrowserTestUtils.switchTab(win.gBrowser, tabAbout);
-
- // switch back to mozilla tab
- yield BrowserTestUtils.switchTab(win.gBrowser, tabMozilla);
-
- // make sure the zoom level has not changed
- is(win.ZoomManager.zoom, mozillaZoom,
- "Entering private browsing should not reset the zoom on a tab");
-
- // cleanup
- win.FullZoom.reset();
- yield Promise.all([ BrowserTestUtils.removeTab(tabMozilla),
- BrowserTestUtils.removeTab(tabAbout) ]);
-
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js
deleted file mode 100644
index b67bfc229..000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/* 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/. */
-
-// This test makes sure that about:privatebrowsing does not appear zoomed in
-// if there is already a zoom site pref for about:blank (bug 487656).
-
-add_task(function* test() {
- // initialization
- let windowsToClose = [];
- let windowsToReset = [];
-
- function promiseLocationChange() {
- return new Promise(resolve => {
- Services.obs.addObserver(function onLocationChange(subj, topic, data) {
- Services.obs.removeObserver(onLocationChange, topic);
- resolve();
- }, "browser-fullZoom:location-change", false);
- });
- }
-
- function promiseTestReady(aIsZoomedWindow, aWindow) {
- // Need to wait on two things, the ordering of which is not guaranteed:
- // (1) the page load, and (2) FullZoom's update to the new page's zoom
- // level. FullZoom broadcasts "browser-fullZoom:location-change" when its
- // update is done. (See bug 856366 for details.)
-
-
- let browser = aWindow.gBrowser.selectedBrowser;
- return BrowserTestUtils.loadURI(browser, "about:blank").then(() => {
- return Promise.all([ BrowserTestUtils.browserLoaded(browser),
- promiseLocationChange() ]);
- }).then(() => doTest(aIsZoomedWindow, aWindow));
- }
-
- function doTest(aIsZoomedWindow, aWindow) {
- if (aIsZoomedWindow) {
- is(aWindow.ZoomManager.zoom, 1,
- "Zoom level for freshly loaded about:blank should be 1");
- // change the zoom on the blank page
- aWindow.FullZoom.enlarge();
- isnot(aWindow.ZoomManager.zoom, 1, "Zoom level for about:blank should be changed");
- return;
- }
-
- // make sure the zoom level is set to 1
- is(aWindow.ZoomManager.zoom, 1, "Zoom level for about:privatebrowsing should be reset");
- }
-
- function testOnWindow(options, callback) {
- return BrowserTestUtils.openNewBrowserWindow(options).then((win) => {
- windowsToClose.push(win);
- windowsToReset.push(win);
- return win;
- });
- }
-
- yield testOnWindow({}).then(win => promiseTestReady(true, win));
- yield testOnWindow({private: true}).then(win => promiseTestReady(false, win));
-
- // cleanup
- windowsToReset.forEach((win) => win.FullZoom.reset());
- yield Promise.all(windowsToClose.map(win => BrowserTestUtils.closeWindow(win)));
-});
diff --git a/browser/components/privatebrowsing/test/browser/empty_file.html b/browser/components/privatebrowsing/test/browser/empty_file.html
deleted file mode 100644
index 42682b474..000000000
--- a/browser/components/privatebrowsing/test/browser/empty_file.html
+++ /dev/null
@@ -1 +0,0 @@
-<html><body></body></html> \ No newline at end of file
diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.html b/browser/components/privatebrowsing/test/browser/file_favicon.html
deleted file mode 100644
index b571134e1..000000000
--- a/browser/components/privatebrowsing/test/browser/file_favicon.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <meta charset='utf-8'>
- <title>Favicon Test for originAttributes</title>
- <link rel="icon" type="image/png" href="file_favicon.png" />
- </head>
- <body>
- Favicon!!
- </body>
-</html> \ No newline at end of file
diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.png b/browser/components/privatebrowsing/test/browser/file_favicon.png
deleted file mode 100644
index 5535363c9..000000000
--- a/browser/components/privatebrowsing/test/browser/file_favicon.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^ b/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^
deleted file mode 100644
index 9e23c73b7..000000000
--- a/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Cache-Control: no-cache
diff --git a/browser/components/privatebrowsing/test/browser/head.js b/browser/components/privatebrowsing/test/browser/head.js
deleted file mode 100644
index c822ba8d1..000000000
--- a/browser/components/privatebrowsing/test/browser/head.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var {PromiseUtils} = Cu.import("resource://gre/modules/PromiseUtils.jsm", {});
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-function whenNewWindowLoaded(aOptions, aCallback) {
- let win = OpenBrowserWindow(aOptions);
- let focused = SimpleTest.promiseFocus(win);
- let startupFinished = TestUtils.topicObserved("browser-delayed-startup-finished",
- subject => subject == win).then(() => win);
- Promise.all([focused, startupFinished])
- .then(results => executeSoon(() => aCallback(results[1])));
-
- return win;
-}
-
-function openWindow(aParent, aOptions, a3) {
- let { Promise: { defer } } = Components.utils.import("resource://gre/modules/Promise.jsm", {});
- let { promise, resolve } = defer();
-
- let win = aParent.OpenBrowserWindow(aOptions);
-
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- resolve(win);
- }, false);
-
- return promise;
-}
-
-function newDirectory() {
- let FileUtils =
- Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;
- let tmpDir = FileUtils.getDir("TmpD", [], true);
- let dir = tmpDir.clone();
- dir.append("testdir");
- dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- return dir;
-}
-
-function newFileInDirectory(aDir) {
- let FileUtils =
- Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;
- let file = aDir.clone();
- file.append("testfile");
- file.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_FILE);
- return file;
-}
-
-function clearHistory() {
- // simulate clearing the private data
- Services.obs.notifyObservers(null, "browser:purge-session-history", "");
-}
-
-function _initTest() {
- // Don't use about:home as the homepage for new windows
- Services.prefs.setIntPref("browser.startup.page", 0);
- registerCleanupFunction(() => Services.prefs.clearUserPref("browser.startup.page"));
-}
-
-_initTest();
diff --git a/browser/components/privatebrowsing/test/browser/popup.html b/browser/components/privatebrowsing/test/browser/popup.html
deleted file mode 100644
index 68bbbfa26..000000000
--- a/browser/components/privatebrowsing/test/browser/popup.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
- <head>
- <meta charset="utf8">
- <title>Page creating a popup</title>
- </head>
- <body>
- <script type="text/javascript">
- window.open("data:text/plain,test", "testwin");
- </script>
- </body>
-</html>
diff --git a/browser/components/privatebrowsing/test/browser/title.sjs b/browser/components/privatebrowsing/test/browser/title.sjs
deleted file mode 100644
index 568e235be..000000000
--- a/browser/components/privatebrowsing/test/browser/title.sjs
+++ /dev/null
@@ -1,22 +0,0 @@
-/* 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/. */
-
-// This provides the tests with a page with different titles based on whether
-// a cookie is present or not.
-
-function handleRequest(request, response) {
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.setHeader("Content-Type", "text/html", false);
-
- var cookie = "name=value";
- var title = "No Cookie";
- if (request.hasHeader("Cookie") && request.getHeader("Cookie") == cookie)
- title = "Cookie";
- else
- response.setHeader("Set-Cookie", cookie, false);
-
- response.write("<html><head><title>");
- response.write(title);
- response.write("</title><body>test page</body></html>");
-}
diff --git a/browser/components/safebrowsing/content/test/.eslintrc.js b/browser/components/safebrowsing/content/test/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/safebrowsing/content/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/safebrowsing/content/test/browser.ini b/browser/components/safebrowsing/content/test/browser.ini
deleted file mode 100644
index 1ce19118e..000000000
--- a/browser/components/safebrowsing/content/test/browser.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-support-files = head.js
-
-[browser_bug400731.js]
-[browser_bug415846.js]
-# Disabled on Mac because of its bizarre special-and-unique snowflake of a help menu.
-skip-if = os == "mac" || e10s # e10s: Bug 1248632
-[browser_whitelisted.js]
diff --git a/browser/components/safebrowsing/content/test/browser_bug400731.js b/browser/components/safebrowsing/content/test/browser_bug400731.js
deleted file mode 100644
index fac187753..000000000
--- a/browser/components/safebrowsing/content/test/browser_bug400731.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Check presence of the "Ignore this warning" button */
-
-function onDOMContentLoaded(callback) {
- function complete({ data }) {
- mm.removeMessageListener("Test:DOMContentLoaded", complete);
- callback(data);
- }
-
- let mm = gBrowser.selectedBrowser.messageManager;
- mm.addMessageListener("Test:DOMContentLoaded", complete);
-
- function contentScript() {
- let listener = function () {
- removeEventListener("DOMContentLoaded", listener);
-
- let button = content.document.getElementById("ignoreWarningButton");
-
- sendAsyncMessage("Test:DOMContentLoaded", { buttonPresent: !!button });
- };
- addEventListener("DOMContentLoaded", listener);
- }
- mm.loadFrameScript("data:,(" + contentScript.toString() + ")();", true);
-}
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab("http://www.itisatrap.org/firefox/its-an-attack.html");
- onDOMContentLoaded(testMalware);
-}
-
-function testMalware(data) {
- ok(data.buttonPresent, "Ignore warning button should be present for malware");
-
- Services.prefs.setBoolPref("browser.safebrowsing.allowOverride", false);
-
- // Now launch the unwanted software test
- onDOMContentLoaded(testUnwanted);
- gBrowser.loadURI("http://www.itisatrap.org/firefox/unwanted.html");
-}
-
-function testUnwanted(data) {
- // Confirm that "Ignore this warning" is visible - bug 422410
- ok(!data.buttonPresent, "Ignore warning button should be missing for unwanted software");
-
- Services.prefs.setBoolPref("browser.safebrowsing.allowOverride", true);
-
- // Now launch the phishing test
- onDOMContentLoaded(testPhishing);
- gBrowser.loadURI("http://www.itisatrap.org/firefox/its-a-trap.html");
-}
-
-function testPhishing(data) {
- ok(data.buttonPresent, "Ignore warning button should be present for phishing");
-
- gBrowser.removeCurrentTab();
- finish();
-}
diff --git a/browser/components/safebrowsing/content/test/browser_bug415846.js b/browser/components/safebrowsing/content/test/browser_bug415846.js
deleted file mode 100644
index fc2e3472f..000000000
--- a/browser/components/safebrowsing/content/test/browser_bug415846.js
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Check for the correct behaviour of the report web forgery/not a web forgery
-menu items.
-
-Mac makes this astonishingly painful to test since their help menu is special magic,
-but we can at least test it on the other platforms.*/
-
-const NORMAL_PAGE = "http://example.com";
-const PHISH_PAGE = "http://www.itisatrap.org/firefox/its-a-trap.html";
-
-/**
- * Opens a new tab and browses to some URL, tests for the existence
- * of the phishing menu items, and then runs a test function to check
- * the state of the menu once opened. This function will take care of
- * opening and closing the menu.
- *
- * @param url (string)
- * The URL to browse the tab to.
- * @param testFn (function)
- * The function to run once the menu has been opened. This
- * function will be passed the "reportMenu" and "errorMenu"
- * DOM nodes as arguments, in that order. This function
- * should not yield anything.
- * @returns Promise
- */
-function check_menu_at_page(url, testFn) {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank",
- }, function*(browser) {
- // We don't get load events when the DocShell redirects to error
- // pages, but we do get DOMContentLoaded, so we'll wait for that.
- let dclPromise = ContentTask.spawn(browser, null, function*() {
- yield ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", false);
- });
- browser.loadURI(url);
- yield dclPromise;
-
- let menu = document.getElementById("menu_HelpPopup");
- ok(menu, "Help menu should exist");
-
- let reportMenu =
- document.getElementById("menu_HelpPopup_reportPhishingtoolmenu");
- ok(reportMenu, "Report phishing menu item should exist");
-
- let errorMenu =
- document.getElementById("menu_HelpPopup_reportPhishingErrortoolmenu");
- ok(errorMenu, "Report phishing error menu item should exist");
-
- let menuOpen = BrowserTestUtils.waitForEvent(menu, "popupshown");
- menu.openPopup(null, "", 0, 0, false, null);
- yield menuOpen;
-
- testFn(reportMenu, errorMenu);
-
- let menuClose = BrowserTestUtils.waitForEvent(menu, "popuphidden");
- menu.hidePopup();
- yield menuClose;
- });
-}
-
-/**
- * Tests that we show the "Report this page" menu item at a normal
- * page.
- */
-add_task(function*() {
- yield check_menu_at_page(NORMAL_PAGE, (reportMenu, errorMenu) => {
- ok(!reportMenu.hidden,
- "Report phishing menu should be visible on normal sites");
- ok(errorMenu.hidden,
- "Report error menu item should be hidden on normal sites");
- });
-});
-
-/**
- * Tests that we show the "Report this page is okay" menu item at
- * a reported attack site.
- */
-add_task(function*() {
- yield check_menu_at_page(PHISH_PAGE, (reportMenu, errorMenu) => {
- ok(reportMenu.hidden,
- "Report phishing menu should be hidden on phishing sites");
- ok(!errorMenu.hidden,
- "Report error menu item should be visible on phishing sites");
- });
-});
-
diff --git a/browser/components/safebrowsing/content/test/browser_whitelisted.js b/browser/components/safebrowsing/content/test/browser_whitelisted.js
deleted file mode 100644
index afb647a81..000000000
--- a/browser/components/safebrowsing/content/test/browser_whitelisted.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Ensure that hostnames in the whitelisted pref are not blocked. */
-
-const PREF_WHITELISTED_HOSTNAMES = "urlclassifier.skipHostnames";
-const TEST_PAGE = "http://www.itisatrap.org/firefox/its-an-attack.html";
-var tabbrowser = null;
-
-registerCleanupFunction(function() {
- tabbrowser = null;
- Services.prefs.clearUserPref(PREF_WHITELISTED_HOSTNAMES);
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
-});
-
-function testBlockedPage(window) {
- info("Non-whitelisted pages must be blocked");
- ok(true, "about:blocked was shown");
-}
-
-function testWhitelistedPage(window) {
- info("Whitelisted pages must be skipped");
- var getmeout_button = window.document.getElementById("getMeOutButton");
- var ignorewarning_button = window.document.getElementById("ignoreWarningButton");
- ok(!getmeout_button, "GetMeOut button not present");
- ok(!ignorewarning_button, "IgnoreWarning button not present");
-}
-
-add_task(function* testNormalBrowsing() {
- tabbrowser = gBrowser;
- let tab = tabbrowser.selectedTab = tabbrowser.addTab();
-
- info("Load a test page that's whitelisted");
- Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, "example.com,www.ItIsaTrap.org,example.net");
- yield promiseTabLoadEvent(tab, TEST_PAGE, "load");
- testWhitelistedPage(tab.ownerGlobal);
-
- info("Load a test page that's no longer whitelisted");
- Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, "");
- yield promiseTabLoadEvent(tab, TEST_PAGE, "AboutBlockedLoaded");
- testBlockedPage(tab.ownerGlobal);
-});
diff --git a/browser/components/safebrowsing/content/test/head.js b/browser/components/safebrowsing/content/test/head.js
deleted file mode 100644
index 90eef0a3f..000000000
--- a/browser/components/safebrowsing/content/test/head.js
+++ /dev/null
@@ -1,55 +0,0 @@
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @param [optional] event
- * The load event type to wait for. Defaults to "load".
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url, eventType="load")
-{
- info(`Wait tab event: ${eventType}`);
-
- function handle(loadedUrl) {
- if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
- info(`Skipping spurious load event for ${loadedUrl}`);
- return false;
- }
-
- info("Tab event received: load");
- return true;
- }
-
- let loaded;
- if (eventType === "load") {
- loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
- } else {
- // No need to use handle.
- loaded =
- BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, eventType,
- true, undefined, true);
- }
-
- if (url)
- BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
- return loaded;
-}
-
-Services.prefs.setCharPref("urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple");
-Services.prefs.setCharPref("urlclassifier.phishTable", "test-phish-simple");
-Services.prefs.setCharPref("urlclassifier.blockedTable", "test-block-simple");
-SafeBrowsing.init();
diff --git a/browser/components/search/test/.eslintrc.js b/browser/components/search/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/search/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/search/test/426329.xml b/browser/components/search/test/426329.xml
deleted file mode 100644
index e4545cc77..000000000
--- a/browser/components/search/test/426329.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>Bug 426329</ShortName>
- <Description>426329 Search</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/test.html">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/test.html</moz:SearchForm>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/483086-1.xml b/browser/components/search/test/483086-1.xml
deleted file mode 100644
index 9dbba4886..000000000
--- a/browser/components/search/test/483086-1.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>483086a</ShortName>
- <Description>Bug 483086 Test 1</Description>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>foo://example.com</moz:SearchForm>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/483086-2.xml b/browser/components/search/test/483086-2.xml
deleted file mode 100644
index f130b9068..000000000
--- a/browser/components/search/test/483086-2.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>483086b</ShortName>
- <Description>Bug 483086 Test 2</Description>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>http://example.com</moz:SearchForm>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/browser.ini b/browser/components/search/test/browser.ini
deleted file mode 100644
index f1070264d..000000000
--- a/browser/components/search/test/browser.ini
+++ /dev/null
@@ -1,44 +0,0 @@
-[DEFAULT]
-support-files =
- 426329.xml
- 483086-1.xml
- 483086-2.xml
- head.js
- opensearch.html
- test.html
- testEngine.xml
- testEngine_diacritics.xml
- testEngine_dupe.xml
- testEngine_mozsearch.xml
- webapi.html
-
-[browser_426329.js]
-[browser_483086.js]
-[browser_addEngine.js]
-[browser_amazon.js]
-[browser_amazon_behavior.js]
-[browser_bing.js]
-[browser_bing_behavior.js]
-[browser_contextmenu.js]
-[browser_contextSearchTabPosition.js]
-skip-if = os == "mac" # bug 967013
-[browser_google.js]
-[browser_google_codes.js]
-[browser_google_behavior.js]
-[browser_healthreport.js]
-[browser_hiddenOneOffs_cleanup.js]
-[browser_hiddenOneOffs_diacritics.js]
-[browser_oneOffContextMenu.js]
-[browser_oneOffContextMenu_setDefault.js]
-[browser_oneOffHeader.js]
-[browser_private_search_perwindowpb.js]
-[browser_yahoo.js]
-[browser_yahoo_behavior.js]
-[browser_abouthome_behavior.js]
-skip-if = true # Bug ??????, Bug 1100301 - leaks windows until shutdown when --run-by-dir
-[browser_aboutSearchReset.js]
-[browser_searchbar_openpopup.js]
-skip-if = os == "linux" # Linux has different focus behaviours.
-[browser_searchbar_keyboard_navigation.js]
-[browser_searchbar_smallpanel_keyboard_navigation.js]
-[browser_webapi.js]
diff --git a/browser/components/search/test/browser_426329.js b/browser/components/search/test/browser_426329.js
deleted file mode 100644
index d9cbd3f7a..000000000
--- a/browser/components/search/test/browser_426329.js
+++ /dev/null
@@ -1,250 +0,0 @@
-XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
- "resource://gre/modules/FormHistory.jsm");
-
-function expectedURL(aSearchTerms) {
- const ENGINE_HTML_BASE = "http://mochi.test:8888/browser/browser/components/search/test/test.html";
- var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"].
- getService(Ci.nsITextToSubURI);
- var searchArg = textToSubURI.ConvertAndEscape("utf-8", aSearchTerms);
- return ENGINE_HTML_BASE + "?test=" + searchArg;
-}
-
-function simulateClick(aEvent, aTarget) {
- var event = document.createEvent("MouseEvent");
- var ctrlKeyArg = aEvent.ctrlKey || false;
- var altKeyArg = aEvent.altKey || false;
- var shiftKeyArg = aEvent.shiftKey || false;
- var metaKeyArg = aEvent.metaKey || false;
- var buttonArg = aEvent.button || 0;
- event.initMouseEvent("click", true, true, window,
- 0, 0, 0, 0, 0,
- ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
- buttonArg, null);
- aTarget.dispatchEvent(event);
-}
-
-// modified from toolkit/components/satchel/test/test_form_autocomplete.html
-function checkMenuEntries(expectedValues) {
- var actualValues = getMenuEntries();
- is(actualValues.length, expectedValues.length, "Checking length of expected menu");
- for (var i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], "Checking menu entry #" + i);
-}
-
-function getMenuEntries() {
- var entries = [];
- var autocompleteMenu = searchBar.textbox.popup;
- // Could perhaps pull values directly from the controller, but it seems
- // more reliable to test the values that are actually in the tree?
- var column = autocompleteMenu.tree.columns[0];
- var numRows = autocompleteMenu.tree.view.rowCount;
- for (var i = 0; i < numRows; i++) {
- entries.push(autocompleteMenu.tree.view.getValueAt(i, column));
- }
- return entries;
-}
-
-function countEntries(name, value) {
- return new Promise(resolve => {
- let count = 0;
- let obj = name && value ? {fieldname: name, value: value} : {};
- FormHistory.count(obj,
- { handleResult: function(result) { count = result; },
- handleError: function(error) { throw error; },
- handleCompletion: function(reason) {
- if (!reason) {
- resolve(count);
- }
- }
- });
- });
-}
-
-var searchBar;
-var searchButton;
-var searchEntries = ["test"];
-function promiseSetEngine() {
- return new Promise(resolve => {
- var ss = Services.search;
-
- function observer(aSub, aTopic, aData) {
- switch (aData) {
- case "engine-added":
- var engine = ss.getEngineByName("Bug 426329");
- ok(engine, "Engine was added.");
- ss.currentEngine = engine;
- break;
- case "engine-current":
- ok(ss.currentEngine.name == "Bug 426329", "currentEngine set");
- searchBar = BrowserSearch.searchBar;
- searchButton = document.getAnonymousElementByAttribute(searchBar,
- "anonid", "search-go-button");
- ok(searchButton, "got search-go-button");
- searchBar.value = "test";
-
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- resolve();
- break;
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- ss.addEngine("http://mochi.test:8888/browser/browser/components/search/test/426329.xml",
- null, "data:image/x-icon,%00", false);
- });
-}
-
-function promiseRemoveEngine() {
- return new Promise(resolve => {
- var ss = Services.search;
-
- function observer(aSub, aTopic, aData) {
- if (aData == "engine-removed") {
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- resolve();
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- var engine = ss.getEngineByName("Bug 426329");
- ss.removeEngine(engine);
- });
-}
-
-
-var preSelectedBrowser;
-var preTabNo;
-function* prepareTest() {
- preSelectedBrowser = gBrowser.selectedBrowser;
- preTabNo = gBrowser.tabs.length;
- searchBar = BrowserSearch.searchBar;
-
- yield SimpleTest.promiseFocus();
-
- if (document.activeElement == searchBar)
- return;
-
- let focusPromise = BrowserTestUtils.waitForEvent(searchBar, "focus");
- gURLBar.focus();
- searchBar.focus();
- yield focusPromise;
-}
-
-add_task(function* testSetupEngine() {
- yield promiseSetEngine();
-});
-
-add_task(function* testReturn() {
- yield* prepareTest();
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
-
- is(gBrowser.tabs.length, preTabNo, "Return key did not open new tab");
- is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testReturn opened correct search page");
-});
-
-add_task(function* testAltReturn() {
- yield* prepareTest();
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- EventUtils.synthesizeKey("VK_RETURN", { altKey: true });
- });
-
- is(gBrowser.tabs.length, preTabNo + 1, "Alt+Return key added new tab");
- is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testAltReturn opened correct search page");
-});
-
-// Shift key has no effect for now, so skip it
-add_task(function* testShiftAltReturn() {
- return;
- /*
- yield* prepareTest();
-
- let url = expectedURL(searchBar.value);
-
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url);
- EventUtils.synthesizeKey("VK_RETURN", { shiftKey: true, altKey: true });
- yield newTabPromise;
-
- is(gBrowser.tabs.length, preTabNo + 1, "Shift+Alt+Return key added new tab");
- is(gBrowser.currentURI.spec, url, "testShiftAltReturn opened correct search page");
- */
-});
-
-add_task(function* testLeftClick() {
- yield* prepareTest();
- simulateClick({ button: 0 }, searchButton);
- yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- is(gBrowser.tabs.length, preTabNo, "LeftClick did not open new tab");
- is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testLeftClick opened correct search page");
-});
-
-add_task(function* testMiddleClick() {
- yield* prepareTest();
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- simulateClick({ button: 1 }, searchButton);
- });
- is(gBrowser.tabs.length, preTabNo + 1, "MiddleClick added new tab");
- is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testMiddleClick opened correct search page");
-});
-
-add_task(function* testShiftMiddleClick() {
- yield* prepareTest();
-
- let url = expectedURL(searchBar.value);
-
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url);
- simulateClick({ button: 1, shiftKey: true }, searchButton);
- let newTab = yield newTabPromise;
-
- is(gBrowser.tabs.length, preTabNo + 1, "Shift+MiddleClick added new tab");
- is(newTab.linkedBrowser.currentURI.spec, url, "testShiftMiddleClick opened correct search page");
-});
-
-add_task(function* testRightClick() {
- preTabNo = gBrowser.tabs.length;
- gBrowser.selectedBrowser.loadURI("about:blank");
- yield new Promise(resolve => {
- setTimeout(function() {
- is(gBrowser.tabs.length, preTabNo, "RightClick did not open new tab");
- is(gBrowser.currentURI.spec, "about:blank", "RightClick did nothing");
- resolve();
- }, 5000);
- simulateClick({ button: 2 }, searchButton);
- });
- // The click in the searchbox focuses it, which opens the suggestion
- // panel. Clean up after ourselves.
- searchBar.textbox.popup.hidePopup();
-});
-
-add_task(function* testSearchHistory() {
- var textbox = searchBar._textbox;
- for (var i = 0; i < searchEntries.length; i++) {
- let count = yield countEntries(textbox.getAttribute("autocompletesearchparam"), searchEntries[i]);
- ok(count > 0, "form history entry '" + searchEntries[i] + "' should exist");
- }
-});
-
-add_task(function* testAutocomplete() {
- var popup = searchBar.textbox.popup;
- let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown");
- searchBar.textbox.showHistoryPopup();
- yield popupShownPromise;
- checkMenuEntries(searchEntries);
-});
-
-add_task(function* testClearHistory() {
- let controller = searchBar.textbox.controllers.getControllerForCommand("cmd_clearhistory")
- ok(controller.isCommandEnabled("cmd_clearhistory"), "Clear history command enabled");
- controller.doCommand("cmd_clearhistory");
- let count = yield countEntries();
- ok(count == 0, "History cleared");
-});
-
-add_task(function* asyncCleanup() {
- searchBar.value = "";
- while (gBrowser.tabs.length != 1) {
- gBrowser.removeTab(gBrowser.tabs[0], {animate: false});
- }
- gBrowser.selectedBrowser.loadURI("about:blank");
- yield promiseRemoveEngine();
-});
diff --git a/browser/components/search/test/browser_483086.js b/browser/components/search/test/browser_483086.js
deleted file mode 100644
index 208add867..000000000
--- a/browser/components/search/test/browser_483086.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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/. */
-var gSS = Services.search;
-
-function test() {
- waitForExplicitFinish();
-
- function observer(aSubject, aTopic, aData) {
- switch (aData) {
- case "engine-added":
- let engine = gSS.getEngineByName("483086a");
- ok(engine, "Test engine 1 installed");
- isnot(engine.searchForm, "foo://example.com",
- "Invalid SearchForm URL dropped");
- gSS.removeEngine(engine);
- break;
- case "engine-removed":
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- test2();
- break;
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/483086-1.xml",
- null, "data:image/x-icon;%00", false);
-}
-
-function test2() {
- function observer(aSubject, aTopic, aData) {
- switch (aData) {
- case "engine-added":
- let engine = gSS.getEngineByName("483086b");
- ok(engine, "Test engine 2 installed");
- is(engine.searchForm, "http://example.com", "SearchForm is correct");
- gSS.removeEngine(engine);
- break;
- case "engine-removed":
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- finish();
- break;
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/483086-2.xml",
- null, "data:image/x-icon;%00", false);
-}
diff --git a/browser/components/search/test/browser_aboutSearchReset.js b/browser/components/search/test/browser_aboutSearchReset.js
deleted file mode 100644
index 64376d6da..000000000
--- a/browser/components/search/test/browser_aboutSearchReset.js
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const TELEMETRY_RESULT_ENUM = {
- RESTORED_DEFAULT: 0,
- KEPT_CURRENT: 1,
- CHANGED_ENGINE: 2,
- CLOSED_PAGE: 3,
- OPENED_SETTINGS: 4
-};
-
-const kSearchStr = "a search";
-const kSearchPurpose = "searchbar";
-
-const kTestEngine = "testEngine.xml";
-
-function checkTelemetryRecords(expectedValue) {
- let histogram = Services.telemetry.getHistogramById("SEARCH_RESET_RESULT");
- let snapshot = histogram.snapshot();
- // The probe is declared with 5 values, but we get 6 back from .counts
- let expectedCounts = [0, 0, 0, 0, 0, 0];
- if (expectedValue != null) {
- expectedCounts[expectedValue] = 1;
- }
- Assert.deepEqual(snapshot.counts, expectedCounts,
- "histogram has expected content");
- histogram.clear();
-}
-
-function promiseStoppedLoad(expectedURL) {
- return new Promise(resolve => {
- let browser = gBrowser.selectedBrowser;
- let original = browser.loadURIWithFlags;
- browser.loadURIWithFlags = function(URI) {
- if (URI == expectedURL) {
- browser.loadURIWithFlags = original;
- ok(true, "loaded expected url: " + URI);
- resolve();
- return;
- }
-
- original.apply(browser, arguments);
- };
- });
-}
-
-var gTests = [
-
-{
- desc: "Test the 'Keep Current Settings' button.",
- run: function* () {
- let engine = yield promiseNewEngine(kTestEngine, {setAsCurrent: true});
-
- let expectedURL = engine.
- getSubmission(kSearchStr, null, kSearchPurpose).
- uri.spec;
-
- let rawEngine = engine.wrappedJSObject;
- let initialHash = rawEngine.getAttr("loadPathHash");
- rawEngine.setAttr("loadPathHash", "broken");
-
- let loadPromise = promiseStoppedLoad(expectedURL);
- gBrowser.contentDocument.getElementById("searchResetKeepCurrent").click();
- yield loadPromise;
-
- is(engine, Services.search.currentEngine,
- "the custom engine is still default");
- is(rawEngine.getAttr("loadPathHash"), initialHash,
- "the loadPathHash has been fixed");
-
- checkTelemetryRecords(TELEMETRY_RESULT_ENUM.KEPT_CURRENT);
- }
-},
-
-{
- desc: "Test the 'Restore Search Defaults' button.",
- run: function* () {
- let currentEngine = Services.search.currentEngine;
- let originalEngine = Services.search.originalDefaultEngine;
- let doc = gBrowser.contentDocument;
- let defaultEngineSpan = doc.getElementById("defaultEngine");
- is(defaultEngineSpan.textContent, originalEngine.name,
- "the name of the original default engine is displayed");
-
- let expectedURL = originalEngine.
- getSubmission(kSearchStr, null, kSearchPurpose).
- uri.spec;
- let loadPromise = promiseStoppedLoad(expectedURL);
- let button = doc.getElementById("searchResetChangeEngine");
- is(doc.activeElement, button,
- "the 'Change Search Engine' button is focused");
- button.click();
- yield loadPromise;
-
- is(originalEngine, Services.search.currentEngine,
- "the default engine is back to the original one");
-
- checkTelemetryRecords(TELEMETRY_RESULT_ENUM.RESTORED_DEFAULT);
- Services.search.currentEngine = currentEngine;
- }
-},
-
-{
- desc: "Click the settings link.",
- run: function* () {
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser,
- false,
- "about:preferences#search")
- gBrowser.contentDocument.getElementById("linkSettingsPage").click();
- yield loadPromise;
-
- checkTelemetryRecords(TELEMETRY_RESULT_ENUM.OPENED_SETTINGS);
- }
-},
-
-{
- desc: "Load another page without clicking any of the buttons.",
- run: function* () {
- yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla");
-
- checkTelemetryRecords(TELEMETRY_RESULT_ENUM.CLOSED_PAGE);
- }
-},
-
-];
-
-function test()
-{
- waitForExplicitFinish();
- Task.spawn(function* () {
- let oldCanRecord = Services.telemetry.canRecordExtended;
- Services.telemetry.canRecordExtended = true;
- checkTelemetryRecords();
-
- for (let test of gTests) {
- info(test.desc);
-
- // Create a tab to run the test.
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
-
- // Start loading about:searchreset and wait for it to complete.
- let url = "about:searchreset?data=" + encodeURIComponent(kSearchStr) +
- "&purpose=" + kSearchPurpose;
- yield promiseTabLoadEvent(tab, url);
-
- info("Running test");
- yield test.run();
-
- info("Cleanup");
- gBrowser.removeCurrentTab();
- }
-
- Services.telemetry.canRecordExtended = oldCanRecord;
- }).then(finish, ex => {
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
-}
diff --git a/browser/components/search/test/browser_abouthome_behavior.js b/browser/components/search/test/browser_abouthome_behavior.js
deleted file mode 100644
index 3291b41f4..000000000
--- a/browser/components/search/test/browser_abouthome_behavior.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test home page search for all plugin URLs
- */
-
-"use strict";
-
-function test() {
- // Bug 992270: Ignore uncaught about:home exceptions (related to snippets from IndexedDB)
- ignoreAllUncaughtExceptions(true);
-
- let previouslySelectedEngine = Services.search.currentEngine;
-
- function replaceUrl(base) {
- return base;
- }
-
- let gMutationObserver = null;
-
- function verify_about_home_search(engine_name) {
- let engine = Services.search.getEngineByName(engine_name);
- ok(engine, engine_name + " is installed");
-
- Services.search.currentEngine = engine;
-
- // load about:home, but remove the listener first so it doesn't
- // get in the way
- gBrowser.removeProgressListener(listener);
- gBrowser.loadURI("about:home");
- info("Waiting for about:home load");
- tab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- tab.linkedBrowser.removeEventListener("load", load, true);
-
- // Observe page setup
- let doc = gBrowser.contentDocument;
- gMutationObserver = new MutationObserver(function (mutations) {
- for (let mutation of mutations) {
- if (mutation.attributeName == "searchEngineName") {
- // Re-add the listener, and perform a search
- gBrowser.addProgressListener(listener);
- gMutationObserver.disconnect()
- gMutationObserver = null;
- executeSoon(function() {
- doc.getElementById("searchText").value = "foo";
- doc.getElementById("searchSubmit").click();
- });
- }
- }
- });
- gMutationObserver.observe(doc.documentElement, { attributes: true });
- }, true);
- }
- waitForExplicitFinish();
-
- let gCurrTest;
- let gTests = [
- {
- name: "Search with Bing from about:home",
- searchURL: replaceUrl("http://www.bing.com/search?q=foo&pc=MOZI&form=MOZSPG"),
- run: function () {
- verify_about_home_search("Bing");
- }
- },
- {
- name: "Search with Yahoo from about:home",
- searchURL: replaceUrl("https://search.yahoo.com/search?p=foo&ei=UTF-8&fr=moz35"),
- run: function () {
- verify_about_home_search("Yahoo");
- }
- },
- {
- name: "Search with Google from about:home",
- searchURL: replaceUrl("https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8"),
- run: function () {
- verify_about_home_search("Google");
- }
- },
- {
- name: "Search with Amazon.com from about:home",
- searchURL: replaceUrl("https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"),
- run: function () {
- verify_about_home_search("Amazon.com");
- }
- }
- ];
-
- function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- info("Running : " + gCurrTest.name);
- executeSoon(gCurrTest.run);
- } else {
- // Make sure we listen again for uncaught exceptions in the next test or cleanup.
- executeSoon(finish);
- }
- }
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onStateChange(webProgress, req, flags, status) {
- info("onStateChange");
- // Only care about top-level document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart) || !webProgress.isTopLevel)
- return;
-
- if (req.originalURI.spec == "about:blank")
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- }
-
- registerCleanupFunction(function () {
- Services.search.currentEngine = previouslySelectedEngine;
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- if (gMutationObserver)
- gMutationObserver.disconnect();
- });
-
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- gBrowser.addProgressListener(listener);
- nextTest();
- }, true);
-}
diff --git a/browser/components/search/test/browser_addEngine.js b/browser/components/search/test/browser_addEngine.js
deleted file mode 100644
index b971ea5f7..000000000
--- a/browser/components/search/test/browser_addEngine.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/* 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/. */
-var gSS = Services.search;
-
-function observer(aSubject, aTopic, aData) {
- if (!gCurrentTest) {
- info("Observer called with no test active");
- return;
- }
-
- let engine = aSubject.QueryInterface(Ci.nsISearchEngine);
- info("Observer: " + aData + " for " + engine.name);
- let method;
- switch (aData) {
- case "engine-added":
- if (gCurrentTest.added)
- method = "added"
- break;
- case "engine-current":
- if (gCurrentTest.current)
- method = "current";
- break;
- case "engine-removed":
- if (gCurrentTest.removed)
- method = "removed";
- break;
- }
-
- if (method)
- gCurrentTest[method](engine);
-}
-
-function checkEngine(checkObj, engineObj) {
- info("Checking engine");
- for (var prop in checkObj)
- is(checkObj[prop], engineObj[prop], prop + " is correct");
-}
-
-var gTests = [
- {
- name: "opensearch install",
- engine: {
- name: "Foo",
- alias: null,
- description: "Foo Search",
- searchForm: "http://mochi.test:8888/browser/browser/components/search/test/"
- },
- run: function () {
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
-
- gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml",
- null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC",
- false);
- },
- added: function (engine) {
- ok(engine, "engine was added.");
-
- checkEngine(this.engine, engine);
-
- let engineFromSS = gSS.getEngineByName(this.engine.name);
- is(engine, engineFromSS, "engine is obtainable via getEngineByName");
-
- let aEngine = gSS.getEngineByAlias("fooalias");
- ok(!aEngine, "Alias was not parsed from engine description");
-
- gSS.currentEngine = engine;
- },
- current: function (engine) {
- let currentEngine = gSS.currentEngine;
- is(engine, currentEngine, "engine is current");
- is(engine.name, this.engine.name, "current engine was changed successfully");
-
- gSS.removeEngine(engine);
- },
- removed: function (engine) {
- // Remove the observer before calling the currentEngine getter,
- // as that getter will set the currentEngine to the original default
- // which will trigger a notification causing the test to loop over all
- // engines.
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
-
- let currentEngine = gSS.currentEngine;
- ok(currentEngine, "An engine is present.");
- isnot(currentEngine.name, this.engine.name, "Current engine reset after removal");
-
- nextTest();
- }
- }
-];
-
-var gCurrentTest = null;
-function nextTest() {
- if (gTests.length) {
- gCurrentTest = gTests.shift();
- info("Running " + gCurrentTest.name);
- gCurrentTest.run();
- } else
- executeSoon(finish);
-}
-
-function test() {
- waitForExplicitFinish();
- nextTest();
-}
diff --git a/browser/components/search/test/browser_amazon.js b/browser/components/search/test/browser_amazon.js
deleted file mode 100644
index 965a3dcf8..000000000
--- a/browser/components/search/test/browser_amazon.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Amazon search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-function test() {
- let engine = Services.search.getEngineByName("Amazon.com");
- ok(engine, "Amazon.com");
-
- let base = "https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base, "Check search URL for 'foo'");
-
- // Check search suggestion URL.
- url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec;
- is(url, "https://completion.amazon.com/search/complete?q=foo&search-alias=aps&mkt=1", "Check search suggestion URL for 'foo'");
-
- // Check all other engine properties.
- const EXPECTED_ENGINE = {
- name: "Amazon.com",
- alias: null,
- description: "Amazon.com Search",
- searchForm: "https://www.amazon.com/exec/obidos/external-search/?field-keywords=&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search",
- hidden: false,
- wrappedJSObject: {
- queryCharset: "UTF-8",
- "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAAAAAC0AQAAJgAAACAgAAAAAAAA6QIAANoBAACJUE5HDQoaCgAAAA1JSERSAAAAEAAAABAIBgAAAB/z/2EAAAF7SURBVDjLlZPLasJAFIaFRF+iVV+h6hO0GF+gVB9AaHwDt64qCG03tQgtdCFIuyhUelmGli66MXThSt24kNiFBUlAYi6ezjnNxSuawB/ITP7v/HNmJgQAEaZzpgHs/gwcTyTEXuXl2U6nA8ViEbK5HKler28CVRAwnB9ptVrAh8MrQuCaZ4iA8fzIqSgCxwzpTIaSuN/RWGwdYLwCUBQFZFkGSZLgqdmEE7YEN8VOAKyaSKUW4nNBAFmnYiKZpDRX1WqwBBzP089n5f/NEQsFL4WqqtsBWJlzDAJr5PwSMM1awEzzdxIbGI3Hvc6jCZeVFgRQRwpY7Qcw3ktgfpR8wLRxCPaot/X4GS95MppfF6DX9n2A3f+kAZycaT8bAZjU6r6B/duD6d3BYg9wQq/tkYzHY1blEiz5lmQyGc95mrO6r2CxgpjCBXgNsJVviolpXJiraeOIjJRE10juUa4sR8V+mO17VvmGqtuOcdNlwut8zTQJcJ0njifyB2bgTdKh6w4BAAAAAElFTkSuQmCCiVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACsElEQVRYw71XQWsTURBe2LQgeNKLB+tVemt6txcteNSD/QGC6VEIGDx5s+eKPQqFgJhLNdFLBWMP7cU0oSAWjB70koC9WHbVQ5SO8+XtS14mr7svyaYDH9m87Jv55puZt1nPi4yIzjMeMj7T9OwjI88455nGC1cZX+nsDESumJmPFDwIAqrX6z00Gg1qt9vjkJgFgUeuO16Vy3RjeZkyMzM9+MY1fsM9I9h9zyV7ZAznZrA4FAoFVwJ1z+WuOysrg1lnMolkHJX4k0igzI5sARYWF7vEZEk0rvO6iyUSuJfLJUqM7zYSqRDIra4OOUZPmNZsNrsl8UVTpkJAjh1GzmaSpJ8mAWmYeZB5urHRhW5SNOfUCCDo47W1bvPZsp2qAhipy3Nz1kaLG8dUCEBqM5AvpgElqFar01NgIZsdco7Zb7VasU2YigIYL5tjqCL7Q5YkFQXKlcqQ7DbHthIALk/IWAKor82xPIhshxWABCYioDMz51sexcVi0XoG4DPLIyvJjkTArK3scDQnRvO0MdTrUHGiKZCP4tNgO6BAEI08EQH9Z2Qow0hyPypJGIa9p6JWKCn4SA8jSKmJIDgyRvPJkcRxjfUwNGr/i8+Mo32iHzWiThBD4NM60bet9P77/ubA728RlTjMiwiH6zEEfvIrwdZFtQmMJ7W/ofIDBZD5m3mVZGwJcOP2kmILIlCkE45HoPWurwCSg0+UQRD4ZyXxId+T7gQb9+4q9sioY5ltrOG3L5vqXiiJffDx/aUi83ZJ7jr2ohcEu8Hh6/m+I7OWGiVxbWKHsz+O3vSOakqFQdsFgQeJUiKD7Wv9YKXBgCeSUC3v2kM5EJhlHDh3NcgcPlG1BXZu98sDmTuBa4fsMnz9fniJUaGzs+eMC540XuR0aDO2L8Y3qPyMcdOM+R/8XcqRA3qp9gAAAABJRU5ErkJggg==",
- _urls : [
- {
- type: "application/x-suggestions+json",
- method: "GET",
- template: "https://completion.amazon.com/search/complete?q={searchTerms}&search-alias=aps&mkt=1",
- params: "",
- },
- {
- type: "text/html",
- method: "GET",
- template: "https://www.amazon.com/exec/obidos/external-search/",
- params: [
- {
- name: "field-keywords",
- value: "{searchTerms}",
- purpose: undefined,
- },
- {
- name: "ie",
- value: "{inputEncoding}",
- purpose: undefined,
- },
- {
- name: "mode",
- value: "blended",
- purpose: undefined,
- },
- {
- name: "tag",
- value: "mozilla-20",
- purpose: undefined,
- },
- {
- name: "sourceid",
- value: "Mozilla-search",
- purpose: undefined,
- },
- ],
- mozparams: {},
- },
- ],
- },
- };
-
- isSubObjectOf(EXPECTED_ENGINE, engine, "Amazon");
-}
diff --git a/browser/components/search/test/browser_amazon_behavior.js b/browser/components/search/test/browser_amazon_behavior.js
deleted file mode 100644
index 22d16581a..000000000
--- a/browser/components/search/test/browser_amazon_behavior.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Amazon search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-
-function test() {
- let engine = Services.search.getEngineByName("Amazon.com");
- ok(engine, "Amazon is installed");
-
- let previouslySelectedEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- engine.alias = "a";
-
- let base = "https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base, "Check search URL for 'foo'");
-
- waitForExplicitFinish();
-
- var gCurrTest;
- var gTests = [
- {
- name: "context menu search",
- searchURL: base,
- run: function () {
- // Simulate a contextmenu search
- // FIXME: This is a bit "low-level"...
- BrowserSearch.loadSearch("foo", false, "contextmenu");
- }
- },
- {
- name: "keyword search",
- searchURL: base,
- run: function () {
- gURLBar.value = "? foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "keyword search",
- searchURL: base,
- run: function () {
- gURLBar.value = "a foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "search bar search",
- searchURL: base,
- run: function () {
- let sb = BrowserSearch.searchBar;
- sb.focus();
- sb.value = "foo";
- registerCleanupFunction(function () {
- sb.value = "";
- });
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "new tab search",
- searchURL: base,
- run: function () {
- function doSearch(doc) {
- // Re-add the listener, and perform a search
- gBrowser.addProgressListener(listener);
- doc.getElementById("newtab-search-text").value = "foo";
- doc.getElementById("newtab-search-submit").click();
- }
-
- // load about:newtab, but remove the listener first so it doesn't
- // get in the way
- gBrowser.removeProgressListener(listener);
- gBrowser.loadURI("about:newtab");
- info("Waiting for about:newtab load");
- tab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- tab.linkedBrowser.removeEventListener("load", load, true);
-
- // Observe page setup
- let win = gBrowser.contentWindow;
- if (win.gSearch.currentEngineName ==
- Services.search.currentEngine.name) {
- doSearch(win.document);
- }
- else {
- info("Waiting for newtab search init");
- win.addEventListener("ContentSearchService", function done(event) {
- info("Got newtab search event " + event.detail.type);
- if (event.detail.type == "State") {
- win.removeEventListener("ContentSearchService", done);
- // Let gSearch respond to the event before continuing.
- executeSoon(() => doSearch(win.document));
- }
- });
- }
- }, true);
- }
- }
- ];
-
- function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- info("Running : " + gCurrTest.name);
- executeSoon(gCurrTest.run);
- } else {
- finish();
- }
- }
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onStateChange(webProgress, req, flags, status) {
- info("onStateChange");
- // Only care about top-level document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart) || !webProgress.isTopLevel)
- return;
-
- if (req.originalURI.spec == "about:blank")
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- }
-
- registerCleanupFunction(function () {
- engine.alias = undefined;
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- Services.search.currentEngine = previouslySelectedEngine;
- });
-
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- gBrowser.addProgressListener(listener);
- nextTest();
- }, true);
-}
diff --git a/browser/components/search/test/browser_bing.js b/browser/components/search/test/browser_bing.js
deleted file mode 100644
index 3a41ae0ac..000000000
--- a/browser/components/search/test/browser_bing.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Bing search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-function test() {
- let engine = Services.search.getEngineByName("Bing");
- ok(engine, "Bing");
-
- let base = "https://www.bing.com/search?q=foo&pc=MOZI";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base + "&form=MOZSBR", "Check search URL for 'foo'");
- url = engine.getSubmission("foo", null, "contextmenu").uri.spec;
- is(url, base + "&form=MOZCON", "Check context menu search URL for 'foo'");
- url = engine.getSubmission("foo", null, "keyword").uri.spec;
- is(url, base + "&form=MOZLBR", "Check keyword search URL for 'foo'");
- url = engine.getSubmission("foo", null, "searchbar").uri.spec;
- is(url, base + "&form=MOZSBR", "Check search bar search URL for 'foo'");
- url = engine.getSubmission("foo", null, "homepage").uri.spec;
- is(url, base + "&form=MOZSPG", "Check homepage search URL for 'foo'");
- url = engine.getSubmission("foo", null, "newtab").uri.spec;
- is(url, base + "&form=MOZTSB", "Check newtab search URL for 'foo'");
-
- // Check search suggestion URL.
- url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec;
- is(url, "https://www.bing.com/osjson.aspx?query=foo&form=OSDJAS&language=" + getLocale(), "Check search suggestion URL for 'foo'");
-
- // Check all other engine properties.
- const EXPECTED_ENGINE = {
- name: "Bing",
- alias: null,
- description: "Bing. Search by Microsoft.",
- searchForm: "https://www.bing.com/search?q=&pc=MOZI&form=MOZSBR",
- hidden: false,
- wrappedJSObject: {
- queryCharset: "UTF-8",
- "_iconURL": "data:image/x-icon;base64,AAABAAIAICAAAAEACACoCAAAJgAAABAQAAABAAgAaAUAAM4IAAAoAAAAIAAAAEAAAAABAAgAAAAAAIAEAAAAAAAAAAAAAAABAAAAAAAAhIQMAI+PIwCXlzEAn59BAKioUwCurl8AtbVuAL6+fwDJyZMA0tKlANjYsgDe3r4A5eXMAOzs2QDy8uUA+fnzAP///wAAGi8AAC1QAAA/cAAAUZAAAGOwAAB2zwAAiPAAEZj/ADGm/wBRs/8AccH/AJHP/wCx3f8A0ev/AP///wAAAAAAACwvAABLUAAAaHAAAIaQAAClsAAAw88AAOHwABHv/wAx8f8AUfP/AHH1/wCR9/8Asfn/ANH7/wD///8AAAAAAAAvIQAAUDcAAHBMAACQYwAAsHkAAM+PAADwpgAR/7QAMf++AFH/yABx/9MAkf/cALH/5QDR//AA////AAAAAAAALw4AAFAYAABwIgAAkCwAALA2AADPQAAA8EoAEf9bADH/cQBR/4cAcf+dAJH/sgCx/8kA0f/fAP///wAAAAAAAi8AAARQAAAGcAAACJAAAAqwAAALzwAADvAAACD/EgA9/zEAW/9RAHn/cQCY/5EAtf+xANT/0QD///8AAAAAABQvAAAiUAAAMHAAAD2QAABMsAAAWc8AAGfwAAB4/xEAiv8xAJz/UQCu/3EAwP+RANL/sQDk/9EA////AAAAAAAmLwAAQFAAAFpwAAB0kAAAjrAAAKnPAADC8AAA0f8RANj/MQDe/1EA4/9xAOn/kQDv/7EA9v/RAP///wAAAAAALyYAAFBBAABwWwAAkHQAALCOAADPqQAA8MMAAP/SEQD/2DEA/91RAP/kcQD/6pEA//CxAP/20QD///8AAAAAAC8UAABQIgAAcDAAAJA+AACwTQAAz1sAAPBpAAD/eREA/4oxAP+dUQD/r3EA/8GRAP/SsQD/5dEA////AAAAAAAvAwAAUAQAAHAGAACQCQAAsAoAAM8MAADwDgAA/yASAP8+MQD/XFEA/3pxAP+XkQD/trEA/9TRAP///wAAAAAALwAOAFAAFwBwACEAkAArALAANgDPAEAA8ABJAP8RWgD/MXAA/1GGAP9xnAD/kbIA/7HIAP/R3wD///8AAAAAAC8AIABQADYAcABMAJAAYgCwAHgAzwCOAPAApAD/EbMA/zG+AP9RxwD/cdEA/5HcAP+x5QD/0fAA////AAAAAAAsAC8ASwBQAGkAcACHAJAApQCwAMQAzwDhAPAA8BH/APIx/wD0Uf8A9nH/APeR/wD5sf8A+9H/AP///wAAAAAAGwAvAC0AUAA/AHAAUgCQAGMAsAB2AM8AiADwAJkR/wCmMf8AtFH/AMJx/wDPkf8A3LH/AOvR/wD///8AAAAAAAgALwAOAFAAFQBwABsAkAAhALAAJgDPACwA8AA+Ef8AWDH/AHFR/wCMcf8AppH/AL+x/wDa0f8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBggCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAsQEA0HAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwkPEBAQEBALBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEMEBAQEBAQEBAPCQMAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAQEBAQEBAQDQgBAAAAAAAAAAAAAAAAAAAAAAABDRAQEBAQEBAQEBAQEA0GAQAAAAAAAAAAAAAAAAAAAAENEBAQDgcLEBAQEBAQEBALBAAAAAAAAAAAAAAAAAAAAQ0QEBANAQEHDRAQEBAQEBAOCAAAAAAAAAAAAAAAAAABDRAQEA4BAAACCA4QEBAQEBANAQAAAAAAAAAAAAAAAAENEBAQDgEAAAAABAsQEBAQEA0BAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAABBw4QEBAQDQEAAAAAAAAAAAAAAAABDRAQEA4BAAABBw0QEBAQEBANAQAAAAAAAAAAAAAAAAENEBAQDgEAAAcQEBAQEBAQEA0BAAAAAAAAAAAAAAAAAQ0QEBAOAQABCxAQEBAQEBANBwAAAAAAAAAAAAAAAAABDRAQEA4BAAQPEBAQEA0IBAEAAAAAAAAAAAAAAAAAAAENEBAQDgEACRAQDQkGAQAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQILCgYCAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA4BAQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEBAQDgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA4BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEBAQDgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA0BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEA0IBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQcFAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAQAAAAIAAAAAEACAAAAAAAQAEAAAAAAAAAAAAAAAEAAAAAAACEhAAAjIwAAJKSFgCZmSgAqqpRALKyYgC+vnsAxsaKAM3NmQDU1KgA4ODBAOjozwDw8OEA+fnyAP///wD///8AAAAAAAAaLwAALVAAAD9wAABRkAAAY7AAAHbPAACI8AARmP8AMab/AFGz/wBxwf8Akc//ALHd/wDR6/8A////AAAAAAAALC8AAEtQAABocAAAhpAAAKWwAADDzwAA4fAAEe//ADHx/wBR8/8AcfX/AJH3/wCx+f8A0fv/AP///wAAAAAAAC8hAABQNwAAcEwAAJBjAACweQAAz48AAPCmABH/tAAx/74AUf/IAHH/0wCR/9wAsf/lANH/8AD///8AAAAAAAAvDgAAUBgAAHAiAACQLAAAsDYAAM9AAADwSgAR/1sAMf9xAFH/hwBx/50Akf+yALH/yQDR/98A////AAAAAAACLwAABFAAAAZwAAAIkAAACrAAAAvPAAAO8AAAIP8SAD3/MQBb/1EAef9xAJj/kQC1/7EA1P/RAP///wAAAAAAFC8AACJQAAAwcAAAPZAAAEywAABZzwAAZ/AAAHj/EQCK/zEAnP9RAK7/cQDA/5EA0v+xAOT/0QD///8AAAAAACYvAABAUAAAWnAAAHSQAACOsAAAqc8AAMLwAADR/xEA2P8xAN7/UQDj/3EA6f+RAO//sQD2/9EA////AAAAAAAvJgAAUEEAAHBbAACQdAAAsI4AAM+pAADwwwAA/9IRAP/YMQD/3VEA/+RxAP/qkQD/8LEA//bRAP///wAAAAAALxQAAFAiAABwMAAAkD4AALBNAADPWwAA8GkAAP95EQD/ijEA/51RAP+vcQD/wZEA/9KxAP/l0QD///8AAAAAAC8DAABQBAAAcAYAAJAJAACwCgAAzwwAAPAOAAD/IBIA/z4xAP9cUQD/enEA/5eRAP+2sQD/1NEA////AAAAAAAvAA4AUAAXAHAAIQCQACsAsAA2AM8AQADwAEkA/xFaAP8xcAD/UYYA/3GcAP+RsgD/scgA/9HfAP///wAAAAAALwAgAFAANgBwAEwAkABiALAAeADPAI4A8ACkAP8RswD/Mb4A/1HHAP9x0QD/kdwA/7HlAP/R8AD///8AAAAAACwALwBLAFAAaQBwAIcAkAClALAAxADPAOEA8ADwEf8A8jH/APRR/wD2cf8A95H/APmx/wD70f8A////AAAAAAAbAC8ALQBQAD8AcABSAJAAYwCwAHYAzwCIAPAAmRH/AKYx/wC0Uf8AwnH/AM+R/wDcsf8A69H/AP///wAAAAAACAAvAA4AUAAVAHAAGwCQACEAsAAmAM8ALADwAD4R/wBYMf8AcVH/AIxx/wCmkf8Av7H/ANrR/wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwMAAAAAAAAAAAAAAAACBgwMBwIAAAAAAAAAAAAABg4ODg4MBgIAAAAAAAAAAAYODQoODg4KBAAAAAAAAAAGDgwDBQsODg4FAAAAAAAABg4MAgADCg4OBgAAAAAAAAYODAICCg4ODgYAAAAAAAAGDgwCBg4OCwcCAAAAAAAABg4MAwkIBAIAAAAAAAAAAAYODAICAAAAAAAAAAAAAAAGDgwCAAAAAAAAAAAAAAAABg4MAgAAAAAAAAAAAAAAAAYMCAEAAAAAAAAAAAAAAAACAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
- _urls : [
- {
- type: "application/x-suggestions+json",
- method: "GET",
- template: "https://www.bing.com/osjson.aspx",
- params: [
- {
- name: "query",
- value: "{searchTerms}",
- purpose: undefined,
- },
- {
- name: "form",
- value: "OSDJAS",
- purpose: undefined,
- },
- {
- name: "language",
- value: "{moz:locale}",
- purpose: undefined,
- },
- ],
- },
- {
- type: "text/html",
- method: "GET",
- template: "https://www.bing.com/search",
- params: [
- {
- name: "q",
- value: "{searchTerms}",
- purpose: undefined,
- },
- {
- name: "pc",
- value: "MOZI",
- purpose: undefined,
- },
- {
- name: "form",
- value: "MOZCON",
- purpose: "contextmenu",
- },
- {
- name: "form",
- value: "MOZSBR",
- purpose: "searchbar",
- },
- {
- name: "form",
- value: "MOZSPG",
- purpose: "homepage",
- },
- {
- name: "form",
- value: "MOZLBR",
- purpose:"keyword",
- },
- {
- name: "form",
- value: "MOZTSB",
- purpose: "newtab",
- },
- ],
- mozparams: {},
- },
- ],
- },
- };
-
- isSubObjectOf(EXPECTED_ENGINE, engine, "Bing");
-}
diff --git a/browser/components/search/test/browser_bing_behavior.js b/browser/components/search/test/browser_bing_behavior.js
deleted file mode 100644
index bc9b187ec..000000000
--- a/browser/components/search/test/browser_bing_behavior.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Bing search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-
-function test() {
- let engine = Services.search.getEngineByName("Bing");
- ok(engine, "Bing is installed");
-
- let previouslySelectedEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- engine.alias = "b";
-
- let base = "https://www.bing.com/search?q=foo&pc=MOZI";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base + "&form=MOZSBR", "Check search URL for 'foo'");
-
- waitForExplicitFinish();
-
- var gCurrTest;
- var gTests = [
- {
- name: "context menu search",
- searchURL: base + "&form=MOZCON",
- run: function () {
- // Simulate a contextmenu search
- // FIXME: This is a bit "low-level"...
- BrowserSearch.loadSearch("foo", false, "contextmenu");
- }
- },
- {
- name: "keyword search",
- searchURL: base + "&form=MOZLBR",
- run: function () {
- gURLBar.value = "? foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "keyword search with alias",
- searchURL: base + "&form=MOZLBR",
- run: function () {
- gURLBar.value = "b foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "search bar search",
- searchURL: base + "&form=MOZSBR",
- run: function () {
- let sb = BrowserSearch.searchBar;
- sb.focus();
- sb.value = "foo";
- registerCleanupFunction(function () {
- sb.value = "";
- });
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "new tab search",
- searchURL: base + "&form=MOZTSB",
- run: function () {
- function doSearch(doc) {
- // Re-add the listener, and perform a search
- gBrowser.addProgressListener(listener);
- doc.getElementById("newtab-search-text").value = "foo";
- doc.getElementById("newtab-search-submit").click();
- }
-
- // load about:newtab, but remove the listener first so it doesn't
- // get in the way
- gBrowser.removeProgressListener(listener);
- gBrowser.loadURI("about:newtab");
- info("Waiting for about:newtab load");
- tab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- tab.linkedBrowser.removeEventListener("load", load, true);
-
- // Observe page setup
- let win = gBrowser.contentWindow;
- if (win.gSearch.currentEngineName ==
- Services.search.currentEngine.name) {
- doSearch(win.document);
- }
- else {
- info("Waiting for newtab search init");
- win.addEventListener("ContentSearchService", function done(event) {
- info("Got newtab search event " + event.detail.type);
- if (event.detail.type == "State") {
- win.removeEventListener("ContentSearchService", done);
- // Let gSearch respond to the event before continuing.
- executeSoon(() => doSearch(win.document));
- }
- });
- }
- }, true);
- }
- }
- ];
-
- function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- info("Running : " + gCurrTest.name);
- executeSoon(gCurrTest.run);
- } else {
- finish();
- }
- }
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onStateChange(webProgress, req, flags, status) {
- info("onStateChange");
- // Only care about top-level document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart) || !webProgress.isTopLevel)
- return;
-
- if (req.originalURI.spec == "about:blank")
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- }
-
- registerCleanupFunction(function () {
- engine.alias = undefined;
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- Services.search.currentEngine = previouslySelectedEngine;
- });
-
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- gBrowser.addProgressListener(listener);
- nextTest();
- }, true);
-}
diff --git a/browser/components/search/test/browser_contextSearchTabPosition.js b/browser/components/search/test/browser_contextSearchTabPosition.js
deleted file mode 100644
index 21a8c1130..000000000
--- a/browser/components/search/test/browser_contextSearchTabPosition.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* 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/. */
-
-add_task(function* test() {
- yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]});
- let engine = yield promiseNewEngine("testEngine.xml");
- let histogramKey = "other-" + engine.name + ".contextmenu";
- let numSearchesBefore = 0;
-
- try {
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- if (histogramKey in hs) {
- numSearchesBefore = hs[histogramKey].sum;
- }
- } catch (ex) {
- // No searches performed yet, not a problem, |numSearchesBefore| is 0.
- }
-
- let tabs = [];
- let tabsLoadedDeferred = new Deferred();
-
- function tabAdded(event) {
- let tab = event.target;
- tabs.push(tab);
-
- // We wait for the blank tab and the two context searches tabs to open.
- if (tabs.length == 3) {
- tabsLoadedDeferred.resolve();
- }
- }
-
- let container = gBrowser.tabContainer;
- container.addEventListener("TabOpen", tabAdded, false);
-
- gBrowser.addTab("about:blank");
- BrowserSearch.loadSearchFromContext("mozilla");
- BrowserSearch.loadSearchFromContext("firefox");
-
- // Wait for all the tabs to open.
- yield tabsLoadedDeferred.promise;
-
- is(tabs[0], gBrowser.tabs[3], "blank tab has been pushed to the end");
- is(tabs[1], gBrowser.tabs[1], "first search tab opens next to the current tab");
- is(tabs[2], gBrowser.tabs[2], "second search tab opens next to the first search tab");
-
- container.removeEventListener("TabOpen", tabAdded, false);
- tabs.forEach(gBrowser.removeTab, gBrowser);
-
- // Make sure that the context searches are correctly recorded.
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- Assert.ok(histogramKey in hs, "The histogram must contain the correct key");
- Assert.equal(hs[histogramKey].sum, numSearchesBefore + 2,
- "The histogram must contain the correct search count");
-});
-
-function Deferred() {
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
-}
diff --git a/browser/components/search/test/browser_contextmenu.js b/browser/components/search/test/browser_contextmenu.js
deleted file mode 100644
index c485242b4..000000000
--- a/browser/components/search/test/browser_contextmenu.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * * http://creativecommons.org/publicdomain/zero/1.0/ */
-/*
- * Test searching for the selected text using the context menu
- */
-
-add_task(function* () {
- const ss = Services.search;
- const ENGINE_NAME = "Foo";
- var contextMenu;
-
- // We want select events to be fired.
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({"set": [["dom.select_events.enabled", true]]}, resolve));
-
- let envService = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
- let originalValue = envService.get("XPCSHELL_TEST_PROFILE_DIR");
- envService.set("XPCSHELL_TEST_PROFILE_DIR", "1");
-
- let url = "chrome://mochitests/content/browser/browser/components/search/test/";
- let resProt = Services.io.getProtocolHandler("resource")
- .QueryInterface(Ci.nsIResProtocolHandler);
- let originalSubstitution = resProt.getSubstitution("search-plugins");
- resProt.setSubstitution("search-plugins",
- Services.io.newURI(url, null, null));
-
- let searchDonePromise;
- yield new Promise(resolve => {
- function observer(aSub, aTopic, aData) {
- switch (aData) {
- case "engine-added":
- var engine = ss.getEngineByName(ENGINE_NAME);
- ok(engine, "Engine was added.");
- ss.currentEngine = engine;
- envService.set("XPCSHELL_TEST_PROFILE_DIR", originalValue);
- resProt.setSubstitution("search-plugins", originalSubstitution);
- break;
- case "engine-current":
- is(ss.currentEngine.name, ENGINE_NAME, "currentEngine set");
- resolve();
- break;
- case "engine-removed":
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- if (searchDonePromise) {
- searchDonePromise();
- }
- break;
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- ss.addEngine("resource://search-plugins/testEngine_mozsearch.xml",
- null, "data:image/x-icon,%00", false);
- });
-
- contextMenu = document.getElementById("contentAreaContextMenu");
- ok(contextMenu, "Got context menu XUL");
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/plain;charset=utf8,test%20search");
-
- yield ContentTask.spawn(tab.linkedBrowser, "", function*() {
- return new Promise(resolve => {
- content.document.addEventListener("selectionchange", function selectionChanged() {
- content.document.removeEventListener("selectionchange", selectionChanged);
- resolve();
- });
- content.document.getSelection().selectAllChildren(content.document.body);
- });
- });
-
- var eventDetails = { type: "contextmenu", button: 2 };
-
- let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- BrowserTestUtils.synthesizeMouseAtCenter("body", eventDetails, gBrowser.selectedBrowser);
- yield popupPromise;
-
- info("checkContextMenu");
- var searchItem = contextMenu.getElementsByAttribute("id", "context-searchselect")[0];
- ok(searchItem, "Got search context menu item");
- is(searchItem.label, 'Search ' + ENGINE_NAME + ' for \u201ctest search\u201d', "Check context menu label");
- is(searchItem.disabled, false, "Check that search context menu item is enabled");
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
- searchItem.click();
- });
-
- is(gBrowser.currentURI.spec,
- "http://mochi.test:8888/browser/browser/components/search/test/?test=test+search&ie=utf-8&channel=contextsearch",
- "Checking context menu search URL");
-
- contextMenu.hidePopup();
-
- // Remove the tab opened by the search
- gBrowser.removeCurrentTab();
-
- yield new Promise(resolve => {
- searchDonePromise = resolve;
- ss.removeEngine(ss.currentEngine);
- });
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/search/test/browser_google.js b/browser/components/search/test/browser_google.js
deleted file mode 100644
index 2b0cabea7..000000000
--- a/browser/components/search/test/browser_google.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Google search plugin URLs
- */
-
-"use strict";
-
-function test() {
- let engine = Services.search.getEngineByName("Google");
- ok(engine, "Google");
-
- let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b";
- let keywordBase = base + "-ab";
-
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base, "Check search URL for 'foo'");
- url = engine.getSubmission("foo", null, "contextmenu").uri.spec;
- is(url, base, "Check context menu search URL for 'foo'");
- url = engine.getSubmission("foo", null, "keyword").uri.spec;
- is(url, keywordBase, "Check keyword search URL for 'foo'");
- url = engine.getSubmission("foo", null, "searchbar").uri.spec;
- is(url, base, "Check search bar search URL for 'foo'");
- url = engine.getSubmission("foo", null, "homepage").uri.spec;
- is(url, base, "Check homepage search URL for 'foo'");
- url = engine.getSubmission("foo", null, "newtab").uri.spec;
- is(url, base, "Check newtab search URL for 'foo'");
-
- // Check search suggestion URL.
- url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec;
- is(url, "https://www.google.com/complete/search?client=firefox&q=foo", "Check search suggestion URL for 'foo'");
-
- // Check result parsing and alternate domains.
- let alternateBase = base.replace("www.google.com", "www.google.fr");
- is(Services.search.parseSubmissionURL(base).terms, "foo",
- "Check result parsing");
- is(Services.search.parseSubmissionURL(alternateBase).terms, "foo",
- "Check alternate domain");
-
- // Check all other engine properties.
- const EXPECTED_ENGINE = {
- name: "Google",
- alias: null,
- description: "Google Search",
- searchForm: "https://www.google.com/search?q=&ie=utf-8&oe=utf-8&client=firefox-b",
- hidden: false,
- wrappedJSObject: {
- queryCharset: "UTF-8",
- "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///zD9/f2W/f392P39/fn9/f35/f391/39/ZT+/v4uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v7+Cf39/Zn///////////////////////////////////////////39/ZX///8IAAAAAAAAAAAAAAAA/v7+Cf39/cH/////+v35/7TZp/92ul3/WKs6/1iqOv9yuFn/rNWd//j79v///////f39v////wgAAAAAAAAAAP39/Zn/////7PXp/3G3WP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP+Or1j//vDo///////9/f2VAAAAAP///zD/////+vz5/3G3V/9TqDT/WKo6/6LQkf/U6cz/1urO/6rUm/+Zo0r/8IZB//adZ////v7///////7+/i79/f2Y/////4nWzf9Lqkj/Vqo4/9Xqzv///////////////////////ebY//SHRv/0hUL//NjD///////9/f2U/f392v////8sxPH/Ebzt/43RsP/////////////////////////////////4roL/9IVC//i1jf///////f391/39/fr/////Cr37/wW8+/+16/7/////////////////9IVC//SFQv/0hUL/9IVC//SFQv/3pnX///////39/fn9/f36/////wu++/8FvPv/tuz+//////////////////SFQv/0hUL/9IVC//SFQv/0hUL/96p7///////9/f35/f392/////81yfz/CrL5/2uk9v///////////////////////////////////////////////////////f392P39/Zn/////ks/7/zdS7P84Rur/0NT6///////////////////////9/f////////////////////////39/Zb+/v4y//////n5/v9WYu3/NUPq/ztJ6/+VnPT/z9L6/9HU+v+WnfT/Ul7t/+Hj/P////////////////////8wAAAAAP39/Z3/////6Or9/1hj7v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v9sdvD////////////9/f2YAAAAAAAAAAD///8K/f39w//////5+f7/paz2/11p7v88Suv/Okfq/1pm7v+iqfX/+fn+///////9/f3B/v7+CQAAAAAAAAAAAAAAAP///wr9/f2d///////////////////////////////////////////9/f2Z/v7+CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/jL9/f2Z/f392/39/fr9/f36/f392v39/Zj///8wAAAAAAAAAAAAAAAAAAAAAPAPAADAAwAAgAEAAIABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAACAAQAAwAMAAPAPAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/g3+/v5X/f39mf39/cj9/f3q/f39+f39/fn9/f3q/f39yP39/Zn+/v5W////DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/iT9/f2c/f399f/////////////////////////////////////////////////////9/f31/f39mv7+/iMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/gn9/f2K/f39+////////////////////////////////////////////////////////////////////////////f39+v39/Yf///8IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+/v4k/f390v////////////////////////////////////////////////////////////////////////////////////////////////39/dD///8iAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////MP39/er//////////////////////////+r05v+v16H/gsBs/2WxSf9Wqjj/Vqk3/2OwRv99vWX/pdKV/97u2P////////////////////////////39/ej+/v4vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/iT9/f3q/////////////////////+v15/+Pxnv/VKk2/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/36+Z//d7tf///////////////////////39/ej///8iAAAAAAAAAAAAAAAAAAAAAAAAAAD///8K/f390//////////////////////E4bn/XKw+/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1apN/+x0pv///////////////////////39/dD///8IAAAAAAAAAAAAAAAAAAAAAP39/Yv/////////////////////sdij/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/YKU1/8qOPv/5wZ////////////////////////39/YcAAAAAAAAAAAAAAAD+/v4l/f39+////////////////8Lgt/9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9utlT/n86N/7faqv+426v/pdKV/3u8ZP9UqDX/U6g0/3egN//jiUH/9IVC//SFQv/82MP//////////////////f39+v7+/iMAAAAAAAAAAP39/Z3////////////////q9Ob/W6w+/1OoNP9TqDT/U6g0/1OoNP9nskz/zOXC/////////////////////////////////+Dv2v+osWP/8YVC//SFQv/0hUL/9IVC//WQVP/++fb//////////////////f39mgAAAAD+/v4O/f399v///////////////4LHj/9TqDT/U6g0/1OoNP9TqDT/dblc//L58P/////////////////////////////////////////////8+v/3p3f/9IVC//SFQv/0hUL/9IVC//rIqf/////////////////9/f31////DP7+/ln////////////////f9v7/Cbz2/zOwhv9TqDT/U6g0/2KwRv/v9+z///////////////////////////////////////////////////////738//1kFT/9IVC//SFQv/0hUL/9plg///////////////////////+/v5W/f39nP///////////////4jf/f8FvPv/Bbz7/yG1s/9QqDz/vN2w//////////////////////////////////////////////////////////////////rHqP/0hUL/9IVC//SFQv/0hUL//vDn//////////////////39/Zn9/f3L////////////////R878/wW8+/8FvPv/Bbz7/y7C5P/7/fr//////////////////////////////////////////////////////////////////ere//SFQv/0hUL/9IVC//SFQv/718H//////////////////f39yP39/ez///////////////8cwvv/Bbz7/wW8+/8FvPv/WNL8///////////////////////////////////////0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//rIqv/////////////////9/f3q/f39+v///////////////we9+/8FvPv/Bbz7/wW8+/993P3///////////////////////////////////////SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/+cGf//////////////////39/fn9/f36////////////////B737/wW8+/8FvPv/Bbz7/33c/f//////////////////////////////////////9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/6xaX//////////////////f39+f39/e3///////////////8cwvv/Bbz7/wW8+/8FvPv/WdP8///////////////////////////////////////0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//vVv//////////////////9/f3q/f39y////////////////0bN/P8FvPv/Bbz7/wW8+/8hrvn/+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/cj9/f2c////////////////ht/9/wW8+/8FvPv/FZP1/zRJ6/+zuPf//////////////////////////////////////////////////////////////////////////////////////////////////////////////////f39mf7+/lr////////////////d9v7/B7n7/yB38f81Q+r/NUPq/0hV7P/u8P3////////////////////////////////////////////////////////////////////////////////////////////////////////////+/v5X////D/39/ff///////////////9tkPT/NUPq/zVD6v81Q+r/NUPq/2Fs7//y8v7////////////////////////////////////////////09f7//////////////////////////////////////////////////f399f7+/g0AAAAA/f39n////////////////+Tm/P89Suv/NUPq/zVD6v81Q+r/NUPq/1Bc7f/IzPn/////////////////////////////////x8v5/0xY7P+MlPP////////////////////////////////////////////9/f2cAAAAAAAAAAD+/v4n/f39/P///////////////7W69/81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v9ZZe7/k5v0/6609/+vtff/lJv0/1pm7v81Q+r/NUPq/zVD6v+GjvL//v7//////////////////////////////f39+/7+/iQAAAAAAAAAAAAAAAD9/f2N/////////////////////6Cn9f81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v+BivL////////////////////////////9/f2KAAAAAAAAAAAAAAAAAAAAAP7+/gv9/f3V/////////////////////7W69/8+S+v/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/P0zr/7q/+P///////////////////////f390v7+/gkAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/ib9/f3r/////////////////////+Xn/P94gfH/NkTq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NkTq/3Z/8f/l5/z///////////////////////39/er+/v4kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/jL9/f3r///////////////////////////k5vz/nqX1/2p08P9IVez/OEbq/zdF6v9GU+z/aHLv/5qh9f/i5Pz////////////////////////////9/f3q////MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/ib9/f3V/////////////////////////////////////////////////////////////////////////////////////////////////f390v7+/iQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wr9/f2N/f39/P///////////////////////////////////////////////////////////////////////////f39+/39/Yv+/v4JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+/v4n/f39n/39/ff//////////////////////////////////////////////////////f399v39/Z3+/v4lAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v7+Dv7+/lr9/f2c/f39y/39/e39/f36/f39+v39/ez9/f3L/f39nP7+/ln+/v4OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/AA///AAD//AAAP/gAAB/wAAAP4AAAB8AAAAPAAAADgAAAAYAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAABgAAAAcAAAAPAAAAD4AAAB/AAAA/4AAAf/AAAP/8AAP//wAP/",
- _urls : [
- {
- type: "application/x-suggestions+json",
- method: "GET",
- template: "https://www.google.com/complete/search?client=firefox&q={searchTerms}",
- params: "",
- },
- {
- type: "text/html",
- method: "GET",
- template: "https://www.google.com/search",
- params: [
- {
- "name": "q",
- "value": "{searchTerms}",
- "purpose": undefined,
- },
- {
- "name": "ie",
- "value": "utf-8",
- "purpose": undefined,
- },
- {
- "name": "oe",
- "value": "utf-8",
- "purpose": undefined,
- },
- {
- "name": "client",
- "value": "firefox-b-ab",
- "purpose": "keyword",
- },
- {
- "name": "client",
- "value": "firefox-b",
- "purpose": "searchbar",
- },
- ],
- mozparams: {
- },
- },
- ],
- },
- };
-
- isSubObjectOf(EXPECTED_ENGINE, engine, "Google");
-}
diff --git a/browser/components/search/test/browser_google_behavior.js b/browser/components/search/test/browser_google_behavior.js
deleted file mode 100644
index 55405bb29..000000000
--- a/browser/components/search/test/browser_google_behavior.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Google search plugin URLs
- */
-
-"use strict";
-
-function test() {
- let engine = Services.search.getEngineByName("Google");
- ok(engine, "Google is installed");
-
- let previouslySelectedEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- engine.alias = "g";
-
- let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b";
- let keywordBase = base + "-ab";
-
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base, "Check search URL for 'foo'");
-
- waitForExplicitFinish();
-
- var gCurrTest;
- var gTests = [
- {
- name: "context menu search",
- searchURL: base,
- run: function () {
- // Simulate a contextmenu search
- // FIXME: This is a bit "low-level"...
- BrowserSearch.loadSearch("foo", false, "contextmenu");
- }
- },
- {
- name: "keyword search",
- searchURL: keywordBase,
- run: function () {
- gURLBar.value = "? foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "keyword search",
- searchURL: keywordBase,
- run: function () {
- gURLBar.value = "g foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "search bar search",
- searchURL: base,
- run: function () {
- let sb = BrowserSearch.searchBar;
- sb.focus();
- sb.value = "foo";
- registerCleanupFunction(function () {
- sb.value = "";
- });
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "new tab search",
- searchURL: base,
- run: function () {
- function doSearch(doc) {
- // Re-add the listener, and perform a search
- gBrowser.addProgressListener(listener);
- doc.getElementById("newtab-search-text").value = "foo";
- doc.getElementById("newtab-search-submit").click();
- }
-
- // load about:newtab, but remove the listener first so it doesn't
- // get in the way
- gBrowser.removeProgressListener(listener);
- gBrowser.loadURI("about:newtab");
- info("Waiting for about:newtab load");
- tab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- tab.linkedBrowser.removeEventListener("load", load, true);
-
- // Observe page setup
- let win = gBrowser.contentWindow;
- if (win.gSearch.currentEngineName ==
- Services.search.currentEngine.name) {
- doSearch(win.document);
- }
- else {
- info("Waiting for newtab search init");
- win.addEventListener("ContentSearchService", function done(event) {
- info("Got newtab search event " + event.detail.type);
- if (event.detail.type == "State") {
- win.removeEventListener("ContentSearchService", done);
- // Let gSearch respond to the event before continuing.
- executeSoon(() => doSearch(win.document));
- }
- });
- }
- }, true);
- }
- }
- ];
-
- function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- info("Running : " + gCurrTest.name);
- executeSoon(gCurrTest.run);
- } else {
- finish();
- }
- }
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onStateChange(webProgress, req, flags, status) {
- info("onStateChange");
- // Only care about top-level document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart) || !webProgress.isTopLevel)
- return;
-
- if (req.originalURI.spec == "about:blank")
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- }
-
- registerCleanupFunction(function () {
- engine.alias = undefined;
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- Services.search.currentEngine = previouslySelectedEngine;
- });
-
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- gBrowser.addProgressListener(listener);
- nextTest();
- }, true);
-}
diff --git a/browser/components/search/test/browser_google_codes.js b/browser/components/search/test/browser_google_codes.js
deleted file mode 100644
index e166b6868..000000000
--- a/browser/components/search/test/browser_google_codes.js
+++ /dev/null
@@ -1,161 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const kUrlPref = "geoSpecificDefaults.url";
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-var originalGeoURL;
-
-/**
- * Clean the profile of any cache file left from a previous run.
- * Returns a boolean indicating if the cache file existed.
- */
-function removeCacheFile()
-{
- const CACHE_FILENAME = "search.json.mozlz4";
-
- let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
- file.append(CACHE_FILENAME);
- if (file.exists()) {
- file.remove(false);
- return true;
- }
- return false;
-}
-
-/**
- * Returns a promise that is resolved when an observer notification from the
- * search service fires with the specified data.
- *
- * @param aExpectedData
- * The value the observer notification sends that causes us to resolve
- * the promise.
- */
-function waitForSearchNotification(aExpectedData, aCallback) {
- const SEARCH_SERVICE_TOPIC = "browser-search-service";
- Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
- if (aData != aExpectedData)
- return;
-
- Services.obs.removeObserver(observer, SEARCH_SERVICE_TOPIC);
- aCallback();
- }, SEARCH_SERVICE_TOPIC, false);
-}
-
-function asyncInit() {
- return new Promise(resolve => {
- Services.search.init(function() {
- ok(Services.search.isInitialized, "search service should be initialized");
- resolve();
- });
- });
-}
-
-function asyncReInit() {
- const kLocalePref = "general.useragent.locale";
-
- let promise = new Promise(resolve => {
- waitForSearchNotification("reinit-complete", resolve);
- });
-
- Services.search.QueryInterface(Ci.nsIObserver)
- .observe(null, "nsPref:changed", kLocalePref);
-
- return promise;
-}
-
-let gEngineCount;
-
-add_task(function* preparation() {
- // ContentSearch is interferring with our async re-initializations of the
- // search service: once _initServicePromise has resolved, it will access
- // the search service, thus causing unpredictable behavior due to
- // synchronous initializations of the service.
- let originalContentSearchPromise = ContentSearch._initServicePromise;
- ContentSearch._initServicePromise = new Promise(resolve => {
- registerCleanupFunction(() => {
- ContentSearch._initServicePromise = originalContentSearchPromise;
- resolve();
- });
- });
-
- yield asyncInit();
- gEngineCount = Services.search.getVisibleEngines().length;
-
- waitForSearchNotification("uninit-complete", () => {
- // Verify search service is not initialized
- is(Services.search.isInitialized, false, "Search service should NOT be initialized");
-
- removeCacheFile();
-
- // Geo specific defaults won't be fetched if there's no country code.
- Services.prefs.setCharPref("browser.search.geoip.url",
- 'data:application/json,{"country_code": "US"}');
-
- Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true);
-
- // Make the new Google the only engine
- originalGeoURL = Services.prefs.getCharPref(BROWSER_SEARCH_PREF + kUrlPref);
- let geoUrl = 'data:application/json,{"interval": 31536000, "settings": {"searchDefault": "Google", "visibleDefaultEngines": ["google"]}}';
- Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, geoUrl);
- });
-
- yield asyncReInit();
-
- yield new Promise(resolve => {
- waitForSearchNotification("write-cache-to-disk-complete", resolve);
- });
-});
-
-add_task(function* tests() {
- let engines = Services.search.getEngines();
- is(Services.search.currentEngine.name, "Google", "Search engine should be Google");
- is(engines.length, 1, "There should only be one engine");
-
- let engine = Services.search.getEngineByName("Google");
- ok(engine, "Google");
-
- let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b";
-
- // Keyword uses a slightly different code
- let keywordBase = base + "-ab";
-
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo", null, "contextmenu").uri.spec;
- is(url, base, "Check context menu search URL for 'foo'");
- url = engine.getSubmission("foo", null, "keyword").uri.spec;
- is(url, keywordBase, "Check keyword search URL for 'foo'");
- url = engine.getSubmission("foo", null, "searchbar").uri.spec;
- is(url, base, "Check search bar search URL for 'foo'");
- url = engine.getSubmission("foo", null, "homepage").uri.spec;
- is(url, base, "Check homepage search URL for 'foo'");
- url = engine.getSubmission("foo", null, "newtab").uri.spec;
- is(url, base, "Check newtab search URL for 'foo'");
- url = engine.getSubmission("foo", null, "system").uri.spec;
- is(url, base, "Check system search URL for 'foo'");
-});
-
-
-add_task(function* cleanup() {
- waitForSearchNotification("uninit-complete", () => {
- // Verify search service is not initialized
- is(Services.search.isInitialized, false,
- "Search service should NOT be initialized");
- removeCacheFile();
-
- Services.prefs.clearUserPref("browser.search.geoip.url");
-
- // We can't clear the pref because it's set to false by testing/profiles/prefs_general.js
- Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", false);
-
- Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, originalGeoURL);
- });
-
- yield asyncReInit();
- is(gEngineCount, Services.search.getVisibleEngines().length,
- "correct engine count after cleanup");
-});
diff --git a/browser/components/search/test/browser_healthreport.js b/browser/components/search/test/browser_healthreport.js
deleted file mode 100644
index c68ad174c..000000000
--- a/browser/components/search/test/browser_healthreport.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-
-function test() {
- waitForExplicitFinish();
- resetPreferences();
-
- function testTelemetry() {
- // Find the right bucket for the "Foo" engine.
- let engine = Services.search.getEngineByName("Foo");
- let histogramKey = (engine.identifier || "other-Foo") + ".searchbar";
- let numSearchesBefore = 0;
- try {
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- if (histogramKey in hs) {
- numSearchesBefore = hs[histogramKey].sum;
- }
- } catch (ex) {
- // No searches performed yet, not a problem, |numSearchesBefore| is 0.
- }
-
- // Now perform a search and ensure the count is incremented.
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- let searchBar = BrowserSearch.searchBar;
-
- searchBar.value = "firefox health report";
- searchBar.focus();
-
- function afterSearch() {
- searchBar.value = "";
- gBrowser.removeTab(tab);
-
- // Make sure that the context searches are correctly recorded.
- let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
- Assert.ok(histogramKey in hs, "The histogram must contain the correct key");
- Assert.equal(hs[histogramKey].sum, numSearchesBefore + 1,
- "Performing a search increments the related SEARCH_COUNTS key by 1.");
-
- let engine = Services.search.getEngineByName("Foo");
- Services.search.removeEngine(engine);
- }
-
- EventUtils.synthesizeKey("VK_RETURN", {});
- executeSoon(() => executeSoon(afterSearch));
- }
-
- function observer(subject, topic, data) {
- switch (data) {
- case "engine-added":
- let engine = Services.search.getEngineByName("Foo");
- ok(engine, "Engine was added.");
- Services.search.currentEngine = engine;
- break;
-
- case "engine-current":
- is(Services.search.currentEngine.name, "Foo", "Current engine is Foo");
- testTelemetry();
- break;
-
- case "engine-removed":
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- finish();
- break;
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]}).then(function() {
- Services.search.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml",
- null, "data:image/x-icon,%00", false);
- });
-}
-
-function resetPreferences() {
- Preferences.resetBranch("datareporting.policy.");
- Preferences.set("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
-}
diff --git a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js
deleted file mode 100644
index 9a584feb6..000000000
--- a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/* 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/. */
-const testPref = "Foo,FooDupe";
-
-function promiseNewEngine(basename) {
- return new Promise((resolve, reject) => {
- info("Waiting for engine to be added: " + basename);
- Services.search.init({
- onInitComplete: function() {
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- reject();
- }
- });
- }
- });
- });
-}
-
-add_task(function* test_remove() {
- yield promiseNewEngine("testEngine_dupe.xml");
- yield promiseNewEngine("testEngine.xml");
- Services.prefs.setCharPref("browser.search.hiddenOneOffs", testPref);
-
- info("Removing testEngine_dupe.xml");
- Services.search.removeEngine(Services.search.getEngineByName("FooDupe"));
-
- let hiddenOneOffs =
- Services.prefs.getCharPref("browser.search.hiddenOneOffs").split(",");
-
- is(hiddenOneOffs.length, 1,
- "hiddenOneOffs has the correct engine count post removal.");
- is(hiddenOneOffs.some(x => x == "FooDupe"), false,
- "Removed Engine is not in hiddenOneOffs after removal");
- is(hiddenOneOffs.some(x => x == "Foo"), true,
- "Current hidden engine is not affected by removal.");
-
- info("Removing testEngine.xml");
- Services.search.removeEngine(Services.search.getEngineByName("Foo"));
-
- is(Services.prefs.getCharPref("browser.search.hiddenOneOffs"), "",
- "hiddenOneOffs is empty after removing all hidden engines.");
-});
-
-add_task(function* test_add() {
- yield promiseNewEngine("testEngine.xml");
- info("setting prefs to " + testPref);
- Services.prefs.setCharPref("browser.search.hiddenOneOffs", testPref);
- yield promiseNewEngine("testEngine_dupe.xml");
-
- let hiddenOneOffs =
- Services.prefs.getCharPref("browser.search.hiddenOneOffs").split(",");
-
- is(hiddenOneOffs.length, 1,
- "hiddenOneOffs has the correct number of hidden engines present post add.");
- is(hiddenOneOffs.some(x => x == "FooDupe"), false,
- "Added engine is not present in hidden list.");
- is(hiddenOneOffs.some(x => x == "Foo"), true,
- "Adding an engine does not remove engines from hidden list.");
-});
-
-add_task(function* test_diacritics() {
- const diacritic_engine = "Foo \u2661";
- let Preferences =
- Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-
- Preferences.set("browser.search.hiddenOneOffs", diacritic_engine);
- yield promiseNewEngine("testEngine_diacritics.xml");
-
- let hiddenOneOffs =
- Preferences.get("browser.search.hiddenOneOffs").split(",");
- is(hiddenOneOffs.some(x => x == diacritic_engine), false,
- "Observer cleans up added hidden engines that include a diacritic.");
-
- Preferences.set("browser.search.hiddenOneOffs", diacritic_engine);
-
- info("Removing testEngine_diacritics.xml");
- Services.search.removeEngine(Services.search.getEngineByName(diacritic_engine));
-
- hiddenOneOffs =
- Preferences.get("browser.search.hiddenOneOffs").split(",");
- is(hiddenOneOffs.some(x => x == diacritic_engine), false,
- "Observer cleans up removed hidden engines that include a diacritic.");
-});
-
-registerCleanupFunction(() => {
- info("Removing testEngine.xml");
- Services.search.removeEngine(Services.search.getEngineByName("Foo"));
- info("Removing testEngine_dupe.xml");
- Services.search.removeEngine(Services.search.getEngineByName("FooDupe"));
- Services.prefs.clearUserPref("browser.search.hiddenOneOffs");
-});
diff --git a/browser/components/search/test/browser_hiddenOneOffs_diacritics.js b/browser/components/search/test/browser_hiddenOneOffs_diacritics.js
deleted file mode 100644
index db24c7192..000000000
--- a/browser/components/search/test/browser_hiddenOneOffs_diacritics.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* 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/. */
-// Tests that keyboard navigation in the search panel works as designed.
-
-const searchbar = document.getElementById("searchbar");
-const textbox = searchbar._textbox;
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid",
- "searchbar-search-button");
-
-const diacritic_engine = "Foo \u2661";
-
-var Preferences =
- Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-
-add_task(function* init() {
- let currentEngine = Services.search.currentEngine;
- yield promiseNewEngine("testEngine_diacritics.xml", {setAsCurrent: false});
- registerCleanupFunction(() => {
- Services.search.currentEngine = currentEngine;
- Services.prefs.clearUserPref("browser.search.hiddenOneOffs");
- });
-});
-
-add_task(function* test_hidden() {
- Preferences.set("browser.search.hiddenOneOffs", diacritic_engine);
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
-
- ok(!getOneOffs().some(x => x.getAttribute("tooltiptext") == diacritic_engine),
- "Search engines with diacritics are hidden when added to hiddenOneOffs preference.");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- info("Closing search panel");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-});
-
-add_task(function* test_shown() {
- Preferences.set("browser.search.hiddenOneOffs", "");
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- });
- yield promise;
-
- ok(getOneOffs().some(x => x.getAttribute("tooltiptext") == diacritic_engine),
- "Search engines with diacritics are shown when removed from hiddenOneOffs preference.");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-});
diff --git a/browser/components/search/test/browser_oneOffContextMenu.js b/browser/components/search/test/browser_oneOffContextMenu.js
deleted file mode 100644
index 69207923b..000000000
--- a/browser/components/search/test/browser_oneOffContextMenu.js
+++ /dev/null
@@ -1,105 +0,0 @@
-"use strict";
-
-const TEST_ENGINE_NAME = "Foo";
-const TEST_ENGINE_BASENAME = "testEngine.xml";
-
-const searchbar = document.getElementById("searchbar");
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const searchIcon = document.getAnonymousElementByAttribute(
- searchbar, "anonid", "searchbar-search-button"
-);
-const oneOffBinding = document.getAnonymousElementByAttribute(
- searchPopup, "anonid", "search-one-off-buttons"
-);
-const contextMenu = document.getAnonymousElementByAttribute(
- oneOffBinding, "anonid", "search-one-offs-context-menu"
-);
-const oneOffButtons = document.getAnonymousElementByAttribute(
- oneOffBinding, "anonid", "search-panel-one-offs"
-);
-const searchInNewTabMenuItem = document.getAnonymousElementByAttribute(
- oneOffBinding, "anonid", "search-one-offs-context-open-in-new-tab"
-);
-
-add_task(function* init() {
- yield promiseNewEngine(TEST_ENGINE_BASENAME, {
- setAsCurrent: false,
- });
-});
-
-add_task(function* extendedTelemetryDisabled() {
- yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", false]]});
- yield doTest();
- checkTelemetry("other");
-});
-
-add_task(function* extendedTelemetryEnabled() {
- yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]});
- yield doTest();
- checkTelemetry("other-" + TEST_ENGINE_NAME);
-});
-
-function* doTest() {
- // Open the popup.
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
-
- // Get the one-off button for the test engine.
- let oneOffButton;
- for (let node of oneOffButtons.childNodes) {
- if (node.engine && node.engine.name == TEST_ENGINE_NAME) {
- oneOffButton = node;
- break;
- }
- }
- Assert.notEqual(oneOffButton, undefined,
- "One-off for test engine should exist");
-
- // Open the context menu on the one-off.
- promise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(oneOffButton, {
- type: "contextmenu",
- button: 2,
- });
- yield promise;
-
- // Click the Search in New Tab menu item.
- promise = BrowserTestUtils.waitForNewTab(gBrowser);
- EventUtils.synthesizeMouseAtCenter(searchInNewTabMenuItem, {});
- let tab = yield promise;
-
- // By default the search will open in the background and the popup will stay open:
- promise = promiseEvent(searchPopup, "popuphidden");
- info("Closing search panel");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- // Check the loaded tab.
- Assert.equal(tab.linkedBrowser.currentURI.spec,
- "http://mochi.test:8888/browser/browser/components/search/test/",
- "Expected search tab should have loaded");
-
- yield BrowserTestUtils.removeTab(tab);
-
- // Move the cursor out of the panel area to avoid messing with other tests.
- yield EventUtils.synthesizeNativeMouseMove(searchbar);
-}
-
-function checkTelemetry(expectedEngineName) {
- let propertyPath = [
- "countableEvents",
- "__DEFAULT__",
- "search-oneoff",
- expectedEngineName + ".oneoff-context-searchbar",
- "unknown",
- "tab-background",
- ];
- let telem = BrowserUITelemetry.getToolbarMeasures();
- for (let prop of propertyPath) {
- Assert.ok(prop in telem, "Property " + prop + " should be in the telemetry");
- telem = telem[prop];
- }
- Assert.equal(telem, 1, "Click count");
-}
diff --git a/browser/components/search/test/browser_oneOffContextMenu_setDefault.js b/browser/components/search/test/browser_oneOffContextMenu_setDefault.js
deleted file mode 100644
index ff49cb0c6..000000000
--- a/browser/components/search/test/browser_oneOffContextMenu_setDefault.js
+++ /dev/null
@@ -1,195 +0,0 @@
-"use strict";
-
-const TEST_ENGINE_NAME = "Foo";
-const TEST_ENGINE_BASENAME = "testEngine.xml";
-const SEARCHBAR_BASE_ID = "searchbar-engine-one-off-item-";
-const URLBAR_BASE_ID = "urlbar-engine-one-off-item-";
-const ONEOFF_URLBAR_PREF = "browser.urlbar.oneOffSearches";
-
-const searchbar = document.getElementById("searchbar");
-const urlbar = document.getElementById("urlbar");
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const urlbarPopup = document.getElementById("PopupAutoCompleteRichResult");
-const searchIcon = document.getAnonymousElementByAttribute(
- searchbar, "anonid", "searchbar-search-button"
-);
-const searchOneOffBinding = document.getAnonymousElementByAttribute(
- searchPopup, "anonid", "search-one-off-buttons"
-);
-const urlBarOneOffBinding = document.getAnonymousElementByAttribute(
- urlbarPopup, "anonid", "one-off-search-buttons"
-);
-
-let originalEngine = Services.search.currentEngine;
-
-function resetEngine() {
- Services.search.currentEngine = originalEngine;
-}
-
-registerCleanupFunction(resetEngine);
-
-add_task(function* init() {
- yield promiseNewEngine(TEST_ENGINE_BASENAME, {
- setAsCurrent: false,
- });
-});
-
-add_task(function* test_searchBarChangeEngine() {
- let oneOffButton = yield openPopupAndGetEngineButton(true, searchPopup,
- searchOneOffBinding,
- SEARCHBAR_BASE_ID);
-
- const setDefaultEngineMenuItem = document.getAnonymousElementByAttribute(
- searchOneOffBinding, "anonid", "search-one-offs-context-set-default"
- );
-
- // Click the set default engine menu item.
- let promise = promiseCurrentEngineChanged();
- EventUtils.synthesizeMouseAtCenter(setDefaultEngineMenuItem, {});
-
- // This also checks the engine correctly changed.
- yield promise;
-
- Assert.equal(oneOffButton.id, SEARCHBAR_BASE_ID + originalEngine.name,
- "Should now have the original engine's id for the button");
- Assert.equal(oneOffButton.getAttribute("tooltiptext"), originalEngine.name,
- "Should now have the original engine's name for the tooltip");
- Assert.equal(oneOffButton.image, originalEngine.iconURI.spec,
- "Should now have the original engine's uri for the image");
-
- yield promiseClosePopup(searchPopup);
-});
-
-add_task(function* test_urlBarChangeEngine() {
- Services.prefs.setBoolPref(ONEOFF_URLBAR_PREF, true);
- registerCleanupFunction(function* () {
- Services.prefs.clearUserPref(ONEOFF_URLBAR_PREF);
- });
-
- // Ensure the engine is reset.
- resetEngine();
-
- let oneOffButton = yield openPopupAndGetEngineButton(false, urlbarPopup,
- urlBarOneOffBinding,
- URLBAR_BASE_ID);
-
- const setDefaultEngineMenuItem = document.getAnonymousElementByAttribute(
- urlBarOneOffBinding, "anonid", "search-one-offs-context-set-default"
- );
-
- // Click the set default engine menu item.
- let promise = promiseCurrentEngineChanged();
- EventUtils.synthesizeMouseAtCenter(setDefaultEngineMenuItem, {});
-
- // This also checks the engine correctly changed.
- yield promise;
-
- let currentEngine = Services.search.currentEngine;
-
- // For the urlbar, we should keep the new engine's icon.
- Assert.equal(oneOffButton.id, URLBAR_BASE_ID + currentEngine.name,
- "Should now have the original engine's id for the button");
- Assert.equal(oneOffButton.getAttribute("tooltiptext"), currentEngine.name,
- "Should now have the original engine's name for the tooltip");
- Assert.equal(oneOffButton.image, currentEngine.iconURI.spec,
- "Should now have the original engine's uri for the image");
-
- yield promiseClosePopup(urlbarPopup);
-});
-
-/**
- * Promises that an engine change has happened for the current engine, which
- * has resulted in the test engine now being the current engine.
- *
- * @return {Promise} Resolved once the test engine is set as the current engine.
- */
-function promiseCurrentEngineChanged() {
- return new Promise(resolve => {
- function observer(aSub, aTopic, aData) {
- if (aData == "engine-current") {
- Assert.ok(Services.search.currentEngine.name, TEST_ENGINE_NAME, "currentEngine set");
- Services.obs.removeObserver(observer, "browser-search-engine-modified");
- resolve();
- }
- }
-
- Services.obs.addObserver(observer, "browser-search-engine-modified", false);
- });
-}
-
-/**
- * Opens the specified urlbar/search popup and gets the test engine from the
- * one-off buttons.
- *
- * @param {Boolean} isSearch true if the search popup should be opened; false
- * for the urlbar popup.
- * @param {Object} popup The expected popup.
- * @param {Object} oneOffBinding The expected one-off-binding for the popup.
- * @param {String} baseId The expected string for the id of the current
- * engine button, without the engine name.
- * @return {Object} Returns an object that represents the one off button for the
- * test engine.
- */
-function* openPopupAndGetEngineButton(isSearch, popup, oneOffBinding, baseId) {
- // Open the popup.
- let promise = promiseEvent(popup, "popupshown");
- info("Opening panel");
-
- // We have to open the popups in differnt ways.
- if (isSearch) {
- // Use the search icon to avoid hitting the network.
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- } else {
- // There's no history at this stage, so we need to press a key.
- urlbar.focus();
- EventUtils.synthesizeKey("a", {});
- }
- yield promise;
-
- const contextMenu = document.getAnonymousElementByAttribute(
- oneOffBinding, "anonid", "search-one-offs-context-menu"
- );
- const oneOffButtons = document.getAnonymousElementByAttribute(
- oneOffBinding, "anonid", "search-panel-one-offs"
- );
-
- // Get the one-off button for the test engine.
- let oneOffButton;
- for (let node of oneOffButtons.childNodes) {
- if (node.engine && node.engine.name == TEST_ENGINE_NAME) {
- oneOffButton = node;
- break;
- }
- }
- Assert.notEqual(oneOffButton, undefined,
- "One-off for test engine should exist");
- Assert.equal(oneOffButton.getAttribute("tooltiptext"), TEST_ENGINE_NAME,
- "One-off should have the tooltip set to the engine name");
- Assert.equal(oneOffButton.id, baseId + TEST_ENGINE_NAME,
- "Should have the correct id");
-
- // Open the context menu on the one-off.
- promise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(oneOffButton, {
- type: "contextmenu",
- button: 2,
- });
- yield promise;
-
- return oneOffButton;
-}
-
-/**
- * Closes the popup and moves the mouse away from it.
- *
- * @param {Button} popup The popup to close.
- */
-function* promiseClosePopup(popup) {
- // close the panel using the escape key.
- let promise = promiseEvent(popup, "popuphidden");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- // Move the cursor out of the panel area to avoid messing with other tests.
- yield EventUtils.synthesizeNativeMouseMove(popup);
-}
diff --git a/browser/components/search/test/browser_oneOffHeader.js b/browser/components/search/test/browser_oneOffHeader.js
deleted file mode 100644
index 3a209bf56..000000000
--- a/browser/components/search/test/browser_oneOffHeader.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* 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/. */
-// Tests that keyboard navigation in the search panel works as designed.
-
-const isMac = ("nsILocalFileMac" in Ci);
-
-const searchbar = document.getElementById("searchbar");
-const textbox = searchbar._textbox;
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid",
- "searchbar-search-button");
-
-const oneOffsContainer =
- document.getAnonymousElementByAttribute(searchPopup, "anonid",
- "search-one-off-buttons");
-const searchSettings =
- document.getAnonymousElementByAttribute(oneOffsContainer, "anonid",
- "search-settings");
-var header =
- document.getAnonymousElementByAttribute(oneOffsContainer, "anonid",
- "search-panel-one-offs-header");
-function getHeaderText() {
- let headerChild = header.selectedPanel;
- while (headerChild.hasChildNodes()) {
- headerChild = headerChild.firstChild;
- }
- let headerStrings = [];
- for (let label = headerChild; label; label = label.nextSibling) {
- headerStrings.push(label.value);
- }
- return headerStrings.join("");
-}
-
-const msg = isMac ? 5 : 1;
-const utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
-const scale = utils.screenPixelsPerCSSPixel;
-function* synthesizeNativeMouseMove(aElement) {
- let rect = aElement.getBoundingClientRect();
- let win = aElement.ownerGlobal;
- let x = win.mozInnerScreenX + (rect.left + rect.right) / 2;
- let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2;
-
- // Wait for the mouseup event to occur before continuing.
- return new Promise((resolve, reject) => {
- function eventOccurred(e)
- {
- aElement.removeEventListener("mouseover", eventOccurred, true);
- resolve();
- }
-
- aElement.addEventListener("mouseover", eventOccurred, true);
-
- utils.sendNativeMouseEvent(x * scale, y * scale, msg, 0, null);
- });
-}
-
-
-add_task(function* init() {
- yield promiseNewEngine("testEngine.xml");
-});
-
-add_task(function* test_notext() {
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
-
- is(header.getAttribute("selectedIndex"), 0,
- "Header has the correct index selected with no search terms.");
-
- is(getHeaderText(), "Search with:",
- "Search header string is correct when no search terms have been entered");
-
- yield synthesizeNativeMouseMove(searchSettings);
- is(header.getAttribute("selectedIndex"), 0,
- "Header has the correct index when no search terms have been entered and the Change Search Settings button is selected.");
- is(getHeaderText(), "Search with:",
- "Header has the correct text when no search terms have been entered and the Change Search Settings button is selected.");
-
- let buttons = getOneOffs();
- yield synthesizeNativeMouseMove(buttons[0]);
- is(header.getAttribute("selectedIndex"), 2,
- "Header has the correct index selected when a search engine has been selected");
- is(getHeaderText(), "Search " + buttons[0].engine.name,
- "Is the header text correct when a search engine is selected and no terms have been entered.");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- info("Closing search panel");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-});
-
-add_task(function* test_text() {
- textbox.value = "foo";
- registerCleanupFunction(() => {
- textbox.value = "";
- });
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- });
- yield promise;
-
- is(header.getAttribute("selectedIndex"), 1,
- "Header has the correct index selected with a search term.");
- is(getHeaderText(), "Search for foo with:",
- "Search header string is correct when a search term has been entered");
-
- let buttons = getOneOffs();
- yield synthesizeNativeMouseMove(buttons[0]);
- is(header.getAttribute("selectedIndex"), 2,
- "Header has the correct index selected when a search engine has been selected");
- is(getHeaderText(), "Search " + buttons[0].engine.name,
- "Is the header text correct when search terms are entered after a search engine has been selected.");
-
- yield synthesizeNativeMouseMove(searchSettings);
- is(header.getAttribute("selectedIndex"), 1,
- "Header has the correct index selected when search terms have been entered and the Change Search Settings button is selected.");
- is(getHeaderText(), "Search for foo with:",
- "Header has the correct text when search terms have been entered and the Change Search Settings button is selected.");
-
- // Click the "Foo Search" header at the top of the popup and make sure it
- // loads the search results.
- let searchbarEngine =
- document.getAnonymousElementByAttribute(searchPopup, "anonid",
- "searchbar-engine");
-
- yield synthesizeNativeMouseMove(searchbarEngine);
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchbarEngine, {});
- });
-
- let url = Services.search.currentEngine.getSubmission(textbox.value).uri.spec;
- yield promiseTabLoadEvent(gBrowser.selectedTab, url);
-
- // Move the cursor out of the panel area to avoid messing with other tests.
- yield synthesizeNativeMouseMove(searchbar);
-});
diff --git a/browser/components/search/test/browser_private_search_perwindowpb.js b/browser/components/search/test/browser_private_search_perwindowpb.js
deleted file mode 100644
index c0410371b..000000000
--- a/browser/components/search/test/browser_private_search_perwindowpb.js
+++ /dev/null
@@ -1,76 +0,0 @@
-// This test performs a search in a public window, then a different
-// search in a private window, and then checks in the public window
-// whether there is an autocomplete entry for the private search.
-
-add_task(function* () {
- // Don't use about:home as the homepage for new windows
- Services.prefs.setIntPref("browser.startup.page", 0);
- registerCleanupFunction(() => Services.prefs.clearUserPref("browser.startup.page"));
-
- let windowsToClose = [];
-
- function performSearch(aWin, aIsPrivate) {
- let searchBar = aWin.BrowserSearch.searchBar;
- ok(searchBar, "got search bar");
-
- let loadPromise = BrowserTestUtils.browserLoaded(aWin.gBrowser.selectedBrowser);
-
- searchBar.value = aIsPrivate ? "private test" : "public test";
- searchBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {}, aWin);
-
- return loadPromise;
- }
-
- function* testOnWindow(aIsPrivate) {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private: aIsPrivate });
- yield SimpleTest.promiseFocus(win);
- windowsToClose.push(win);
- return win;
- }
-
- yield promiseNewEngine("426329.xml", { iconURL: "data:image/x-icon,%00" });
-
- let newWindow = yield* testOnWindow(false);
- yield performSearch(newWindow, false);
-
- newWindow = yield* testOnWindow(true);
- yield performSearch(newWindow, true);
-
- newWindow = yield* testOnWindow(false);
-
- let searchBar = newWindow.BrowserSearch.searchBar;
- searchBar.value = "p";
- searchBar.focus();
-
- let popup = searchBar.textbox.popup;
- let popupPromise = BrowserTestUtils.waitForEvent(popup, "popupshown");
- searchBar.textbox.showHistoryPopup();
- yield popupPromise;
-
- let entries = getMenuEntries(searchBar);
- for (let i = 0; i < entries.length; i++) {
- isnot(entries[i], "private test",
- "shouldn't see private autocomplete entries");
- }
-
- searchBar.textbox.toggleHistoryPopup();
- searchBar.value = "";
-
- windowsToClose.forEach(function(win) {
- win.close();
- });
-});
-
-function getMenuEntries(searchBar) {
- let entries = [];
- let autocompleteMenu = searchBar.textbox.popup;
- // Could perhaps pull values directly from the controller, but it seems
- // more reliable to test the values that are actually in the tree?
- let column = autocompleteMenu.tree.columns[0];
- let numRows = autocompleteMenu.tree.view.rowCount;
- for (let i = 0; i < numRows; i++) {
- entries.push(autocompleteMenu.tree.view.getValueAt(i, column));
- }
- return entries;
-}
diff --git a/browser/components/search/test/browser_searchbar_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_keyboard_navigation.js
deleted file mode 100644
index d395dfdc2..000000000
--- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js
+++ /dev/null
@@ -1,425 +0,0 @@
-// Tests that keyboard navigation in the search panel works as designed.
-
-const searchbar = document.getElementById("searchbar");
-const textbox = searchbar._textbox;
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const oneOffsContainer =
- document.getAnonymousElementByAttribute(searchPopup, "anonid",
- "search-one-off-buttons");
-
-const kValues = ["foo1", "foo2", "foo3"];
-const kUserValue = "foo";
-
-function getOpenSearchItems() {
- let os = [];
-
- let addEngineList =
- document.getAnonymousElementByAttribute(oneOffsContainer, "anonid",
- "add-engines");
- for (let item = addEngineList.firstChild; item; item = item.nextSibling)
- os.push(item);
-
- return os;
-}
-
-add_task(function* init() {
- yield promiseNewEngine("testEngine.xml");
-
- // First cleanup the form history in case other tests left things there.
- yield new Promise((resolve, reject) => {
- info("cleanup the search history");
- searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"},
- {handleCompletion: resolve,
- handleError: reject});
- });
-
- yield new Promise((resolve, reject) => {
- info("adding search history values: " + kValues);
- let ops = kValues.map(value => { return {op: "add",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops, {
- handleCompletion: function() {
- registerCleanupFunction(() => {
- info("removing search history values: " + kValues);
- let ops =
- kValues.map(value => { return {op: "remove",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops);
- });
- resolve();
- },
- handleError: reject
- });
- });
-
- textbox.value = kUserValue;
- registerCleanupFunction(() => { textbox.value = ""; });
-});
-
-
-add_task(function* test_arrows() {
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- searchbar.focus();
- yield promise;
- is(textbox.mController.searchString, kUserValue, "The search string should be 'foo'");
-
- // Check the initial state of the panel before sending keyboard events.
- is(searchPopup.view.rowCount, kValues.length, "There should be 3 suggestions");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
-
- // The tests will be less meaningful if the first, second, last, and
- // before-last one-off buttons aren't different. We should always have more
- // than 4 default engines, but it's safer to check this assumption.
- let oneOffs = getOneOffs();
- ok(oneOffs.length >= 4, "we have at least 4 one-off buttons displayed")
-
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // The down arrow should first go through the suggestions.
- for (let i = 0; i < kValues.length; ++i) {
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(searchPopup.selectedIndex, i,
- "the suggestion at index " + i + " should be selected");
- is(textbox.value, kValues[i],
- "the textfield value should be " + kValues[i]);
- }
-
- // Pressing down again should remove suggestion selection and change the text
- // field value back to what the user typed, and select the first one-off.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue,
- "the textfield value should be back to initial value");
-
- // now cycle through the one-off items, the first one is already selected.
- for (let i = 0; i < oneOffs.length; ++i) {
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
- }
-
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
-
- // We should now be back to the initial situation.
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- info("now test the up arrow key");
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // cycle through the one-off items, the first one is already selected.
- for (let i = oneOffs.length; i; --i) {
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, oneOffs[i - 1],
- "the one-off button #" + i + " should be selected");
- }
-
- // Another press on up should clear the one-off selection and select the
- // last suggestion.
- EventUtils.synthesizeKey("VK_UP", {});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- for (let i = kValues.length - 1; i >= 0; --i) {
- is(searchPopup.selectedIndex, i,
- "the suggestion at index " + i + " should be selected");
- is(textbox.value, kValues[i],
- "the textfield value should be " + kValues[i]);
- EventUtils.synthesizeKey("VK_UP", {});
- }
-
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue,
- "the textfield value should be back to initial value");
-});
-
-add_task(function* test_typing_clears_button_selection() {
- is(Services.focus.focusedElement, textbox.inputField,
- "the search bar should be focused"); // from the previous test.
- ok(!textbox.selectedButton, "no button should be selected");
-
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // Type a character.
- EventUtils.synthesizeKey("a", {});
- ok(!textbox.selectedButton, "the settings item should be de-selected");
-
- // Remove the character.
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
-});
-
-add_task(function* test_tab() {
- is(Services.focus.focusedElement, textbox.inputField,
- "the search bar should be focused"); // from the previous test.
-
- let oneOffs = getOneOffs();
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // Pressing tab should select the first one-off without selecting suggestions.
- // now cycle through the one-off items, the first one is already selected.
- for (let i = 0; i < oneOffs.length; ++i) {
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- }
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue, "the textfield value should be unmodified");
-
- // One more <tab> selects the settings button.
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // Pressing tab again should close the panel...
- let promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_TAB", {});
- yield promise;
-
- // ... and move the focus out of the searchbox.
- isnot(Services.focus.focusedElement, textbox.inputField,
- "the search bar no longer be focused");
-});
-
-add_task(function* test_shift_tab() {
- // First reopen the panel.
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- searchbar.focus();
- yield promise;
-
- let oneOffs = getOneOffs();
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // Press up once to select the last button.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // Press up again to select the last one-off button.
- EventUtils.synthesizeKey("VK_UP", {});
-
- // Pressing shift+tab should cycle through the one-off items.
- for (let i = oneOffs.length - 1; i >= 0; --i) {
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- if (i)
- EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
- }
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue, "the textfield value should be unmodified");
-
- // Pressing shift+tab again should close the panel...
- promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
- yield promise;
-
- // ... and move the focus out of the searchbox.
- isnot(Services.focus.focusedElement, textbox.inputField,
- "the search bar no longer be focused");
-});
-
-add_task(function* test_alt_down() {
- // First refocus the panel.
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- searchbar.focus();
- yield promise;
-
- // close the panel using the escape key.
- promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- // check that alt+down opens the panel...
- promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- yield promise;
-
- // ... and does nothing else.
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue, "the textfield value should be unmodified");
-
- // Pressing alt+down should select the first one-off without selecting suggestions
- // and cycle through the one-off items.
- let oneOffs = getOneOffs();
- for (let i = 0; i < oneOffs.length; ++i) {
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- }
-
- // One more alt+down keypress and nothing should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // another one and the first one-off should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should be selected");
-});
-
-add_task(function* test_alt_up() {
- // close the panel using the escape key.
- let promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- // check that alt+up opens the panel...
- promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- yield promise;
-
- // ... and does nothing else.
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue, "the textfield value should be unmodified");
-
- // Pressing alt+up should select the last one-off without selecting suggestions
- // and cycle up through the one-off items.
- let oneOffs = getOneOffs();
- for (let i = oneOffs.length - 1; i >= 0; --i) {
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- }
-
- // One more alt+down keypress and nothing should be selected.
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // another one and the last one-off should be selected.
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- is(textbox.selectedButton, oneOffs[oneOffs.length - 1],
- "the last one-off button should be selected");
-
- // Cleanup for the next test.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
- ok(!textbox.selectedButton, "no one-off should be selected anymore");
-});
-
-add_task(function* test_tab_and_arrows() {
- // Check the initial state is as expected.
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue, "the textfield value should be unmodified");
-
- // After pressing down, the first sugggestion should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(searchPopup.selectedIndex, 0, "first suggestion should be selected");
- is(textbox.value, kValues[0], "the textfield value should have changed");
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // After pressing tab, the first one-off should be selected,
- // and the first suggestion still selected.
- let oneOffs = getOneOffs();
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should be selected");
- is(searchPopup.selectedIndex, 0, "first suggestion should still be selected");
-
- // After pressing down, the second suggestion should be selected,
- // and the first one-off still selected.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should still be selected");
- is(searchPopup.selectedIndex, 1, "second suggestion should be selected");
-
- // After pressing up, the first suggestion should be selected again,
- // and the first one-off still selected.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should still be selected");
- is(searchPopup.selectedIndex, 0, "second suggestion should be selected again");
-
- // After pressing up again, we should have no suggestion selected anymore,
- // the textfield value back to the user-typed value, and still the first one-off
- // selected.
- EventUtils.synthesizeKey("VK_UP", {});
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, kUserValue,
- "the textfield value should be back to user typed value");
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should still be selected");
-
- // Now pressing down should select the second one-off.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton, oneOffs[1],
- "the second one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "there should still be no selected suggestion");
-
- // Finally close the panel.
- let promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-});
-
-add_task(function* test_open_search() {
- let rootDir = getRootDirectory(gTestPath);
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- searchbar.focus();
- yield promise;
-
- let engines = getOpenSearchItems();
- is(engines.length, 2, "the opensearch.html page exposes 2 engines")
-
- // Check that there's initially no selection.
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- ok(!textbox.selectedButton, "no button should be selected");
-
- // Pressing up once selects the setting button...
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // ...and then pressing up selects open search engines.
- for (let i = engines.length; i; --i) {
- EventUtils.synthesizeKey("VK_UP", {});
- let selectedButton = textbox.selectedButton;
- is(selectedButton, engines[i - 1],
- "the engine #" + i + " should be selected");
- ok(selectedButton.classList.contains("addengine-item"),
- "the button is themed as an engine item");
- }
-
- // Pressing up again should select the last one-off button.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, getOneOffs().pop(),
- "the last one-off button should be selected");
-
- info("now check that the down key navigates open search items as expected");
- for (let i = 0; i < engines.length; ++i) {
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton, engines[i],
- "the engine #" + (i + 1) + " should be selected");
- }
-
- // Pressing down on the last engine item selects the settings button.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/search/test/browser_searchbar_openpopup.js b/browser/components/search/test/browser_searchbar_openpopup.js
deleted file mode 100644
index befc8f142..000000000
--- a/browser/components/search/test/browser_searchbar_openpopup.js
+++ /dev/null
@@ -1,521 +0,0 @@
-// Tests that the suggestion popup appears at the right times in response to
-// focus and user events (mouse, keyboard, drop).
-
-// Instead of loading EventUtils.js into the test scope in browser-test.js for all tests,
-// we only need EventUtils.js for a few files which is why we are using loadSubScript.
-var EventUtils = {};
-this._scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
-this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils);
-
-const searchbar = document.getElementById("searchbar");
-const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid", "searchbar-search-button");
-const goButton = document.getAnonymousElementByAttribute(searchbar, "anonid", "search-go-button");
-const textbox = searchbar._textbox;
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const kValues = ["long text", "long text 2", "long text 3"];
-
-const isWindows = Services.appinfo.OS == "WINNT";
-const mouseDown = isWindows ? 2 : 1;
-const mouseUp = isWindows ? 4 : 2;
-const utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils);
-const scale = utils.screenPixelsPerCSSPixel;
-
-function* synthesizeNativeMouseClick(aElement) {
- let rect = aElement.getBoundingClientRect();
- let win = aElement.ownerGlobal;
- let x = win.mozInnerScreenX + (rect.left + rect.right) / 2;
- let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2;
-
- // Wait for the mouseup event to occur before continuing.
- return new Promise((resolve, reject) => {
- function eventOccurred(e)
- {
- aElement.removeEventListener("mouseup", eventOccurred, true);
- resolve();
- }
-
- aElement.addEventListener("mouseup", eventOccurred, true);
-
- utils.sendNativeMouseEvent(x * scale, y * scale, mouseDown, 0, null);
- utils.sendNativeMouseEvent(x * scale, y * scale, mouseUp, 0, null);
- });
-}
-
-add_task(function* init() {
- yield promiseNewEngine("testEngine.xml");
-
- // First cleanup the form history in case other tests left things there.
- yield new Promise((resolve, reject) => {
- info("cleanup the search history");
- searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"},
- {handleCompletion: resolve,
- handleError: reject});
- });
-
- yield new Promise((resolve, reject) => {
- info("adding search history values: " + kValues);
- let ops = kValues.map(value => { return {op: "add",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops, {
- handleCompletion: function() {
- registerCleanupFunction(() => {
- info("removing search history values: " + kValues);
- let ops =
- kValues.map(value => { return {op: "remove",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops);
- });
- resolve();
- },
- handleError: reject
- });
- });
-});
-
-// Adds a task that shouldn't show the search suggestions popup.
-function add_no_popup_task(task) {
- add_task(function*() {
- let sawPopup = false;
- function listener() {
- sawPopup = true;
- }
-
- info("Entering test " + task.name);
- searchPopup.addEventListener("popupshowing", listener, false);
- yield Task.spawn(task);
- searchPopup.removeEventListener("popupshowing", listener, false);
- ok(!sawPopup, "Shouldn't have seen the suggestions popup");
- info("Leaving test " + task.name);
- });
-}
-
-// Simulates the full set of events for a context click
-function context_click(target) {
- for (let event of ["mousedown", "contextmenu", "mouseup"])
- EventUtils.synthesizeMouseAtCenter(target, { type: event, button: 2 });
-}
-
-// Right clicking the icon should not open the popup.
-add_no_popup_task(function* open_icon_context() {
- gURLBar.focus();
- let toolbarPopup = document.getElementById("toolbar-context-menu");
-
- let promise = promiseEvent(toolbarPopup, "popupshown");
- context_click(searchIcon);
- yield promise;
-
- promise = promiseEvent(toolbarPopup, "popuphidden");
- toolbarPopup.hidePopup();
- yield promise;
-});
-
-// With no text in the search box left clicking the icon should open the popup.
-// Clicking the icon again should hide the popup and not show it again.
-add_task(function* open_empty() {
- gURLBar.focus();
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Clicking icon");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should only show the settings");
- is(textbox.mController.searchString, "", "Should be an empty search string");
-
- // By giving the textbox some text any next attempt to open the search popup
- // from the click handler will try to search for this text.
- textbox.value = "foo";
-
- promise = promiseEvent(searchPopup, "popuphidden");
-
- info("Hiding popup");
- yield synthesizeNativeMouseClick(searchIcon);
- yield promise;
-
- is(textbox.mController.searchString, "", "Should not have started to search for the new text");
-
- // Cancel the search if it started.
- if (textbox.mController.searchString != "") {
- textbox.mController.stopSearch();
- }
-
- textbox.value = "";
-});
-
-// With no text in the search box left clicking it should not open the popup.
-add_no_popup_task(function* click_doesnt_open_popup() {
- gURLBar.focus();
-
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 0, "Should have selected all of the text");
-});
-
-// Left clicking in a non-empty search box when unfocused should focus it and open the popup.
-add_task(function* click_opens_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-
- textbox.value = "";
-});
-
-// Right clicking in a non-empty search box when unfocused should open the edit context menu.
-add_no_popup_task(function* right_click_doesnt_open_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let contextPopup = document.getAnonymousElementByAttribute(textbox.inputField.parentNode, "anonid", "input-box-contextmenu");
- let promise = promiseEvent(contextPopup, "popupshown");
- context_click(textbox);
- yield promise;
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(contextPopup, "popuphidden");
- contextPopup.hidePopup();
- yield promise;
-
- textbox.value = "";
-});
-
-// Moving focus away from the search box should close the popup
-add_task(function* focus_change_closes_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- let promise2 = promiseEvent(searchbar, "blur");
- EventUtils.synthesizeKey("VK_TAB", { shiftKey: true });
- yield promise;
- yield promise2;
-
- textbox.value = "";
-});
-
-// Moving focus away from the search box should close the small popup
-add_task(function* focus_change_closes_small_popup() {
- gURLBar.focus();
-
- let promise = promiseEvent(searchPopup, "popupshown");
- // For some reason sending the mouse event immediately doesn't open the popup.
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- });
- yield promise;
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- let promise2 = promiseEvent(searchbar, "blur");
- EventUtils.synthesizeKey("VK_TAB", { shiftKey: true });
- yield promise;
- yield promise2;
-});
-
-// Pressing escape should close the popup.
-add_task(function* escape_closes_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- textbox.value = "";
-});
-
-// Pressing contextmenu should close the popup.
-add_task(function* contextmenu_closes_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
-
- // synthesizeKey does not work with VK_CONTEXT_MENU (bug 1127368)
- EventUtils.synthesizeMouseAtCenter(textbox, { type: "contextmenu", button: null });
-
- yield promise;
-
- let contextPopup =
- document.getAnonymousElementByAttribute(textbox.inputField.parentNode,
- "anonid", "input-box-contextmenu");
- promise = promiseEvent(contextPopup, "popuphidden");
- contextPopup.hidePopup();
- yield promise;
-
- textbox.value = "";
-});
-
-// Tabbing to the search box should open the popup if it contains text.
-add_task(function* tab_opens_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeKey("VK_TAB", {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-
- textbox.value = "";
-});
-
-// Tabbing to the search box should not open the popup if it doesn't contain text.
-add_no_popup_task(function* tab_doesnt_open_popup() {
- gURLBar.focus();
- textbox.value = "foo";
-
- EventUtils.synthesizeKey("VK_TAB", {});
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- textbox.value = "";
-});
-
-// Switching back to the window when the search box has focus from mouse should not open the popup.
-add_task(function* refocus_window_doesnt_open_popup_mouse() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(searchbar, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- let newWin = OpenBrowserWindow();
- yield new Promise(resolve => waitForFocus(resolve, newWin));
- yield promise;
-
- function listener() {
- ok(false, "Should not have shown the popup.");
- }
- searchPopup.addEventListener("popupshowing", listener, false);
-
- promise = promiseEvent(searchbar, "focus");
- newWin.close();
- yield promise;
-
- // Wait a few ticks to allow any focus handlers to show the popup if they are going to.
- yield new Promise(resolve => executeSoon(resolve));
- yield new Promise(resolve => executeSoon(resolve));
- yield new Promise(resolve => executeSoon(resolve));
-
- searchPopup.removeEventListener("popupshowing", listener, false);
- textbox.value = "";
-});
-
-// Switching back to the window when the search box has focus from keyboard should not open the popup.
-add_task(function* refocus_window_doesnt_open_popup_keyboard() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeKey("VK_TAB", {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- let newWin = OpenBrowserWindow();
- yield new Promise(resolve => waitForFocus(resolve, newWin));
- yield promise;
-
- function listener() {
- ok(false, "Should not have shown the popup.");
- }
- searchPopup.addEventListener("popupshowing", listener, false);
-
- promise = promiseEvent(searchbar, "focus");
- newWin.close();
- yield promise;
-
- // Wait a few ticks to allow any focus handlers to show the popup if they are going to.
- yield new Promise(resolve => executeSoon(resolve));
- yield new Promise(resolve => executeSoon(resolve));
- yield new Promise(resolve => executeSoon(resolve));
-
- searchPopup.removeEventListener("popupshowing", listener, false);
- textbox.value = "";
-});
-
-// Clicking the search go button shouldn't open the popup
-add_no_popup_task(function* search_go_doesnt_open_popup() {
- gBrowser.selectedTab = gBrowser.addTab();
-
- gURLBar.focus();
- textbox.value = "foo";
- searchbar.updateGoButtonVisibility();
-
- let promise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- EventUtils.synthesizeMouseAtCenter(goButton, {});
- yield promise;
-
- textbox.value = "";
- gBrowser.removeCurrentTab();
-});
-
-// Clicks outside the search popup should close the popup but not consume the click.
-add_task(function* dont_consume_clicks() {
- gURLBar.focus();
- textbox.value = "foo";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
-
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- is(textbox.selectionStart, 0, "Should have selected all of the text");
- is(textbox.selectionEnd, 3, "Should have selected all of the text");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- yield synthesizeNativeMouseClick(gURLBar);
- yield promise;
-
- is(Services.focus.focusedElement, gURLBar.inputField, "Should have focused the URL bar");
-
- textbox.value = "";
-});
-
-// Dropping text to the searchbar should open the popup
-add_task(function* drop_opens_popup() {
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeDrop(searchIcon, textbox.inputField, [[ {type: "text/plain", data: "foo" } ]], "move", window);
- yield promise;
-
- isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup");
- is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar");
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-
- textbox.value = "";
-});
-
-// Moving the caret using the cursor keys should not close the popup.
-add_task(function* dont_rollup_oncaretmove() {
- gURLBar.focus();
- textbox.value = "long text";
-
- let promise = promiseEvent(searchPopup, "popupshown");
- EventUtils.synthesizeMouseAtCenter(textbox, {});
- yield promise;
-
- // Deselect the text
- EventUtils.synthesizeKey("VK_RIGHT", {});
- is(textbox.selectionStart, 9, "Should have moved the caret (selectionStart after deselect right)");
- is(textbox.selectionEnd, 9, "Should have moved the caret (selectionEnd after deselect right)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- EventUtils.synthesizeKey("VK_LEFT", {});
- is(textbox.selectionStart, 8, "Should have moved the caret (selectionStart after left)");
- is(textbox.selectionEnd, 8, "Should have moved the caret (selectionEnd after left)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- EventUtils.synthesizeKey("VK_RIGHT", {});
- is(textbox.selectionStart, 9, "Should have moved the caret (selectionStart after right)");
- is(textbox.selectionEnd, 9, "Should have moved the caret (selectionEnd after right)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- // Ensure caret movement works while a suggestion is selected.
- is(textbox.popup.selectedIndex, -1, "No selected item in list");
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.popup.selectedIndex, 0, "Selected item in list");
- is(textbox.selectionStart, 9, "Should have moved the caret to the end (selectionStart after selection)");
- is(textbox.selectionEnd, 9, "Should have moved the caret to the end (selectionEnd after selection)");
-
- EventUtils.synthesizeKey("VK_LEFT", {});
- is(textbox.selectionStart, 8, "Should have moved the caret again (selectionStart after left)");
- is(textbox.selectionEnd, 8, "Should have moved the caret again (selectionEnd after left)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- EventUtils.synthesizeKey("VK_LEFT", {});
- is(textbox.selectionStart, 7, "Should have moved the caret (selectionStart after left)");
- is(textbox.selectionEnd, 7, "Should have moved the caret (selectionEnd after left)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- EventUtils.synthesizeKey("VK_RIGHT", {});
- is(textbox.selectionStart, 8, "Should have moved the caret (selectionStart after right)");
- is(textbox.selectionEnd, 8, "Should have moved the caret (selectionEnd after right)");
- is(searchPopup.state, "open", "Popup should still be open");
-
- if (navigator.platform.indexOf("Mac") == -1) {
- EventUtils.synthesizeKey("VK_HOME", {});
- is(textbox.selectionStart, 0, "Should have moved the caret (selectionStart after home)");
- is(textbox.selectionEnd, 0, "Should have moved the caret (selectionEnd after home)");
- is(searchPopup.state, "open", "Popup should still be open");
- }
-
- // Close the popup again
- promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_ESCAPE", {});
- yield promise;
-
- textbox.value = "";
-});
diff --git a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js
deleted file mode 100644
index 37ca32cf2..000000000
--- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js
+++ /dev/null
@@ -1,354 +0,0 @@
-// Tests that keyboard navigation in the search panel works as designed.
-
-const searchbar = document.getElementById("searchbar");
-const textbox = searchbar._textbox;
-const searchPopup = document.getElementById("PopupSearchAutoComplete");
-const oneOffsContainer =
- document.getAnonymousElementByAttribute(searchPopup, "anonid",
- "search-one-off-buttons");
-const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid",
- "searchbar-search-button");
-
-const kValues = ["foo1", "foo2", "foo3"];
-
-function getOpenSearchItems() {
- let os = [];
-
- let addEngineList =
- document.getAnonymousElementByAttribute(oneOffsContainer, "anonid",
- "add-engines");
- for (let item = addEngineList.firstChild; item; item = item.nextSibling)
- os.push(item);
-
- return os;
-}
-
-add_task(function* init() {
- yield promiseNewEngine("testEngine.xml");
-
- // First cleanup the form history in case other tests left things there.
- yield new Promise((resolve, reject) => {
- info("cleanup the search history");
- searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"},
- {handleCompletion: resolve,
- handleError: reject});
- });
-
- yield new Promise((resolve, reject) => {
- info("adding search history values: " + kValues);
- let ops = kValues.map(value => { return {op: "add",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops, {
- handleCompletion: function() {
- registerCleanupFunction(() => {
- info("removing search history values: " + kValues);
- let ops =
- kValues.map(value => { return {op: "remove",
- fieldname: "searchbar-history",
- value: value}
- });
- searchbar.FormHistory.update(ops);
- });
- resolve();
- },
- handleError: reject
- });
- });
-});
-
-
-add_task(function* test_arrows() {
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
-info("textbox.mController.searchString = " + textbox.mController.searchString);
- is(textbox.mController.searchString, "", "The search string should be empty");
-
- // Check the initial state of the panel before sending keyboard events.
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
- // Having suggestions populated (but hidden) is important, because if there
- // are none we can't ensure the keyboard events don't reach them.
- is(searchPopup.view.rowCount, kValues.length, "There should be 3 suggestions");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
-
- // The tests will be less meaningful if the first, second, last, and
- // before-last one-off buttons aren't different. We should always have more
- // than 4 default engines, but it's safer to check this assumption.
- let oneOffs = getOneOffs();
- ok(oneOffs.length >= 4, "we have at least 4 one-off buttons displayed")
-
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // Pressing should select the first one-off.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // now cycle through the one-off items, the first one is already selected.
- for (let i = 0; i < oneOffs.length; ++i) {
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
- }
-
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
-
- // We should now be back to the initial situation.
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- info("now test the up arrow key");
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // cycle through the one-off items, the first one is already selected.
- for (let i = oneOffs.length; i; --i) {
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, oneOffs[i - 1],
- "the one-off button #" + i + " should be selected");
- }
-
- // Another press on up should clear the one-off selection.
- EventUtils.synthesizeKey("VK_UP", {});
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-});
-
-add_task(function* test_tab() {
- is(Services.focus.focusedElement, textbox.inputField,
- "the search bar should be focused"); // from the previous test.
-
- let oneOffs = getOneOffs();
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // Pressing tab should select the first one-off without selecting suggestions.
- // now cycle through the one-off items, the first one is already selected.
- for (let i = 0; i < oneOffs.length; ++i) {
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- }
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // One more <tab> selects the settings button.
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // Pressing tab again should close the panel...
- let promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_TAB", {});
- yield promise;
-
- // ... and move the focus out of the searchbox.
- isnot(Services.focus.focusedElement, textbox.inputField,
- "the search bar no longer be focused");
-});
-
-add_task(function* test_shift_tab() {
- // First reopen the panel.
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- });
- yield promise;
-
- let oneOffs = getOneOffs();
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
-
- // Press up once to select the last button.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // Press up again to select the last one-off button.
- EventUtils.synthesizeKey("VK_UP", {});
-
- // Pressing shift+tab should cycle through the one-off items.
- for (let i = oneOffs.length - 1; i >= 0; --i) {
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- if (i)
- EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
- }
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // Pressing shift+tab again should close the panel...
- promise = promiseEvent(searchPopup, "popuphidden");
- EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
- yield promise;
-
- // ... and move the focus out of the searchbox.
- isnot(Services.focus.focusedElement, textbox.inputField,
- "the search bar no longer be focused");
-});
-
-add_task(function* test_alt_down() {
- // First reopen the panel.
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- SimpleTest.executeSoon(() => {
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- });
- yield promise;
-
- // and check it's in a correct initial state.
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // Pressing alt+down should select the first one-off without selecting suggestions
- // and cycle through the one-off items.
- let oneOffs = getOneOffs();
- for (let i = 0; i < oneOffs.length; ++i) {
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- }
-
- // One more alt+down keypress and nothing should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // another one and the first one-off should be selected.
- EventUtils.synthesizeKey("VK_DOWN", {altKey: true});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should be selected");
-
- // Clear the selection with an alt+up keypress
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-});
-
-add_task(function* test_alt_up() {
- // Check the initial state of the panel
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // Pressing alt+up should select the last one-off without selecting suggestions
- // and cycle up through the one-off items.
- let oneOffs = getOneOffs();
- for (let i = oneOffs.length - 1; i >= 0; --i) {
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- is(textbox.selectedButton, oneOffs[i],
- "the one-off button #" + (i + 1) + " should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- }
-
- // One more alt+down keypress and nothing should be selected.
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- ok(!textbox.selectedButton, "no one-off button should be selected");
-
- // another one and the last one-off should be selected.
- EventUtils.synthesizeKey("VK_UP", {altKey: true});
- is(textbox.selectedButton, oneOffs[oneOffs.length - 1],
- "the last one-off button should be selected");
-
- // Cleanup for the next test.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
- EventUtils.synthesizeKey("VK_DOWN", {});
- ok(!textbox.selectedButton, "no one-off should be selected anymore");
-});
-
-add_task(function* test_tab_and_arrows() {
- // Check the initial state is as expected.
- ok(!textbox.selectedButton, "no one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- is(textbox.value, "", "the textfield value should be unmodified");
-
- // After pressing down, the first one-off should be selected.
- let oneOffs = getOneOffs();
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
-
- // After pressing tab, the second one-off should be selected.
- EventUtils.synthesizeKey("VK_TAB", {});
- is(textbox.selectedButton, oneOffs[1],
- "the second one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
-
- // After pressing up, the first one-off should be selected again.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, oneOffs[0],
- "the first one-off button should be selected");
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
-
- // Finally close the panel.
- let promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-});
-
-add_task(function* test_open_search() {
- let rootDir = getRootDirectory(gTestPath);
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html");
-
- let promise = promiseEvent(searchPopup, "popupshown");
- info("Opening search panel");
- EventUtils.synthesizeMouseAtCenter(searchIcon, {});
- yield promise;
- is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup");
-
- let engines = getOpenSearchItems();
- is(engines.length, 2, "the opensearch.html page exposes 2 engines")
-
- // Check that there's initially no selection.
- is(searchPopup.selectedIndex, -1, "no suggestion should be selected");
- ok(!textbox.selectedButton, "no button should be selected");
-
- // Pressing up once selects the setting button...
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- // ...and then pressing up selects open search engines.
- for (let i = engines.length; i; --i) {
- EventUtils.synthesizeKey("VK_UP", {});
- let selectedButton = textbox.selectedButton;
- is(selectedButton, engines[i - 1],
- "the engine #" + i + " should be selected");
- ok(selectedButton.classList.contains("addengine-item"),
- "the button is themed as an engine item");
- }
-
- // Pressing up again should select the last one-off button.
- EventUtils.synthesizeKey("VK_UP", {});
- is(textbox.selectedButton, getOneOffs().pop(),
- "the last one-off button should be selected");
-
- info("now check that the down key navigates open search items as expected");
- for (let i = 0; i < engines.length; ++i) {
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton, engines[i],
- "the engine #" + (i + 1) + " should be selected");
- }
-
- // Pressing down on the last engine item selects the settings button.
- EventUtils.synthesizeKey("VK_DOWN", {});
- is(textbox.selectedButton.getAttribute("anonid"), "search-settings",
- "the settings item should be selected");
-
- promise = promiseEvent(searchPopup, "popuphidden");
- searchPopup.hidePopup();
- yield promise;
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/search/test/browser_webapi.js b/browser/components/search/test/browser_webapi.js
deleted file mode 100644
index d8161ffbe..000000000
--- a/browser/components/search/test/browser_webapi.js
+++ /dev/null
@@ -1,92 +0,0 @@
-var ROOT = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-const searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
-const brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
-const brandName = brandBundle.GetStringFromName("brandShortName");
-
-function getString(key, ...params) {
- return searchBundle.formatStringFromName(key, params, params.length);
-}
-
-function AddSearchProvider(...args) {
- return gBrowser.addTab(ROOT + "webapi.html?" + encodeURIComponent(JSON.stringify(args)));
-}
-
-function promiseDialogOpened() {
- return new Promise((resolve, reject) => {
- Services.wm.addListener({
- onOpenWindow: function(xulWin) {
- Services.wm.removeListener(this);
-
- let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- waitForFocus(() => {
- if (win.location == "chrome://global/content/commonDialog.xul")
- resolve(win)
- else
- reject();
- }, win);
- }
- });
- });
-}
-
-add_task(function* test_working() {
- gBrowser.selectedTab = AddSearchProvider(ROOT + "testEngine.xml");
-
- let dialog = yield promiseDialogOpened();
- is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
- is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"),
- "Should have seen the right install message");
- dialog.document.documentElement.cancelDialog();
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* test_HTTP() {
- gBrowser.selectedTab = AddSearchProvider(ROOT.replace("http:", "HTTP:") + "testEngine.xml");
-
- let dialog = yield promiseDialogOpened();
- is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
- is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"),
- "Should have seen the right install message");
- dialog.document.documentElement.cancelDialog();
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* test_relative() {
- gBrowser.selectedTab = AddSearchProvider("testEngine.xml");
-
- let dialog = yield promiseDialogOpened();
- is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog.");
- is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"),
- "Should have seen the right install message");
- dialog.document.documentElement.cancelDialog();
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* test_invalid() {
- gBrowser.selectedTab = AddSearchProvider("z://foobar");
-
- let dialog = yield promiseDialogOpened();
- is(dialog.args.promptType, "alert", "Should see the alert dialog.");
- is(dialog.args.text, getString("error_invalid_engine_msg", brandName),
- "Should have seen the right error message")
- dialog.document.documentElement.acceptDialog();
-
- gBrowser.removeCurrentTab();
-});
-
-add_task(function* test_missing() {
- let url = ROOT + "foobar.xml";
- gBrowser.selectedTab = AddSearchProvider(url);
-
- let dialog = yield promiseDialogOpened();
- is(dialog.args.promptType, "alert", "Should see the alert dialog.");
- is(dialog.args.text, getString("error_loading_engine_msg2", brandName, url),
- "Should have seen the right error message")
- dialog.document.documentElement.acceptDialog();
-
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/search/test/browser_yahoo.js b/browser/components/search/test/browser_yahoo.js
deleted file mode 100644
index f45b47d0c..000000000
--- a/browser/components/search/test/browser_yahoo.js
+++ /dev/null
@@ -1,132 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Yahoo search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-function test() {
- let engine = Services.search.getEngineByName("Yahoo");
- ok(engine, "Yahoo");
-
- let base = "https://search.yahoo.com/yhs/search?p=foo&ei=UTF-8&hspart=mozilla";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base + "&hsimp=yhs-001", "Check search URL for 'foo'");
- url = engine.getSubmission("foo", null, "searchbar").uri.spec;
- is(url, base + "&hsimp=yhs-001", "Check search bar search URL for 'foo'");
- url = engine.getSubmission("foo", null, "keyword").uri.spec;
- is(url, base + "&hsimp=yhs-002", "Check keyword search URL for 'foo'");
- url = engine.getSubmission("foo", null, "homepage").uri.spec;
- is(url, base + "&hsimp=yhs-003", "Check homepage search URL for 'foo'");
- url = engine.getSubmission("foo", null, "newtab").uri.spec;
- is(url, base + "&hsimp=yhs-004", "Check newtab search URL for 'foo'");
- url = engine.getSubmission("foo", null, "contextmenu").uri.spec;
- is(url, base + "&hsimp=yhs-005", "Check context menu search URL for 'foo'");
- url = engine.getSubmission("foo", null, "system").uri.spec;
- is(url, base + "&hsimp=yhs-007", "Check system search URL for 'foo'");
- url = engine.getSubmission("foo", null, "invalid").uri.spec;
- is(url, base + "&hsimp=yhs-001", "Check invalid URL for 'foo'");
-
- // Check search suggestion URL.
- url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec;
- is(url, "https://search.yahoo.com/sugg/ff?output=fxjson&appid=ffd&command=foo", "Check search suggestion URL for 'foo'");
-
- // Check all other engine properties.
- const EXPECTED_ENGINE = {
- name: "Yahoo",
- alias: null,
- description: "Yahoo Search",
- searchForm: "https://search.yahoo.com/yhs/search?p=&ei=UTF-8&hspart=mozilla&hsimp=yhs-001",
- hidden: false,
- wrappedJSObject: {
- queryCharset: "UTF-8",
- "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAEACAA8DQAAJgAAACAgAAABAAgAowsAAGINAACJUE5HDQoaCgAAAA1JSERSAAAAEAAAABAIBgAAAB/z/2EAAAAJcEhZcwAACxMAAAsTAQCanBgAAApPaUNDUFBob3Rvc2hvcCBJQ0MgcHJvZmlsZQAAeNqdU2dUU+kWPffe9EJLiICUS29SFQggUkKLgBSRJiohCRBKiCGh2RVRwRFFRQQbyKCIA46OgIwVUSwMigrYB+Qhoo6Do4iKyvvhe6Nr1rz35s3+tdc+56zznbPPB8AIDJZIM1E1gAypQh4R4IPHxMbh5C5AgQokcAAQCLNkIXP9IwEA+H48PCsiwAe+AAF40wsIAMBNm8AwHIf/D+pCmVwBgIQBwHSROEsIgBQAQHqOQqYAQEYBgJ2YJlMAoAQAYMtjYuMAUC0AYCd/5tMAgJ34mXsBAFuUIRUBoJEAIBNliEQAaDsArM9WikUAWDAAFGZLxDkA2C0AMElXZkgAsLcAwM4QC7IACAwAMFGIhSkABHsAYMgjI3gAhJkAFEbyVzzxK64Q5yoAAHiZsjy5JDlFgVsILXEHV1cuHijOSRcrFDZhAmGaQC7CeZkZMoE0D+DzzAAAoJEVEeCD8/14zg6uzs42jrYOXy3qvwb/ImJi4/7lz6twQAAA4XR+0f4sL7MagDsGgG3+oiXuBGheC6B194tmsg9AtQCg6dpX83D4fjw8RaGQudnZ5eTk2ErEQlthyld9/mfCX8BX/Wz5fjz89/XgvuIkgTJdgUcE+ODCzPRMpRzPkgmEYtzmj0f8twv//B3TIsRJYrlYKhTjURJxjkSajPMypSKJQpIpxSXS/2Ti3yz7Az7fNQCwaj4Be5EtqF1jA/ZLJxBYdMDi9wAA8rtvwdQoCAOAaIPhz3f/7z/9R6AlAIBmSZJxAABeRCQuVMqzP8cIAABEoIEqsEEb9MEYLMAGHMEF3MEL/GA2hEIkxMJCEEIKZIAccmAprIJCKIbNsB0qYC/UQB00wFFohpNwDi7CVbgOPXAP+mEInsEovIEJBEHICBNhIdqIAWKKWCOOCBeZhfghwUgEEoskIMmIFFEiS5E1SDFSilQgVUgd8j1yAjmHXEa6kTvIADKC/Ia8RzGUgbJRPdQMtUO5qDcahEaiC9BkdDGajxagm9BytBo9jDah59CraA/ajz5DxzDA6BgHM8RsMC7Gw0KxOCwJk2PLsSKsDKvGGrBWrAO7ifVjz7F3BBKBRcAJNgR3QiBhHkFIWExYTthIqCAcJDQR2gk3CQOEUcInIpOoS7QmuhH5xBhiMjGHWEgsI9YSjxMvEHuIQ8Q3JBKJQzInuZACSbGkVNIS0kbSblIj6SypmzRIGiOTydpka7IHOZQsICvIheSd5MPkM+Qb5CHyWwqdYkBxpPhT4ihSympKGeUQ5TTlBmWYMkFVo5pS3aihVBE1j1pCraG2Uq9Rh6gTNHWaOc2DFklLpa2ildMaaBdo92mv6HS6Ed2VHk6X0FfSy+lH6JfoA/R3DA2GFYPHiGcoGZsYBxhnGXcYr5hMphnTixnHVDA3MeuY55kPmW9VWCq2KnwVkcoKlUqVJpUbKi9Uqaqmqt6qC1XzVctUj6leU32uRlUzU+OpCdSWq1WqnVDrUxtTZ6k7qIeqZ6hvVD+kfln9iQZZw0zDT0OkUaCxX+O8xiALYxmzeCwhaw2rhnWBNcQmsc3ZfHYqu5j9HbuLPaqpoTlDM0ozV7NS85RmPwfjmHH4nHROCecop5fzforeFO8p4ikbpjRMuTFlXGuqlpeWWKtIq1GrR+u9Nq7tp52mvUW7WfuBDkHHSidcJ0dnj84FnedT2VPdpwqnFk09OvWuLqprpRuhu0R3v26n7pievl6Ankxvp955vef6HH0v/VT9bfqn9UcMWAazDCQG2wzOGDzFNXFvPB0vx9vxUUNdw0BDpWGVYZfhhJG50Tyj1UaNRg+MacZc4yTjbcZtxqMmBiYhJktN6k3umlJNuaYppjtMO0zHzczNos3WmTWbPTHXMueb55vXm9+3YFp4Wiy2qLa4ZUmy5FqmWe62vG6FWjlZpVhVWl2zRq2drSXWu627pxGnuU6TTque1mfDsPG2ybaptxmw5dgG2662bbZ9YWdiF2e3xa7D7pO9k326fY39PQcNh9kOqx1aHX5ztHIUOlY63prOnO4/fcX0lukvZ1jPEM/YM+O2E8spxGmdU5vTR2cXZ7lzg/OIi4lLgssulz4umxvG3ci95Ep09XFd4XrS9Z2bs5vC7ajbr+427mnuh9yfzDSfKZ5ZM3PQw8hD4FHl0T8Ln5Uwa9+sfk9DT4FntecjL2MvkVet17C3pXeq92HvFz72PnKf4z7jPDfeMt5ZX8w3wLfIt8tPw2+eX4XfQ38j/2T/ev/RAKeAJQFnA4mBQYFbAvv4enwhv44/Ottl9rLZ7UGMoLlBFUGPgq2C5cGtIWjI7JCtIffnmM6RzmkOhVB+6NbQB2HmYYvDfgwnhYeFV4Y/jnCIWBrRMZc1d9HcQ3PfRPpElkTem2cxTzmvLUo1Kj6qLmo82je6NLo/xi5mWczVWJ1YSWxLHDkuKq42bmy+3/zt84fineIL43sXmC/IXXB5oc7C9IWnFqkuEiw6lkBMiE44lPBBECqoFowl8hN3JY4KecIdwmciL9E20YjYQ1wqHk7ySCpNepLskbw1eSTFM6Us5bmEJ6mQvEwNTN2bOp4WmnYgbTI9Or0xg5KRkHFCqiFNk7Zn6mfmZnbLrGWFsv7Fbou3Lx6VB8lrs5CsBVktCrZCpuhUWijXKgeyZ2VXZr/Nico5lqueK83tzLPK25A3nO+f/+0SwhLhkralhktXLR1Y5r2sajmyPHF52wrjFQUrhlYGrDy4irYqbdVPq+1Xl65+vSZ6TWuBXsHKgsG1AWvrC1UK5YV969zX7V1PWC9Z37Vh+oadGz4ViYquFNsXlxV/2CjceOUbh2/Kv5nclLSpq8S5ZM9m0mbp5t4tnlsOlqqX5pcObg3Z2rQN31a07fX2Rdsvl80o27uDtkO5o788uLxlp8nOzTs/VKRU9FT6VDbu0t21Ydf4btHuG3u89jTs1dtbvPf9Psm+21UBVU3VZtVl+0n7s/c/romq6fiW+21drU5tce3HA9ID/QcjDrbXudTVHdI9VFKP1ivrRw7HH77+ne93LQ02DVWNnMbiI3BEeeTp9wnf9x4NOtp2jHus4QfTH3YdZx0vakKa8ppGm1Oa+1tiW7pPzD7R1ureevxH2x8PnDQ8WXlK81TJadrpgtOTZ/LPjJ2VnX1+LvncYNuitnvnY87fag9v77oQdOHSRf+L5zu8O85c8rh08rLb5RNXuFearzpfbep06jz+k9NPx7ucu5quuVxrue56vbV7ZvfpG543zt30vXnxFv/W1Z45Pd2983pv98X39d8W3X5yJ/3Oy7vZdyfurbxPvF/0QO1B2UPdh9U/W/7c2O/cf2rAd6Dz0dxH9waFg8/+kfWPD0MFj5mPy4YNhuueOD45OeI/cv3p/KdDz2TPJp4X/qL+y64XFi9++NXr187RmNGhl/KXk79tfKX96sDrGa/bxsLGHr7JeDMxXvRW++3Bd9x3He+j3w9P5Hwgfyj/aPmx9VPQp/uTGZOT/wQDmPP8YzMt2wAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAACZ0lEQVR42mzSP4icZRTF4ee+38xOkp2sG5cQxVJIIaaKkICxTkqJjQhpJFYiop2F1YKFQqoUVpEoCBYSS7dfOxVFWGIsokUE/0TEye7OzPe977XYNWk83b0cDoffvXHWGxkKYjt0N1fi+FaJIzNIFSJ0kDXn0z5nF1O9Sp5PzaizamLD2NELo5W4sOwXqqX/04o1R2wg9PYs/GXUmTjqpGNxwvWdFzz19Akvjj+XUkYTggylFLfml93due+tZ7+y577BrkJnbNWke8yHmzvgi/4lq+WU1XjCsThl2p1ya3GZ4KNrt03KuhXH0SkkkbTOL5+u2PnuZ/D8axtGMTaKsbOvrINP3v/W3Y9XhCJjQCrUWRedVpaq3nvn7oHXrz8jD8PfvnEGbL0716LXytIoxqizkups4R/VwhB7hpi7sXkbXNo86bkrazK5sXnbEHND7BvMLcykOotz3vlxvZw+faRb08VEiVC64rPdSw/pZ/Ly9EutNi3TkHOLOvN3u3OnHNx7MFio5qq5Ifdce/WHhwEfXPnekPuq/UPPQhrAKOV0MFdyRFQFRefr7Z9wRrb0zfYd1aCpGmr2BvtSTkcp1wZLnX0tx4oQjeHX+UF97P75QGspM7VMqTfopVwb0aY1F4ZWlFK1SCVDHQKUEvphj0ztkEdrvZoLtOkoNS2XlkHJIlroIky7Jw8atDSJdQ/aPTUdtJBaLqVmlJpqQataCZKhY/L4HwcEI/Qbv1v8tivbIdVG1UtNnPVmFmPEoT9l/Dc9Ujp42Mx4uGl6I5pmgdjGzaLbopsdJqZHWZnqtKkXcZU8D/8OAPAMQ4kD8KK1AAAAAElFTkSuQmCCiVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEJGlDQ1BJQ0MgUHJvZmlsZQAAOBGFVd9v21QUPolvUqQWPyBYR4eKxa9VU1u5GxqtxgZJk6XtShal6dgqJOQ6N4mpGwfb6baqT3uBNwb8AUDZAw9IPCENBmJ72fbAtElThyqqSUh76MQPISbtBVXhu3ZiJ1PEXPX6yznfOec7517bRD1fabWaGVWIlquunc8klZOnFpSeTYrSs9RLA9Sr6U4tkcvNEi7BFffO6+EdigjL7ZHu/k72I796i9zRiSJPwG4VHX0Z+AxRzNRrtksUvwf7+Gm3BtzzHPDTNgQCqwKXfZwSeNHHJz1OIT8JjtAq6xWtCLwGPLzYZi+3YV8DGMiT4VVuG7oiZpGzrZJhcs/hL49xtzH/Dy6bdfTsXYNY+5yluWO4D4neK/ZUvok/17X0HPBLsF+vuUlhfwX4j/rSfAJ4H1H0qZJ9dN7nR19frRTeBt4Fe9FwpwtN+2p1MXscGLHR9SXrmMgjONd1ZxKzpBeA71b4tNhj6JGoyFNp4GHgwUp9qplfmnFW5oTdy7NamcwCI49kv6fN5IAHgD+0rbyoBc3SOjczohbyS1drbq6pQdqumllRC/0ymTtej8gpbbuVwpQfyw66dqEZyxZKxtHpJn+tZnpnEdrYBbueF9qQn93S7HQGGHnYP7w6L+YGHNtd1FJitqPAR+hERCNOFi1i1alKO6RQnjKUxL1GNjwlMsiEhcPLYTEiT9ISbN15OY/jx4SMshe9LaJRpTvHr3C/ybFYP1PZAfwfYrPsMBtnE6SwN9ib7AhLwTrBDgUKcm06FSrTfSj187xPdVQWOk5Q8vxAfSiIUc7Z7xr6zY/+hpqwSyv0I0/QMTRb7RMgBxNodTfSPqdraz/sDjzKBrv4zu2+a2t0/HHzjd2Lbcc2sG7GtsL42K+xLfxtUgI7YHqKlqHK8HbCCXgjHT1cAdMlDetv4FnQ2lLasaOl6vmB0CMmwT/IPszSueHQqv6i/qluqF+oF9TfO2qEGTumJH0qfSv9KH0nfS/9TIp0Wboi/SRdlb6RLgU5u++9nyXYe69fYRPdil1o1WufNSdTTsp75BfllPy8/LI8G7AUuV8ek6fkvfDsCfbNDP0dvRh0CrNqTbV7LfEEGDQPJQadBtfGVMWEq3QWWdufk6ZSNsjG2PQjp3ZcnOWWing6noonSInvi0/Ex+IzAreevPhe+CawpgP1/pMTMDo64G0sTCXIM+KdOnFWRfQKdJvQzV1+Bt8OokmrdtY2yhVX2a+qrykJfMq4Ml3VR4cVzTQVz+UoNne4vcKLoyS+gyKO6EHe+75Fdt0Mbe5bRIf/wjvrVmhbqBN97RD1vxrahvBOfOYzoosH9bq94uejSOQGkVM6sN/7HelL4t10t9F4gPdVzydEOx83Gv+uNxo7XyL/FtFl8z9ZAHF4bBsrEwAAAAlwSFlzAAALEwAACxMBAJqcGAAAByVJREFUWAm1l1uIldcVx9d3ruMZZzRaay+pCjFJH6LSRqxQqA1NH0pBiH3Qp774kEAg4EOkxKdQSCjUFvpm6YsNVNoSaGjFtmga2yZgCIIawdv04g2kM7Uz6lzO+c758v/t/9lzTB/61Oxhn7332muv9V+3vb8pnooDVRkzZ4oY/LmK6mQZa05frX6yFJ9Ae7x4qd2IuV1FFM9WMfhaI9Z+pQBAL+aiEZ0QgNBm2YuZmxHF9VZMXqmivFaLweUyuteWYvHGVPWr2f+F7YvF/ola9DZGVJsHUXs8YvBEK1ZrXt9URDwqxY1BdGMQvWjGqkgA+iLUtazHuADUoowHYugKTilaR7SIpZjWqOMRfY090RbasS4JglpFtzWIcqwZa+pSqnWVcLLXijXpZCFpvbgb/VhMe8huMLPylWkci8/oSD8xJq7hj4WUWvXrlbqVrUyKtBYdpX3Bh9YbzsdErwRgbZKyFP+KdqxPssu4l2hDAOOxIj6bCHigKWRNCcpMCHHHB4TJLc+TXxKHnC51Ct+Qgxl/TZ0qE5Be/EdWTwjqQuJJAPIB8qAZk4kZoXJnvHH+27Hq0+0YX12PH+w7E3/8zbWkitN2M8pS7kCKZ761OV55c2fcm+nG7J1e7N/+e3m2nbyKQcAhnHWZLC86B1rxiFRvSIkIgJHFVWzZ+qk4fG5HEr4wV8buVb+Vuv5QeVZsi/HeW//eHZ1HbNfLT5+Jc2dndBav9KXugfqc+pLsv6Xxvk6kVheumnpDnXlTVMZWfHh+Li6cdOKvmGzEC69+WTskzwr1SfUJ9ZWp7z/0pWXlF9+ejQtnUdCWnAxQ+al5Tdz80lIVEP8x9eZQWCQwOTAhNc34Re+rUW8U0S+r2Ns8nWzBKgONBOeX3V3RaCpPRN7XeFcO7yYl+InML2U3VdBVHszHzbSXYLBJkuTSQzBuphoYZ7X/u8O30gFAHHxzi+Yop8ETcfDXW5JyKMd/fFuO9l3mYuwLAl5gbMg8QuKdYQg4Zjcxo7HikMeIn37vcizes9Ide9bGhs9NLPN9YX0ndnzHpbZ4vx9HXr6kc6Sobo2hIkuzOnIh0xMFRlvc0waWL+p3UePCQ/Myjjx/JSnl59CJbUkJgl75g+ZD/D978Yrc7EuMPe4ESo6OYsaasiiX7tADAyny5cGtyMHsDxzFnP0Tx6Z0SfsW27B1PHZ+c13seGZdbNo2Lo6Iu7e7cfznfxc/8ggNQBhZI9dSs2c5k+rFaHBXmZhd32xTGdlZPvzDvefj9XddlgeObYVpuf1o3zkpyrEnCJwBDjlmr9i7XP3jgrYkDamhEqRA8UOBxZ53tcOtBbgyzr53M65f8DU6sVZ1o067cfFBvP+XGzrDOa5s+JkTShIc+dBtlLOLlRpqAUDc+yqQMnViNq81edDVnPixno/vP/dXjn2svbbnPa1RiqXEHVkYQ06RWygnFEtpbZDLAJws2X1OHgfCv+hiRkZU8Y+pmbjwzjTE1D48PR1TV+5IMErgsjex2A8TJrqCHH9Cw6U0BGBkPUWrKTZnPq4L9WqIOFvEO8ml+vbRvyUB/Jw6OiUa9GydM58qQl6lTrNHyiENrwyTkOvXLziVkMlOOsesVKyIFtZB1zfDAGvdyj4xtkD7yHQ8Ynn4hCrwvYA+DOJCSlXAZl3MjNQobNzVPK7gJm0AiPsQyEg0c6s1cbEB5X08AmDz1TTLucApzHHyJgADvUqVysJMKOSicLRQl+emOIvbnaw+ot2pSTzl5zzJVjPaZ6ix7zCSN4E1shOAWnqbyYH8bOqd1h9AGJ0qtl6LRBubcBKxbo6xh60kWlbLjgG4NJ2ETkwqbl7SeUXVSCq+BF1C2bWEgEO4CxBGvOydGmu3ooXv7AEogLFqn2JtWKO8yc9xAmDxjhGiWMOQXe63zCvHtIjOpGOIwvGJlhRQepyzaiu0MQ4MnFhuT7CiJQC+sUg4jtOYO+1IH9OdCwgBSmOkP2r60CarHeXMjxw3PGyvOBnN670EgOPOc1yEYgDYCxbqTPDXki1srChi4R6lpQ+uDmVFDtkA5GH1qJEvQFgacqCFT37pyP+Y+DMJs0Y54NgbiIVn61jhEUrNARuNIi3vOQf8iUeQuNzILe4b/jFZ7RDYJhTbVRaJTxyWh8PgO93hQJCBsSa2GQyyoLlBzWDxgnm9l0JgADgNgVxElCH22xs4NCsaieSUyzWXaSTLDAPlGQB0Kt6JaqpzYjkJQT9id60aNwqZjVqlz9Kqp+JcfDjOAqhirNoCI6MelpVPAjZ/CbFv45Y9YNcicqDMKm/Xo/FPJdMlqZ9SIK7qSrrci9mbl6q3/DGQ5f7XuK347rgKeuMgiicEfLPmT0rGY1K5SdI/ryritlMbJrr/PZ8+I8qf9PF8qhMrT39QHfHLkhj/fz/bi+eb83F/VxX1b6jWvt6KdTs/AvvCmqXE235jAAAAAElFTkSuQmCC",
- _urls : [
- {
- type: "application/x-suggestions+json",
- method: "GET",
- template: "https://search.yahoo.com/sugg/ff",
- params: [
- {
- name: "output",
- value: "fxjson",
- purpose: undefined,
- },
- {
- name: "appid",
- value: "ffd",
- purpose: undefined,
- },
- {
- name: "command",
- value: "{searchTerms}",
- purpose: undefined,
- },
- ],
- },
- {
- type: "text/html",
- method: "GET",
- template: "https://search.yahoo.com/yhs/search",
- params: [
- {
- name: "p",
- value: "{searchTerms}",
- purpose: undefined,
- },
- {
- name: "ei",
- value: "UTF-8",
- purpose: undefined,
- },
- {
- name: "hspart",
- value: "mozilla",
- purpose: undefined,
- },
- {
- name: "hsimp",
- value: "yhs-001",
- purpose: "searchbar",
- },
- {
- name: "hsimp",
- value: "yhs-002",
- purpose: "keyword",
- },
- {
- name: "hsimp",
- value: "yhs-003",
- purpose: "homepage",
- },
- {
- name: "hsimp",
- value: "yhs-004",
- purpose: "newtab",
- },
- {
- name: "hsimp",
- value: "yhs-005",
- purpose: "contextmenu",
- },
- {
- name: "hsimp",
- value: "yhs-007",
- purpose: "system",
- },
- ],
- mozparams: {},
- },
- ],
- },
- };
-
- isSubObjectOf(EXPECTED_ENGINE, engine, "Yahoo");
-}
diff --git a/browser/components/search/test/browser_yahoo_behavior.js b/browser/components/search/test/browser_yahoo_behavior.js
deleted file mode 100644
index 5b2d61422..000000000
--- a/browser/components/search/test/browser_yahoo_behavior.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Test Yahoo search plugin URLs
- */
-
-"use strict";
-
-const BROWSER_SEARCH_PREF = "browser.search.";
-
-
-function test() {
- let engine = Services.search.getEngineByName("Yahoo");
- ok(engine, "Yahoo is installed");
-
- let previouslySelectedEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
- engine.alias = "y";
-
- let base = "https://search.yahoo.com/yhs/search?p=foo&ei=UTF-8&hspart=mozilla";
- let url;
-
- // Test search URLs (including purposes).
- url = engine.getSubmission("foo").uri.spec;
- is(url, base + "&hsimp=yhs-001", "Check search URL for 'foo'");
-
- waitForExplicitFinish();
-
- var gCurrTest;
- var gTests = [
- {
- name: "context menu search",
- searchURL: base + "&hsimp=yhs-005",
- run: function () {
- // Simulate a contextmenu search
- // FIXME: This is a bit "low-level"...
- BrowserSearch.loadSearch("foo", false, "contextmenu");
- }
- },
- {
- name: "keyword search",
- searchURL: base + "&hsimp=yhs-002",
- run: function () {
- gURLBar.value = "? foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "keyword search with alias",
- searchURL: base + "&hsimp=yhs-002",
- run: function () {
- gURLBar.value = "y foo";
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "search bar search",
- searchURL: base + "&hsimp=yhs-001",
- run: function () {
- let sb = BrowserSearch.searchBar;
- sb.focus();
- sb.value = "foo";
- registerCleanupFunction(function () {
- sb.value = "";
- });
- EventUtils.synthesizeKey("VK_RETURN", {});
- }
- },
- {
- name: "new tab search",
- searchURL: base + "&hsimp=yhs-004",
- run: function () {
- function doSearch(doc) {
- // Re-add the listener, and perform a search
- gBrowser.addProgressListener(listener);
- doc.getElementById("newtab-search-text").value = "foo";
- doc.getElementById("newtab-search-submit").click();
- }
-
- // load about:newtab, but remove the listener first so it doesn't
- // get in the way
- gBrowser.removeProgressListener(listener);
- gBrowser.loadURI("about:newtab");
- info("Waiting for about:newtab load");
- tab.linkedBrowser.addEventListener("load", function load(event) {
- if (event.originalTarget != tab.linkedBrowser.contentDocument ||
- event.target.location.href == "about:blank") {
- info("skipping spurious load event");
- return;
- }
- tab.linkedBrowser.removeEventListener("load", load, true);
-
- // Observe page setup
- let win = gBrowser.contentWindow;
- if (win.gSearch.currentEngineName ==
- Services.search.currentEngine.name) {
- doSearch(win.document);
- }
- else {
- info("Waiting for newtab search init");
- win.addEventListener("ContentSearchService", function done(event) {
- info("Got newtab search event " + event.detail.type);
- if (event.detail.type == "State") {
- win.removeEventListener("ContentSearchService", done);
- // Let gSearch respond to the event before continuing.
- executeSoon(() => doSearch(win.document));
- }
- });
- }
- }, true);
- }
- }
- ];
-
- function nextTest() {
- if (gTests.length) {
- gCurrTest = gTests.shift();
- info("Running : " + gCurrTest.name);
- executeSoon(gCurrTest.run);
- } else {
- finish();
- }
- }
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let listener = {
- onStateChange: function onStateChange(webProgress, req, flags, status) {
- info("onStateChange");
- // Only care about top-level document starts
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if (!(flags & docStart) || !webProgress.isTopLevel)
- return;
-
- if (req.originalURI.spec == "about:blank")
- return;
-
- info("received document start");
-
- ok(req instanceof Ci.nsIChannel, "req is a channel");
- is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded");
- info("Actual URI: " + req.URI.spec);
-
- req.cancel(Components.results.NS_ERROR_FAILURE);
-
- executeSoon(nextTest);
- }
- }
-
- registerCleanupFunction(function () {
- engine.alias = undefined;
- gBrowser.removeProgressListener(listener);
- gBrowser.removeTab(tab);
- Services.search.currentEngine = previouslySelectedEngine;
- });
-
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- gBrowser.addProgressListener(listener);
- nextTest();
- }, true);
-}
diff --git a/browser/components/search/test/head.js b/browser/components/search/test/head.js
deleted file mode 100644
index de27b5e1e..000000000
--- a/browser/components/search/test/head.js
+++ /dev/null
@@ -1,156 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-/**
- * Recursively compare two objects and check that every property of expectedObj has the same value
- * on actualObj.
- */
-function isSubObjectOf(expectedObj, actualObj, name) {
- for (let prop in expectedObj) {
- if (typeof expectedObj[prop] == 'function')
- continue;
- if (expectedObj[prop] instanceof Object) {
- is(actualObj[prop].length, expectedObj[prop].length, name + "[" + prop + "]");
- isSubObjectOf(expectedObj[prop], actualObj[prop], name + "[" + prop + "]");
- } else {
- is(actualObj[prop], expectedObj[prop], name + "[" + prop + "]");
- }
- }
-}
-
-function getLocale() {
- const localePref = "general.useragent.locale";
- return getLocalizedPref(localePref, Services.prefs.getCharPref(localePref));
-}
-
-/**
- * Wrapper for nsIPrefBranch::getComplexValue.
- * @param aPrefName
- * The name of the pref to get.
- * @returns aDefault if the requested pref doesn't exist.
- */
-function getLocalizedPref(aPrefName, aDefault) {
- try {
- return Services.prefs.getComplexValue(aPrefName, Ci.nsIPrefLocalizedString).data;
- } catch (ex) {
- return aDefault;
- }
-}
-
-function promiseEvent(aTarget, aEventName, aPreventDefault) {
- function cancelEvent(event) {
- if (aPreventDefault) {
- event.preventDefault();
- }
-
- return true;
- }
-
- return BrowserTestUtils.waitForEvent(aTarget, aEventName, false, cancelEvent);
-}
-
-/**
- * Adds a new search engine to the search service and confirms it completes.
- *
- * @param {String} basename The file to load that contains the search engine
- * details.
- * @param {Object} [options] Options for the test:
- * - {String} [iconURL] The icon to use for the search engine.
- * - {Boolean} [setAsCurrent] Whether to set the new engine to be the
- * current engine or not.
- * - {String} [testPath] Used to override the current test path if this
- * file is used from a different directory.
- * @returns {Promise} The promise is resolved once the engine is added, or
- * rejected if the addition failed.
- */
-function promiseNewEngine(basename, options = {}) {
- return new Promise((resolve, reject) => {
- // Default the setAsCurrent option to true.
- let setAsCurrent =
- options.setAsCurrent == undefined ? true : options.setAsCurrent;
- info("Waiting for engine to be added: " + basename);
- Services.search.init({
- onInitComplete: function() {
- let url = getRootDirectory(options.testPath || gTestPath) + basename;
- let current = Services.search.currentEngine;
- Services.search.addEngine(url, null, options.iconURL || "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- if (setAsCurrent) {
- Services.search.currentEngine = engine;
- }
- registerCleanupFunction(() => {
- if (setAsCurrent) {
- Services.search.currentEngine = current;
- }
- Services.search.removeEngine(engine);
- info("Search engine removed: " + basename);
- });
- resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- reject();
- }
- });
- }
- });
- });
-}
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url)
-{
- info("Wait tab event: load");
-
- function handle(loadedUrl) {
- if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
- info(`Skipping spurious load event for ${loadedUrl}`);
- return false;
- }
-
- info("Tab event received: load");
- return true;
- }
-
- let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
-
- if (url)
- BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
- return loaded;
-}
-
-// Get an array of the one-off buttons.
-function getOneOffs() {
- let oneOffs = [];
- let searchPopup = document.getElementById("PopupSearchAutoComplete");
- let oneOffsContainer =
- document.getAnonymousElementByAttribute(searchPopup, "anonid",
- "search-one-off-buttons");
- let oneOff =
- document.getAnonymousElementByAttribute(oneOffsContainer, "anonid",
- "search-panel-one-offs");
- for (oneOff = oneOff.firstChild; oneOff; oneOff = oneOff.nextSibling) {
- if (oneOff.nodeType == Node.ELEMENT_NODE) {
- if (oneOff.classList.contains("dummy") ||
- oneOff.classList.contains("search-setting-button-compact"))
- break;
- oneOffs.push(oneOff);
- }
- }
- return oneOffs;
-}
diff --git a/browser/components/search/test/opensearch.html b/browser/components/search/test/opensearch.html
deleted file mode 100644
index f4c0cc98e..000000000
--- a/browser/components/search/test/opensearch.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8">
-<link rel="search" type="application/opensearchdescription+xml" title="engine1" href="http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml">
-<link rel="search" type="application/opensearchdescription+xml" title="engine2" href="http://mochi.test:8888/browser/browser/components/search/test/testEngine_mozsearch.xml">
-</head>
-<body></body>
-</html>
diff --git a/browser/components/search/test/test.html b/browser/components/search/test/test.html
deleted file mode 100644
index a39bece4f..000000000
--- a/browser/components/search/test/test.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8" />
- <title>Bug 426329</title>
-</head>
-<body></body>
-</html>
diff --git a/browser/components/search/test/testEngine.xml b/browser/components/search/test/testEngine.xml
deleted file mode 100644
index 21ddc4b9a..000000000
--- a/browser/components/search/test/testEngine.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>Foo</ShortName>
- <Description>Foo Search</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm>
- <moz:Alias>fooalias</moz:Alias>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/testEngine_diacritics.xml b/browser/components/search/test/testEngine_diacritics.xml
deleted file mode 100644
index 0744921eb..000000000
--- a/browser/components/search/test/testEngine_diacritics.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>Foo &#9825;</ShortName>
- <Description>Engine whose ShortName contains non-BMP Unicode characters</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm>
- <moz:Alias>diacriticalias</moz:Alias>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/testEngine_dupe.xml b/browser/components/search/test/testEngine_dupe.xml
deleted file mode 100644
index d2db580c4..000000000
--- a/browser/components/search/test/testEngine_dupe.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
- xmlns:moz="http://www.mozilla.org/2006/browser/search/">
- <ShortName>FooDupe</ShortName>
- <Description>Second Engine Search</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
- <Param name="test" value="{searchTerms}"/>
- </Url>
- <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm>
- <moz:Alias>secondalias</moz:Alias>
-</OpenSearchDescription>
diff --git a/browser/components/search/test/testEngine_mozsearch.xml b/browser/components/search/test/testEngine_mozsearch.xml
deleted file mode 100644
index 9b4c02a0c..000000000
--- a/browser/components/search/test/testEngine_mozsearch.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
- <ShortName>Foo</ShortName>
- <Description>Foo Search</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
- <Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?suggestions&amp;locale={moz:locale}&amp;test={searchTerms}"/>
- <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/">
- <Param name="test" value="{searchTerms}"/>
- <Param name="ie" value="utf-8"/>
- <MozParam name="channel" condition="purpose" purpose="keyword" value="keywordsearch"/>
- <MozParam name="channel" condition="purpose" purpose="contextmenu" value="contextsearch"/>
- </Url>
- <SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</SearchForm>
-</SearchPlugin>
diff --git a/browser/components/search/test/webapi.html b/browser/components/search/test/webapi.html
deleted file mode 100644
index 1ef38b895..000000000
--- a/browser/components/search/test/webapi.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
-<script>
-function installEngine() {
- var query = window.location.search.substring(1);
- var args = JSON.parse(decodeURIComponent(query));
-
- window.external.AddSearchProvider(...args);
-}
-</script>
-</head>
-<body onload="installEngine()">
-</body>
-</html>
diff --git a/browser/components/selfsupport/test/.eslintrc.js b/browser/components/selfsupport/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/selfsupport/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/selfsupport/test/browser.ini b/browser/components/selfsupport/test/browser.ini
deleted file mode 100644
index ba56857b3..000000000
--- a/browser/components/selfsupport/test/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[browser_selfsupportAPI.js]
diff --git a/browser/components/selfsupport/test/browser_selfsupportAPI.js b/browser/components/selfsupport/test/browser_selfsupportAPI.js
deleted file mode 100644
index 2a54d4ae6..000000000
--- a/browser/components/selfsupport/test/browser_selfsupportAPI.js
+++ /dev/null
@@ -1,88 +0,0 @@
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-function test_resetPref() {
- const prefNewName = "browser.newpref.fake";
- Assert.ok(!Preferences.has(prefNewName), "pref should not exist");
-
- const prefExistingName = "extensions.hotfix.id";
- Assert.ok(Preferences.has(prefExistingName), "pref should exist");
- Assert.ok(!Preferences.isSet(prefExistingName), "pref should not be user-set");
- let prefExistingOriginalValue = Preferences.get(prefExistingName);
-
- registerCleanupFunction(function() {
- Preferences.set(prefExistingName, prefExistingOriginalValue);
- Services.prefs.deleteBranch(prefNewName);
- });
-
- // 1. do nothing on an inexistent pref
- MozSelfSupport.resetPref(prefNewName);
- Assert.ok(!Preferences.has(prefNewName), "pref should still not exist");
-
- // 2. creation of a new pref
- Preferences.set(prefNewName, 10);
- Assert.ok(Preferences.has(prefNewName), "pref should exist");
- Assert.equal(Preferences.get(prefNewName), 10, "pref value should be 10");
-
- MozSelfSupport.resetPref(prefNewName);
- Assert.ok(!Preferences.has(prefNewName), "pref should not exist any more");
-
- // 3. do nothing on an unchanged existing pref
- MozSelfSupport.resetPref(prefExistingName);
- Assert.ok(Preferences.has(prefExistingName), "pref should still exist");
- Assert.equal(Preferences.get(prefExistingName), prefExistingOriginalValue, "pref value should be the same as original");
-
- // 4. change the value of an existing pref
- Preferences.set(prefExistingName, "anyone@mozilla.org");
- Assert.ok(Preferences.has(prefExistingName), "pref should exist");
- Assert.equal(Preferences.get(prefExistingName), "anyone@mozilla.org", "pref value should have changed");
-
- MozSelfSupport.resetPref(prefExistingName);
- Assert.ok(Preferences.has(prefExistingName), "pref should still exist");
- Assert.equal(Preferences.get(prefExistingName), prefExistingOriginalValue, "pref value should be the same as original");
-
- // 5. delete an existing pref
- // deleteBranch is implemented in such a way that
- // clearUserPref can't undo its action
- // see discussion in bug 1075160
-}
-
-function test_resetSearchEngines()
-{
- const defaultEngineOriginal = Services.search.defaultEngine;
- const visibleEnginesOriginal = Services.search.getVisibleEngines();
-
- // 1. do nothing on unchanged search configuration
- MozSelfSupport.resetSearchEngines();
- Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset");
- Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal,
- "default visible engines set should be reset");
-
- // 2. change the default search engine
- const defaultEngineNew = visibleEnginesOriginal[3];
- Assert.notEqual(defaultEngineOriginal, defaultEngineNew, "new default engine should be different from original");
- Services.search.defaultEngine = defaultEngineNew;
- Assert.equal(Services.search.defaultEngine, defaultEngineNew, "default engine should be set to new");
- MozSelfSupport.resetSearchEngines();
- Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset");
- Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal,
- "default visible engines set should be reset");
-
- // 3. remove an engine
- const engineRemoved = visibleEnginesOriginal[2];
- Services.search.removeEngine(engineRemoved);
- Assert.ok(Services.search.getVisibleEngines().indexOf(engineRemoved) == -1,
- "removed engine should not be visible any more");
- MozSelfSupport.resetSearchEngines();
- Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset");
- Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal,
- "default visible engines set should be reset");
-
- // 4. add an angine
- // we don't remove user-added engines as they are only used if selected
-}
-
-function test()
-{
- test_resetPref();
- test_resetSearchEngines();
-}
diff --git a/browser/components/sessionstore/test/.eslintrc.js b/browser/components/sessionstore/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/sessionstore/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/sessionstore/test/browser.ini b/browser/components/sessionstore/test/browser.ini
deleted file mode 100644
index 37154a0cc..000000000
--- a/browser/components/sessionstore/test/browser.ini
+++ /dev/null
@@ -1,242 +0,0 @@
-# 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/.
-
-# browser_506482.js is disabled because of frequent failures (bug 538672)
-# browser_526613.js is disabled because of frequent failures (bug 534489)
-# browser_589246.js is disabled for leaking browser windows (bug 752467)
-# browser_580512.js is disabled for leaking browser windows (bug 752467)
-
-[DEFAULT]
-support-files =
- head.js
- content.js
- content-forms.js
- browser_cookies.sjs
- browser_formdata_sample.html
- browser_formdata_xpath_sample.html
- browser_frametree_sample.html
- browser_frametree_sample_frameset.html
- browser_frame_history_index.html
- browser_frame_history_index2.html
- browser_frame_history_index_blank.html
- browser_frame_history_a.html
- browser_frame_history_b.html
- browser_frame_history_c.html
- browser_frame_history_c1.html
- browser_frame_history_c2.html
- browser_form_restore_events_sample.html
- browser_formdata_format_sample.html
- browser_pageStyle_sample.html
- browser_pageStyle_sample_nested.html
- browser_sessionHistory_slow.sjs
- browser_scrollPositions_sample.html
- browser_scrollPositions_sample_frameset.html
- browser_scrollPositions_readerModeArticle.html
- browser_sessionStorage.html
- browser_248970_b_sample.html
- browser_339445_sample.html
- browser_423132_sample.html
- browser_447951_sample.html
- browser_454908_sample.html
- browser_456342_sample.xhtml
- browser_463205_sample.html
- browser_463206_sample.html
- browser_466937_sample.html
- browser_485482_sample.html
- browser_637020_slow.sjs
- browser_662743_sample.html
- browser_739531_sample.html
- browser_911547_sample.html
- browser_911547_sample.html^headers^
- restore_redirect_http.html
- restore_redirect_http.html^headers^
- restore_redirect_js.html
- restore_redirect_target.html
- browser_1234021_page.html
-
-#NB: the following are disabled
-# browser_464620_a.html
-# browser_464620_b.html
-# browser_464620_xd.html
-
-
-#disabled-for-intermittent-failures--bug-766044, browser_459906_empty.html
-#disabled-for-intermittent-failures--bug-766044, browser_459906_sample.html
-#disabled-for-intermittent-failures--bug-765389, browser_461743_sample.html
-
-[browser_aboutPrivateBrowsing.js]
-[browser_aboutSessionRestore.js]
-[browser_async_duplicate_tab.js]
-[browser_async_flushes.js]
-run-if = e10s && crashreporter
-skip-if = debug # bug 1167933
-[browser_async_remove_tab.js]
-run-if = e10s
-skip-if = debug # bug 1211084
-[browser_attributes.js]
-[browser_backup_recovery.js]
-[browser_broadcast.js]
-[browser_capabilities.js]
-[browser_cleaner.js]
-[browser_cookies.js]
-[browser_crashedTabs.js]
-skip-if = !e10s || !crashreporter
-[browser_unrestored_crashedTabs.js]
-skip-if = !e10s || !crashreporter
-[browser_revive_crashed_bg_tabs.js]
-skip-if = !e10s || !crashreporter
-[browser_dying_cache.js]
-[browser_dynamic_frames.js]
-[browser_form_restore_events.js]
-[browser_formdata.js]
-[browser_formdata_cc.js]
-[browser_formdata_format.js]
-[browser_formdata_xpath.js]
-[browser_frametree.js]
-[browser_frame_history.js]
-[browser_global_store.js]
-[browser_history_persist.js]
-[browser_label_and_icon.js]
-[browser_merge_closed_tabs.js]
-[browser_page_title.js]
-[browser_pageStyle.js]
-[browser_pending_tabs.js]
-[browser_privatetabs.js]
-[browser_purge_shistory.js]
-skip-if = e10s # Bug 1271024
-[browser_replace_load.js]
-[browser_restore_redirect.js]
-[browser_restore_cookies_noOriginAttributes.js]
-[browser_scrollPositions.js]
-[browser_scrollPositionsReaderMode.js]
-[browser_sessionHistory.js]
-[browser_sessionStorage.js]
-[browser_sessionStorage_size.js]
-[browser_swapDocShells.js]
-[browser_switch_remoteness.js]
-run-if = e10s
-[browser_upgrade_backup.js]
-[browser_windowRestore_perwindowpb.js]
-[browser_248970_b_perwindowpb.js]
-# Disabled because of leaks.
-# Re-enabling and rewriting this test is tracked in bug 936919.
-skip-if = true
-[browser_339445.js]
-[browser_345898.js]
-[browser_350525.js]
-[browser_354894_perwindowpb.js]
-[browser_367052.js]
-[browser_393716.js]
-[browser_394759_basic.js]
-# Disabled for intermittent failures, bug 944372.
-skip-if = true
-[browser_394759_behavior.js]
-[browser_394759_perwindowpb.js]
-[browser_394759_purge.js]
-[browser_423132.js]
-[browser_447951.js]
-[browser_454908.js]
-[browser_456342.js]
-[browser_461634.js]
-[browser_463205.js]
-[browser_463206.js]
-[browser_464199.js]
-[browser_465215.js]
-[browser_465223.js]
-[browser_466937.js]
-[browser_467409-backslashplosion.js]
-[browser_477657.js]
-[browser_480893.js]
-[browser_485482.js]
-[browser_485563.js]
-[browser_490040.js]
-[browser_491168.js]
-[browser_491577.js]
-[browser_495495.js]
-[browser_500328.js]
-[browser_514751.js]
-[browser_522375.js]
-[browser_522545.js]
-[browser_524745.js]
-[browser_528776.js]
-[browser_579868.js]
-[browser_579879.js]
-skip-if = (os == 'linux' && e10s && (debug||asan)) # Bug 1234404
-[browser_581937.js]
-[browser_586147.js]
-[browser_586068-apptabs.js]
-[browser_586068-apptabs_ondemand.js]
-[browser_586068-browser_state_interrupted.js]
-[browser_586068-cascade.js]
-[browser_586068-multi_window.js]
-[browser_586068-reload.js]
-[browser_586068-select.js]
-[browser_586068-window_state.js]
-[browser_586068-window_state_override.js]
-[browser_588426.js]
-[browser_590268.js]
-[browser_590563.js]
-[browser_595601-restore_hidden.js]
-[browser_597071.js]
-skip-if = true # Needs to be rewritten as Marionette test, bug 995916
-[browser_599909.js]
-[browser_600545.js]
-[browser_601955.js]
-[browser_607016.js]
-[browser_615394-SSWindowState_events.js]
-[browser_618151.js]
-[browser_623779.js]
-[browser_624727.js]
-[browser_628270.js]
-[browser_635418.js]
-[browser_636279.js]
-[browser_637020.js]
-[browser_644409-scratchpads.js]
-[browser_645428.js]
-[browser_659591.js]
-[browser_662743.js]
-[browser_662812.js]
-[browser_665702-state_session.js]
-[browser_682507.js]
-[browser_687710.js]
-[browser_687710_2.js]
-[browser_694378.js]
-[browser_701377.js]
-[browser_705597.js]
-[browser_707862.js]
-[browser_739531.js]
-[browser_739805.js]
-[browser_819510_perwindowpb.js]
-skip-if = (os == 'win' && bits == 64) # Bug 1284312
-
-# Disabled for frequent intermittent failures
-[browser_464620_a.js]
-skip-if = true
-[browser_464620_b.js]
-skip-if = true
-
-# Disabled on OS X:
-[browser_625016.js]
-skip-if = os == "mac"
-
-[browser_911547.js]
-[browser_send_async_message_oom.js]
-[browser_multiple_navigateAndRestore.js]
-run-if = e10s
-[browser_async_window_flushing.js]
-[browser_forget_async_closings.js]
-[browser_newtab_userTypedValue.js]
-[browser_parentProcessRestoreHash.js]
-run-if = e10s
-[browser_sessionStoreContainer.js]
-[browser_windowStateContainer.js]
-[browser_1234021.js]
-[browser_remoteness_flip_on_restore.js]
-run-if = e10s
-[browser_background_tab_crash.js]
-run-if = e10s && crashreporter
-
-# Disabled on debug for frequent intermittent failures:
-[browser_undoCloseById.js]
-skip-if = debug
diff --git a/browser/components/sessionstore/test/browser_1234021.js b/browser/components/sessionstore/test/browser_1234021.js
deleted file mode 100644
index a307d1e01..000000000
--- a/browser/components/sessionstore/test/browser_1234021.js
+++ /dev/null
@@ -1,18 +0,0 @@
-"use strict";
-
-const PREF = 'network.cookie.cookieBehavior';
-const PAGE_URL = 'http://mochi.test:8888/browser/' +
- 'browser/components/sessionstore/test/browser_1234021_page.html';
-const BEHAVIOR_REJECT = 2;
-
-add_task(function* test() {
- yield pushPrefs([PREF, BEHAVIOR_REJECT]);
-
- yield BrowserTestUtils.withNewTab({
- gBrowser: gBrowser,
- url: PAGE_URL
- }, function* handler(aBrowser) {
- yield TabStateFlusher.flush(aBrowser);
- ok(true, "Flush didn't time out");
- });
-});
diff --git a/browser/components/sessionstore/test/browser_1234021_page.html b/browser/components/sessionstore/test/browser_1234021_page.html
deleted file mode 100644
index 4a74fbc02..000000000
--- a/browser/components/sessionstore/test/browser_1234021_page.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<!doctype html>
-<html>
- <script>
- sessionStorage
- </script>
-</html>
diff --git a/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js b/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js
deleted file mode 100644
index f5775cd5b..000000000
--- a/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test (B) for Bug 248970 **/
- waitForExplicitFinish();
-
- let windowsToClose = [];
- let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
- let filePath = file.path;
- let fieldList = {
- "//input[@name='input']": Date.now().toString(),
- "//input[@name='spaced 1']": Math.random().toString(),
- "//input[3]": "three",
- "//input[@type='checkbox']": true,
- "//input[@name='uncheck']": false,
- "//input[@type='radio'][1]": false,
- "//input[@type='radio'][2]": true,
- "//input[@type='radio'][3]": false,
- "//select": 2,
- "//select[@multiple]": [1, 3],
- "//textarea[1]": "",
- "//textarea[2]": "Some text... " + Math.random(),
- "//textarea[3]": "Some more text\n" + new Date(),
- "//input[@type='file']": filePath
- };
-
- registerCleanupFunction(function* () {
- for (let win of windowsToClose) {
- yield BrowserTestUtils.closeWindow(win);
- }
- });
-
- function test(aLambda) {
- try {
- return aLambda() || true;
- } catch(ex) { }
- return false;
- }
-
- function getElementByXPath(aTab, aQuery) {
- let doc = aTab.linkedBrowser.contentDocument;
- let xptype = Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE;
- return doc.evaluate(aQuery, doc, null, xptype, null).singleNodeValue;
- }
-
- function setFormValue(aTab, aQuery, aValue) {
- let node = getElementByXPath(aTab, aQuery);
- if (typeof aValue == "string")
- node.value = aValue;
- else if (typeof aValue == "boolean")
- node.checked = aValue;
- else if (typeof aValue == "number")
- node.selectedIndex = aValue;
- else
- Array.forEach(node.options, (aOpt, aIx) =>
- (aOpt.selected = aValue.indexOf(aIx) > -1));
- }
-
- function compareFormValue(aTab, aQuery, aValue) {
- let node = getElementByXPath(aTab, aQuery);
- if (!node)
- return false;
- if (node instanceof Ci.nsIDOMHTMLInputElement)
- return aValue == (node.type == "checkbox" || node.type == "radio" ?
- node.checked : node.value);
- if (node instanceof Ci.nsIDOMHTMLTextAreaElement)
- return aValue == node.value;
- if (!node.multiple)
- return aValue == node.selectedIndex;
- return Array.every(node.options, (aOpt, aIx) =>
- (aValue.indexOf(aIx) > -1) == aOpt.selected);
- }
-
- //////////////////////////////////////////////////////////////////
- // Test (B) : Session data restoration between windows //
- //////////////////////////////////////////////////////////////////
-
- let rootDir = getRootDirectory(gTestPath);
- const testURL = rootDir + "browser_248970_b_sample.html";
- const testURL2 = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_248970_b_sample.html";
-
- whenNewWindowLoaded({ private: false }, function(aWin) {
- windowsToClose.push(aWin);
-
- // get closed tab count
- let count = ss.getClosedTabCount(aWin);
- let max_tabs_undo =
- Services.prefs.getIntPref("browser.sessionstore.max_tabs_undo");
- ok(0 <= count && count <= max_tabs_undo,
- "getClosedTabCount should return zero or at most max_tabs_undo");
-
- // setup a state for tab (A) so we can check later that is restored
- let key = "key";
- let value = "Value " + Math.random();
- let state = { entries: [{ url: testURL }], extData: { key: value } };
-
- // public session, add new tab: (A)
- let tab_A = aWin.gBrowser.addTab(testURL);
- ss.setTabState(tab_A, JSON.stringify(state));
- promiseBrowserLoaded(tab_A.linkedBrowser).then(() => {
- // make sure that the next closed tab will increase getClosedTabCount
- Services.prefs.setIntPref(
- "browser.sessionstore.max_tabs_undo", max_tabs_undo + 1)
-
- // populate tab_A with form data
- for (let i in fieldList)
- setFormValue(tab_A, i, fieldList[i]);
-
- // public session, close tab: (A)
- aWin.gBrowser.removeTab(tab_A);
-
- // verify that closedTabCount increased
- ok(ss.getClosedTabCount(aWin) > count,
- "getClosedTabCount has increased after closing a tab");
-
- // verify tab: (A), in undo list
- let tab_A_restored = test(() => ss.undoCloseTab(aWin, 0));
- ok(tab_A_restored, "a tab is in undo list");
- promiseTabRestored(tab_A_restored).then(() => {
- is(testURL, tab_A_restored.linkedBrowser.currentURI.spec,
- "it's the same tab that we expect");
- aWin.gBrowser.removeTab(tab_A_restored);
-
- whenNewWindowLoaded({ private: true }, function(aWin) {
- windowsToClose.push(aWin);
-
- // setup a state for tab (B) so we can check that its duplicated
- // properly
- let key1 = "key1";
- let value1 = "Value " + Math.random();
- let state1 = {
- entries: [{ url: testURL2 }], extData: { key1: value1 }
- };
-
- let tab_B = aWin.gBrowser.addTab(testURL2);
- promiseTabState(tab_B, state1).then(() => {
- // populate tab: (B) with different form data
- for (let item in fieldList)
- setFormValue(tab_B, item, fieldList[item]);
-
- // duplicate tab: (B)
- let tab_C = aWin.gBrowser.duplicateTab(tab_B);
- promiseTabRestored(tab_C).then(() => {
- // verify the correctness of the duplicated tab
- is(ss.getTabValue(tab_C, key1), value1,
- "tab successfully duplicated - correct state");
-
- for (let item in fieldList)
- ok(compareFormValue(tab_C, item, fieldList[item]),
- "The value for \"" + item + "\" was correctly duplicated");
-
- // private browsing session, close tab: (C) and (B)
- aWin.gBrowser.removeTab(tab_C);
- aWin.gBrowser.removeTab(tab_B);
-
- finish();
- });
- });
- });
- });
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_248970_b_sample.html b/browser/components/sessionstore/test/browser_248970_b_sample.html
deleted file mode 100644
index 76c3ae1aa..000000000
--- a/browser/components/sessionstore/test/browser_248970_b_sample.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<meta charset="utf-8">
-<title>Test for bug 248970</title>
-
-<h3>Text Fields</h3>
-<input type="text" name="input">
-<input type="text" name="spaced 1">
-<input>
-
-<h3>Checkboxes and Radio buttons</h3>
-<input type="checkbox" name="check"> Check 1
-<input type="checkbox" name="uncheck" checked> Check 2
-<p>
-<input type="radio" name="group" value="1"> Radio 1
-<input type="radio" name="group" value="some"> Radio 2
-<input type="radio" name="group" checked> Radio 3
-
-<h3>Selects</h3>
-<select name="any">
- <option value="1"> Select 1
- <option value="some"> Select 2
- <option>Select 3
-</select>
-<select multiple="multiple">
- <option value=1> Multi-select 1
- <option value=2> Multi-select 2
- <option value=3> Multi-select 3
- <option value=4> Multi-select 4
-</select>
-
-<h3>Text Areas</h3>
-<textarea name="testarea"></textarea>
-<textarea name="sized one" rows="5" cols="25"></textarea>
-<textarea></textarea>
-
-<h3>File Selector</h3>
-<input type="file">
diff --git a/browser/components/sessionstore/test/browser_339445.js b/browser/components/sessionstore/test/browser_339445.js
deleted file mode 100644
index c38a6cb18..000000000
--- a/browser/components/sessionstore/test/browser_339445.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* 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/. */
-
-add_task(function* test() {
- /** Test for Bug 339445 **/
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_339445_sample.html";
-
- let tab = gBrowser.addTab(testURL);
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function() {
- let doc = content.document;
- is(doc.getElementById("storageTestItem").textContent, "PENDING",
- "sessionStorage value has been set");
- });
-
- let tab2 = gBrowser.duplicateTab(tab);
- yield promiseTabRestored(tab2);
-
- yield ContentTask.spawn(tab2.linkedBrowser, null, function() {
- let doc2 = content.document;
- is(doc2.getElementById("storageTestItem").textContent, "SUCCESS",
- "sessionStorage value has been duplicated");
- });
-
- // clean up
- yield Promise.all([ BrowserTestUtils.removeTab(tab2),
- BrowserTestUtils.removeTab(tab) ]);
-});
diff --git a/browser/components/sessionstore/test/browser_339445_sample.html b/browser/components/sessionstore/test/browser_339445_sample.html
deleted file mode 100644
index 32656a8d9..000000000
--- a/browser/components/sessionstore/test/browser_339445_sample.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<meta charset="utf-8">
-<title>Test for bug 339445</title>
-
-storageTestItem = <span id="storageTestItem">FAIL</span>
-
-<!--
- storageTestItem's textContent will be one of the following:
- * FAIL : sessionStorage wasn't available
- * PENDING : the test value has been initialized on first load
- * SUCCESS : the test value was correctly retrieved
--->
-
-<script type="application/javascript">
- document.getElementById("storageTestItem").textContent =
- sessionStorage["storageTestItem"] || "PENDING";
- sessionStorage["storageTestItem"] = "SUCCESS";
-</script>
diff --git a/browser/components/sessionstore/test/browser_345898.js b/browser/components/sessionstore/test/browser_345898.js
deleted file mode 100644
index bd4a46e69..000000000
--- a/browser/components/sessionstore/test/browser_345898.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 345898 **/
-
- function test(aLambda) {
- try {
- aLambda();
- return false;
- }
- catch (ex) {
- return ex.name == "NS_ERROR_ILLEGAL_VALUE" ||
- ex.name == "NS_ERROR_FAILURE";
- }
- }
-
- // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE
- ok(test(() => ss.getWindowState({})),
- "Invalid window for getWindowState throws");
- ok(test(() => ss.setWindowState({}, "", false)),
- "Invalid window for setWindowState throws");
- ok(test(() => ss.getTabState({})),
- "Invalid tab for getTabState throws");
- ok(test(() => ss.setTabState({}, "{}")),
- "Invalid tab state for setTabState throws");
- ok(test(() => ss.setTabState({}, JSON.stringify({ entries: [] }))),
- "Invalid tab for setTabState throws");
- ok(test(() => ss.duplicateTab({}, {})),
- "Invalid tab for duplicateTab throws");
- ok(test(() => ss.duplicateTab({}, gBrowser.selectedTab)),
- "Invalid window for duplicateTab throws");
- ok(test(() => ss.getClosedTabData({})),
- "Invalid window for getClosedTabData throws");
- ok(test(() => ss.undoCloseTab({}, 0)),
- "Invalid window for undoCloseTab throws");
- ok(test(() => ss.undoCloseTab(window, -1)),
- "Invalid index for undoCloseTab throws");
- ok(test(() => ss.getWindowValue({}, "")),
- "Invalid window for getWindowValue throws");
- ok(test(() => ss.setWindowValue({}, "", "")),
- "Invalid window for setWindowValue throws");
-}
diff --git a/browser/components/sessionstore/test/browser_350525.js b/browser/components/sessionstore/test/browser_350525.js
deleted file mode 100644
index 1d87b3754..000000000
--- a/browser/components/sessionstore/test/browser_350525.js
+++ /dev/null
@@ -1,102 +0,0 @@
-"use strict";
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-})
-
-add_task(function* () {
- /** Test for Bug 350525 **/
-
- function test(aLambda) {
- try {
- return aLambda() || true;
- }
- catch (ex) { }
- return false;
- }
-
- ////////////////////////////
- // setWindowValue, et al. //
- ////////////////////////////
- let key = "Unique name: " + Date.now();
- let value = "Unique value: " + Math.random();
-
- // test adding
- ok(test(() => ss.setWindowValue(window, key, value)), "set a window value");
-
- // test retrieving
- is(ss.getWindowValue(window, key), value, "stored window value matches original");
-
- // test deleting
- ok(test(() => ss.deleteWindowValue(window, key)), "delete the window value");
-
- // value should not exist post-delete
- is(ss.getWindowValue(window, key), "", "window value was deleted");
-
- // test deleting a non-existent value
- ok(test(() => ss.deleteWindowValue(window, key)), "delete non-existent window value");
-
- /////////////////////////
- // setTabValue, et al. //
- /////////////////////////
- key = "Unique name: " + Math.random();
- value = "Unique value: " + Date.now();
- let tab = gBrowser.addTab();
- tab.linkedBrowser.stop();
-
- // test adding
- ok(test(() => ss.setTabValue(tab, key, value)), "store a tab value");
-
- // test retrieving
- is(ss.getTabValue(tab, key), value, "stored tab value match original");
-
- // test deleting
- ok(test(() => ss.deleteTabValue(tab, key)), "delete the tab value");
-
- // value should not exist post-delete
- is(ss.getTabValue(tab, key), "", "tab value was deleted");
-
- // test deleting a non-existent value
- ok(test(() => ss.deleteTabValue(tab, key)), "delete non-existent tab value");
-
- // clean up
- yield promiseRemoveTab(tab);
-
- /////////////////////////////////////
- // getClosedTabCount, undoCloseTab //
- /////////////////////////////////////
-
- // get closed tab count
- let count = ss.getClosedTabCount(window);
- let max_tabs_undo = gPrefService.getIntPref("browser.sessionstore.max_tabs_undo");
- ok(0 <= count && count <= max_tabs_undo,
- "getClosedTabCount returns zero or at most max_tabs_undo");
-
- // create a new tab
- let testURL = "about:";
- tab = gBrowser.addTab(testURL);
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // make sure that the next closed tab will increase getClosedTabCount
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", max_tabs_undo + 1);
- registerCleanupFunction(() => gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo"));
-
- // remove tab
- yield promiseRemoveTab(tab);
-
- // getClosedTabCount
- let newcount = ss.getClosedTabCount(window);
- ok(newcount > count, "after closing a tab, getClosedTabCount has been incremented");
-
- // undoCloseTab
- tab = test(() => ss.undoCloseTab(window, 0));
- ok(tab, "undoCloseTab doesn't throw")
-
- yield promiseTabRestored(tab);
- is(tab.linkedBrowser.currentURI.spec, testURL, "correct tab was reopened");
-
- // clean up
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_354894_perwindowpb.js b/browser/components/sessionstore/test/browser_354894_perwindowpb.js
deleted file mode 100644
index bf80cd710..000000000
--- a/browser/components/sessionstore/test/browser_354894_perwindowpb.js
+++ /dev/null
@@ -1,474 +0,0 @@
-/* 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/. */
-
-/**
- * Checks that restoring the last browser window in session is actually
- * working.
- *
- * @see https://bugzilla.mozilla.org/show_bug.cgi?id=354894
- * @note It is implicitly tested that restoring the last window works when
- * non-browser windows are around. The "Run Tests" window as well as the main
- * browser window (wherein the test code gets executed) won't be considered
- * browser windows. To achiveve this said main browser window has it's windowtype
- * attribute modified so that it's not considered a browser window any longer.
- * This is crucial, because otherwise there would be two browser windows around,
- * said main test window and the one opened by the tests, and hence the new
- * logic wouldn't be executed at all.
- * @note Mac only tests the new notifications, as restoring the last window is
- * not enabled on that platform (platform shim; the application is kept running
- * although there are no windows left)
- * @note There is a difference when closing a browser window with
- * BrowserTryToCloseWindow() as opposed to close(). The former will make
- * nsSessionStore restore a window next time it gets a chance and will post
- * notifications. The latter won't.
- */
-
-// Some urls that might be opened in tabs and/or popups
-// Do not use about:blank:
-// That one is reserved for special purposes in the tests
-const TEST_URLS = ["about:mozilla", "about:buildconfig"];
-
-// Number of -request notifications to except
-// remember to adjust when adding new tests
-const NOTIFICATIONS_EXPECTED = 6;
-
-// Window features of popup windows
-const POPUP_FEATURES = "toolbar=no,resizable=no,status=no";
-
-// Window features of browser windows
-const CHROME_FEATURES = "chrome,all,dialog=no";
-
-const IS_MAC = navigator.platform.match(/Mac/);
-
-/**
- * Returns an Object with two properties:
- * open (int):
- * A count of how many non-closed navigator:browser windows there are.
- * winstates (int):
- * A count of how many windows there are in the SessionStore state.
- */
-function getBrowserWindowsCount() {
- let open = 0;
- let e = Services.wm.getEnumerator("navigator:browser");
- while (e.hasMoreElements()) {
- if (!e.getNext().closed)
- ++open;
- }
-
- let winstates = JSON.parse(ss.getBrowserState()).windows.length;
-
- return { open, winstates };
-}
-
-add_task(function* setup() {
- // Make sure we've only got one browser window to start with
- let { open, winstates } = getBrowserWindowsCount();
- is(open, 1, "Should only be one open window");
- is(winstates, 1, "Should only be one window state in SessionStore");
-
- // This test takes some time to run, and it could timeout randomly.
- // So we require a longer timeout. See bug 528219.
- requestLongerTimeout(3);
-
- // Make the main test window not count as a browser window any longer
- let oldWinType = document.documentElement.getAttribute("windowtype");
- document.documentElement.setAttribute("windowtype", "navigator:testrunner");
-
- registerCleanupFunction(() => {
- document.documentElement.setAttribute("windowtype", "navigator:browser");
- });
-});
-
-/**
- * Sets up one of our tests by setting the right preferences, and
- * then opening up a browser window preloaded with some tabs.
- *
- * @param options (Object)
- * An object that can contain the following properties:
- *
- * private:
- * Whether or not the opened window should be private.
- *
- * denyFirst:
- * Whether or not the first window that attempts to close
- * via closeWindowForRestoration should be denied.
- *
- * @param testFunction (Function*)
- * A generator function that yields Promises to be run
- * once the test has been set up.
- *
- * @returns Promise
- * Resolves once the test has been cleaned up.
- */
-let setupTest = Task.async(function*(options, testFunction) {
- yield pushPrefs(["browser.startup.page", 3],
- ["browser.tabs.warnOnClose", false]);
-
- // Observe these, and also use to count the number of hits
- let observing = {
- "browser-lastwindow-close-requested": 0,
- "browser-lastwindow-close-granted": 0
- };
-
- /**
- * Helper: Will observe and handle the notifications for us
- */
- let hitCount = 0;
- function observer(aCancel, aTopic, aData) {
- // count so that we later may compare
- observing[aTopic]++;
-
- // handle some tests
- if (options.denyFirst && ++hitCount == 1) {
- aCancel.QueryInterface(Ci.nsISupportsPRBool).data = true;
- }
- }
-
- for (let o in observing) {
- Services.obs.addObserver(observer, o, false);
- }
-
- let private = options.private || false;
- let newWin = yield promiseNewWindowLoaded({ private });
-
- injectTestTabs(newWin);
-
- yield testFunction(newWin, observing);
-
- let count = getBrowserWindowsCount();
- is(count.open, 0, "Got right number of open windows");
- is(count.winstates, 1, "Got right number of stored window states");
-
- for (let o in observing) {
- Services.obs.removeObserver(observer, o);
- }
-
- yield popPrefs();
-});
-
-/**
- * Loads a TEST_URLS into a browser window.
- *
- * @param win (Window)
- * The browser window to load the tabs in
- */
-function injectTestTabs(win) {
- TEST_URLS.forEach(function (url) {
- win.gBrowser.addTab(url);
- });
-}
-
-/**
- * Attempts to close a window via BrowserTryToCloseWindow so that
- * we get the browser-lastwindow-close-requested and
- * browser-lastwindow-close-granted observer notifications.
- *
- * @param win (Window)
- * The window to try to close
- * @returns Promise
- * Resolves to true if the window closed, or false if the window
- * was denied the ability to close.
- */
-function closeWindowForRestoration(win) {
- return new Promise((resolve) => {
- let closePromise = BrowserTestUtils.windowClosed(win);
- win.BrowserTryToCloseWindow();
- if (!win.closed) {
- resolve(false);
- return;
- }
-
- closePromise.then(() => {
- resolve(true);
- });
- });
-}
-
-/**
- * Normal in-session restore
- *
- * @note: Non-Mac only
- *
- * Should do the following:
- * 1. Open a new browser window
- * 2. Add some tabs
- * 3. Close that window
- * 4. Opening another window
- * 5. Checks that state is restored
- */
-add_task(function* test_open_close_normal() {
- if (IS_MAC) {
- return;
- }
-
- yield setupTest({ denyFirst: true }, function*(newWin, obs) {
- let closed = yield closeWindowForRestoration(newWin);
- ok(!closed, "First close request should have been denied");
-
- closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Second close request should be accepted");
-
- newWin = yield promiseNewWindowLoaded();
- is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2,
- "Restored window in-session with otherpopup windows around");
-
- // Note that this will not result in the the browser-lastwindow-close
- // notifications firing for this other newWin.
- yield BrowserTestUtils.closeWindow(newWin);
-
- // setupTest gave us a window which was denied for closing once, and then
- // closed.
- is(obs["browser-lastwindow-close-requested"], 2,
- "Got expected browser-lastwindow-close-requested notifications");
- is(obs["browser-lastwindow-close-granted"], 1,
- "Got expected browser-lastwindow-close-granted notifications");
- });
-});
-
-/**
- * PrivateBrowsing in-session restore
- *
- * @note: Non-Mac only
- *
- * Should do the following:
- * 1. Open a new browser window A
- * 2. Add some tabs
- * 3. Close the window A as the last window
- * 4. Open a private browsing window B
- * 5. Make sure that B didn't restore the tabs from A
- * 6. Close private browsing window B
- * 7. Open a new window C
- * 8. Make sure that new window C has restored tabs from A
- */
-add_task(function* test_open_close_private_browsing() {
- if (IS_MAC) {
- return;
- }
-
- yield setupTest({}, function*(newWin, obs) {
- let closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Should be able to close the window");
-
- newWin = yield promiseNewWindowLoaded({private: true});
- is(newWin.gBrowser.browsers.length, 1,
- "Did not restore in private browing mode");
-
- closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Should be able to close the window");
-
- newWin = yield promiseNewWindowLoaded();
- is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2,
- "Restored tabs in a new non-private window");
-
- // Note that this will not result in the the browser-lastwindow-close
- // notifications firing for this other newWin.
- yield BrowserTestUtils.closeWindow(newWin);
-
- // We closed two windows with closeWindowForRestoration, and both
- // should have been successful.
- is(obs["browser-lastwindow-close-requested"], 2,
- "Got expected browser-lastwindow-close-requested notifications");
- is(obs["browser-lastwindow-close-granted"], 2,
- "Got expected browser-lastwindow-close-granted notifications");
- });
-});
-
-/**
- * Open some popup windows to check those aren't restored, but the browser
- * window is.
- *
- * @note: Non-Mac only
- *
- * Should do the following:
- * 1. Open a new browser window
- * 2. Add some tabs
- * 3. Open some popups
- * 4. Add another tab to one popup (so that it gets stored) and close it again
- * 5. Close the browser window
- * 6. Open another browser window
- * 7. Make sure that the tabs of the closed browser window, but not the popup,
- * are restored
- */
-add_task(function* test_open_close_window_and_popup() {
- if (IS_MAC) {
- return;
- }
-
- yield setupTest({}, function*(newWin, obs) {
- let popupPromise = BrowserTestUtils.waitForNewWindow();
- openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[0]);
- let popup = yield popupPromise;
-
- let popup2Promise = BrowserTestUtils.waitForNewWindow();
- openDialog(location, "popup2", POPUP_FEATURES, TEST_URLS[1]);
- let popup2 = yield popup2Promise;
-
- popup2.gBrowser.addTab(TEST_URLS[0]);
-
- let closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Should be able to close the window");
-
- yield BrowserTestUtils.closeWindow(popup2);
-
- newWin = yield promiseNewWindowLoaded();
-
- is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2,
- "Restored window and associated tabs in session");
-
- yield BrowserTestUtils.closeWindow(popup);
- yield BrowserTestUtils.closeWindow(newWin);
-
- // We closed one window with closeWindowForRestoration, and it should
- // have been successful.
- is(obs["browser-lastwindow-close-requested"], 1,
- "Got expected browser-lastwindow-close-requested notifications");
- is(obs["browser-lastwindow-close-granted"], 1,
- "Got expected browser-lastwindow-close-granted notifications");
- });
-});
-
-/**
- * Open some popup window to check it isn't restored. Instead nothing at all
- * should be restored
- *
- * @note: Non-Mac only
- *
- * Should do the following:
- * 1. Open a popup
- * 2. Add another tab to the popup (so that it gets stored) and close it again
- * 3. Open a window
- * 4. Check that nothing at all is restored
- * 5. Open two browser windows and close them again
- * 6. undoCloseWindow() one
- * 7. Open another browser window
- * 8. Check that nothing at all is restored
- */
-add_task(function* test_open_close_only_popup() {
- if (IS_MAC) {
- return;
- }
-
- yield setupTest({}, function*(newWin, obs) {
- // We actually don't care about the initial window in this test.
- yield BrowserTestUtils.closeWindow(newWin);
-
- // This will cause nsSessionStore to restore a window the next time it
- // gets a chance.
- let popupPromise = BrowserTestUtils.waitForNewWindow();
- openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[1]);
- let popup = yield popupPromise;
-
- is(popup.gBrowser.browsers.length, 1,
- "Did not restore the popup window (1)");
-
- let closed = yield closeWindowForRestoration(popup);
- ok(closed, "Should be able to close the window");
-
- popupPromise = BrowserTestUtils.waitForNewWindow();
- openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[1]);
- popup = yield popupPromise;
-
- popup.gBrowser.addTab(TEST_URLS[0]);
- is(popup.gBrowser.browsers.length, 2,
- "Did not restore to the popup window (2)");
-
- yield BrowserTestUtils.closeWindow(popup);
-
- newWin = yield promiseNewWindowLoaded();
- isnot(newWin.gBrowser.browsers.length, 2,
- "Did not restore the popup window");
- is(TEST_URLS.indexOf(newWin.gBrowser.browsers[0].currentURI.spec), -1,
- "Did not restore the popup window (2)");
- yield BrowserTestUtils.closeWindow(newWin);
-
- // We closed one popup window with closeWindowForRestoration, and popup
- // windows should never fire the browser-lastwindow notifications.
- is(obs["browser-lastwindow-close-requested"], 0,
- "Got expected browser-lastwindow-close-requested notifications");
- is(obs["browser-lastwindow-close-granted"], 0,
- "Got expected browser-lastwindow-close-granted notifications");
- });
-});
-
-/**
- * Open some windows and do undoCloseWindow. This should prevent any
- * restoring later in the test
- *
- * @note: Non-Mac only
- *
- * Should do the following:
- * 1. Open two browser windows and close them again
- * 2. undoCloseWindow() one
- * 3. Open another browser window
- * 4. Make sure nothing at all is restored
- */
-add_task(function* test_open_close_restore_from_popup() {
- if (IS_MAC) {
- return;
- }
-
- yield setupTest({}, function*(newWin, obs) {
- let newWin2 = yield promiseNewWindowLoaded();
- yield injectTestTabs(newWin2);
-
- let closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Should be able to close the window");
- closed = yield closeWindowForRestoration(newWin2);
- ok(closed, "Should be able to close the window");
-
- let counts = getBrowserWindowsCount();
- is(counts.open, 0, "Got right number of open windows");
- is(counts.winstates, 1, "Got right number of window states");
-
- newWin = undoCloseWindow(0);
- yield BrowserTestUtils.waitForEvent(newWin, "load");
-
- // Make sure we wait until this window is restored.
- yield BrowserTestUtils.waitForEvent(newWin.gBrowser.tabContainer,
- "SSTabRestored");
-
- newWin2 = yield promiseNewWindowLoaded();
-
- is(newWin2.gBrowser.browsers.length, 1,
- "Did not restore, as undoCloseWindow() was last called");
- is(TEST_URLS.indexOf(newWin2.gBrowser.browsers[0].currentURI.spec), -1,
- "Did not restore, as undoCloseWindow() was last called (2)");
-
- counts = getBrowserWindowsCount();
- is(counts.open, 2, "Got right number of open windows");
- is(counts.winstates, 3, "Got right number of window states");
-
- yield BrowserTestUtils.closeWindow(newWin);
- yield BrowserTestUtils.closeWindow(newWin2);
-
- counts = getBrowserWindowsCount();
- is(counts.open, 0, "Got right number of open windows");
- is(counts.winstates, 1, "Got right number of window states");
- });
-});
-
-/**
- * Test if closing can be denied on Mac.
- * @note: Mac only
- */
-add_task(function* test_mac_notifications() {
- if (!IS_MAC) {
- return;
- }
-
- yield setupTest({ denyFirst: true }, function*(newWin, obs) {
- let closed = yield closeWindowForRestoration(newWin);
- ok(!closed, "First close attempt should be denied");
- closed = yield closeWindowForRestoration(newWin);
- ok(closed, "Second close attempt should be granted");
-
- // We tried closing once, and got denied. Then we tried again and
- // succeeded. That means 2 close requests, and 1 close granted.
- is(obs["browser-lastwindow-close-requested"], 2,
- "Got expected browser-lastwindow-close-requested notifications");
- is(obs["browser-lastwindow-close-granted"], 1,
- "Got expected browser-lastwindow-close-granted notifications");
- });
-});
-
diff --git a/browser/components/sessionstore/test/browser_367052.js b/browser/components/sessionstore/test/browser_367052.js
deleted file mode 100644
index 3cc89a66c..000000000
--- a/browser/components/sessionstore/test/browser_367052.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function* () {
- // make sure that the next closed tab will increase getClosedTabCount
- let max_tabs_undo = gPrefService.getIntPref("browser.sessionstore.max_tabs_undo");
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", max_tabs_undo + 1);
- registerCleanupFunction(() => gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo"));
-
- // Empty the list of closed tabs.
- while (ss.getClosedTabCount(window)) {
- ss.forgetClosedTab(window, 0);
- }
-
- // restore a blank tab
- let tab = gBrowser.addTab("about:");
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- let count = yield promiseSHistoryCount(tab.linkedBrowser);
- ok(count >= 1, "the new tab does have at least one history entry");
-
- yield promiseTabState(tab, {entries: []});
-
- // We may have a different sessionHistory object if the tab
- // switched from non-remote to remote.
- count = yield promiseSHistoryCount(tab.linkedBrowser);
- is(count, 0, "the tab was restored without any history whatsoever");
-
- yield promiseRemoveTab(tab);
- is(ss.getClosedTabCount(window), 0,
- "The closed blank tab wasn't added to Recently Closed Tabs");
-});
-
-function promiseSHistoryCount(browser) {
- return ContentTask.spawn(browser, null, function* () {
- return docShell.QueryInterface(Ci.nsIWebNavigation).sessionHistory.count;
- });
-}
diff --git a/browser/components/sessionstore/test/browser_393716.js b/browser/components/sessionstore/test/browser_393716.js
deleted file mode 100644
index c59bdcc8b..000000000
--- a/browser/components/sessionstore/test/browser_393716.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = "about:config";
-
-/**
- * Bug 393716 - Basic tests for getTabState(), setTabState(), and duplicateTab().
- */
-add_task(function test_set_tabstate() {
- let key = "Unique key: " + Date.now();
- let value = "Unique value: " + Math.random();
-
- // create a new tab
- let tab = gBrowser.addTab(URL);
- ss.setTabValue(tab, key, value);
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // get the tab's state
- yield TabStateFlusher.flush(tab.linkedBrowser);
- let state = ss.getTabState(tab);
- ok(state, "get the tab's state");
-
- // verify the tab state's integrity
- state = JSON.parse(state);
- ok(state instanceof Object && state.entries instanceof Array && state.entries.length > 0,
- "state object seems valid");
- ok(state.entries.length == 1 && state.entries[0].url == URL,
- "Got the expected state object (test URL)");
- ok(state.extData && state.extData[key] == value,
- "Got the expected state object (test manually set tab value)");
-
- // clean up
- gBrowser.removeTab(tab);
-});
-
-add_task(function test_set_tabstate_and_duplicate() {
- let key2 = "key2";
- let value2 = "Value " + Math.random();
- let value3 = "Another value: " + Date.now();
- let state = { entries: [{ url: URL }], extData: { key2: value2 } };
-
- // create a new tab
- let tab = gBrowser.addTab();
- // set the tab's state
- ss.setTabState(tab, JSON.stringify(state));
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // verify the correctness of the restored tab
- ok(ss.getTabValue(tab, key2) == value2 && tab.linkedBrowser.currentURI.spec == URL,
- "the tab's state was correctly restored");
-
- // add text data
- yield setInputValue(tab.linkedBrowser, {id: "textbox", value: value3});
-
- // duplicate the tab
- let tab2 = ss.duplicateTab(window, tab);
- yield promiseTabRestored(tab2);
-
- // verify the correctness of the duplicated tab
- ok(ss.getTabValue(tab2, key2) == value2 &&
- tab2.linkedBrowser.currentURI.spec == URL,
- "correctly duplicated the tab's state");
- let textbox = yield getInputValue(tab2.linkedBrowser, {id: "textbox"});
- is(textbox, value3, "also duplicated text data");
-
- // clean up
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_394759_basic.js b/browser/components/sessionstore/test/browser_394759_basic.js
deleted file mode 100644
index 1b1650e27..000000000
--- a/browser/components/sessionstore/test/browser_394759_basic.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_URL = "data:text/html;charset=utf-8,<input%20id=txt>" +
- "<input%20type=checkbox%20id=chk>";
-
-Cu.import("resource:///modules/sessionstore/SessionStore.jsm");
-
-/**
- * This test ensures that closing a window is a reversible action. We will
- * close the the window, restore it and check that all data has been restored.
- * This includes window-specific data as well as form data for tabs.
- */
-function test() {
- waitForExplicitFinish();
-
- let uniqueKey = "bug 394759";
- let uniqueValue = "unik" + Date.now();
- let uniqueText = "pi != " + Math.random();
-
- // Clear the list of closed windows.
- forgetClosedWindows();
-
- provideWindow(function onTestURLLoaded(newWin) {
- newWin.gBrowser.addTab().linkedBrowser.stop();
-
- // Mark the window with some unique data to be restored later on.
- ss.setWindowValue(newWin, uniqueKey, uniqueValue);
- let [txt, chk] = newWin.content.document.querySelectorAll("#txt, #chk");
- txt.value = uniqueText;
-
- let browser = newWin.gBrowser.selectedBrowser;
- setInputChecked(browser, {id: "chk", checked: true}).then(() => {
- BrowserTestUtils.closeWindow(newWin).then(() => {
- is(ss.getClosedWindowCount(), 1,
- "The closed window was added to Recently Closed Windows");
-
- let data = SessionStore.getClosedWindowData(false);
-
- // Verify that non JSON serialized data is the same as JSON serialized data.
- is(JSON.stringify(data), ss.getClosedWindowData(),
- "Non-serialized data is the same as serialized data")
-
- ok(data[0].title == TEST_URL && JSON.stringify(data[0]).indexOf(uniqueText) > -1,
- "The closed window data was stored correctly");
-
- // Reopen the closed window and ensure its integrity.
- let newWin2 = ss.undoCloseWindow(0);
-
- ok(newWin2 instanceof ChromeWindow,
- "undoCloseWindow actually returned a window");
- is(ss.getClosedWindowCount(), 0,
- "The reopened window was removed from Recently Closed Windows");
-
- // SSTabRestored will fire more than once, so we need to make sure we count them.
- let restoredTabs = 0;
- let expectedTabs = data[0].tabs.length;
- newWin2.addEventListener("SSTabRestored", function sstabrestoredListener(aEvent) {
- ++restoredTabs;
- info("Restored tab " + restoredTabs + "/" + expectedTabs);
- if (restoredTabs < expectedTabs) {
- return;
- }
-
- is(restoredTabs, expectedTabs, "Correct number of tabs restored");
- newWin2.removeEventListener("SSTabRestored", sstabrestoredListener, true);
-
- is(newWin2.gBrowser.tabs.length, 2,
- "The window correctly restored 2 tabs");
- is(newWin2.gBrowser.currentURI.spec, TEST_URL,
- "The window correctly restored the URL");
-
- let [txt, chk] = newWin2.content.document.querySelectorAll("#txt, #chk");
- ok(txt.value == uniqueText && chk.checked,
- "The window correctly restored the form");
- is(ss.getWindowValue(newWin2, uniqueKey), uniqueValue,
- "The window correctly restored the data associated with it");
-
- // Clean up.
- BrowserTestUtils.closeWindow(newWin2).then(finish);
- }, true);
- });
- });
- }, TEST_URL);
-}
-
-function setInputChecked(browser, data) {
- return sendMessage(browser, "ss-test:setInputChecked", data);
-}
diff --git a/browser/components/sessionstore/test/browser_394759_behavior.js b/browser/components/sessionstore/test/browser_394759_behavior.js
deleted file mode 100644
index aa74dc061..000000000
--- a/browser/components/sessionstore/test/browser_394759_behavior.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Test helper function that opens a series of windows, closes them
- * and then checks the closed window data from SessionStore against
- * expected results.
- *
- * @param windowsToOpen (Array)
- * An array of Objects, where each object must define a single
- * property "isPopup" for whether or not the opened window should
- * be a popup.
- * @param expectedResults (Array)
- * An Object with two properies: mac and other, where each points
- * at yet another Object, with the following properties:
- *
- * popup (int):
- * The number of popup windows we expect to be in the closed window
- * data.
- * normal (int):
- * The number of normal windows we expect to be in the closed window
- * data.
- * @returns Promise
- */
-function testWindows(windowsToOpen, expectedResults) {
- return Task.spawn(function*() {
- for (let winData of windowsToOpen) {
- let features = "chrome,dialog=no," +
- (winData.isPopup ? "all=no" : "all");
- let url = "http://example.com/?window=" + windowsToOpen.length;
-
- let openWindowPromise = BrowserTestUtils.waitForNewWindow(true, url);
- openDialog(getBrowserURL(), "", features, url);
- let win = yield openWindowPromise;
- yield BrowserTestUtils.closeWindow(win);
- }
-
- let closedWindowData = JSON.parse(ss.getClosedWindowData());
- let numPopups = closedWindowData.filter(function(el, i, arr) {
- return el.isPopup;
- }).length;
- let numNormal = ss.getClosedWindowCount() - numPopups;
- // #ifdef doesn't work in browser-chrome tests, so do a simple regex on platform
- let oResults = navigator.platform.match(/Mac/) ? expectedResults.mac
- : expectedResults.other;
- is(numPopups, oResults.popup,
- "There were " + oResults.popup + " popup windows to reopen");
- is(numNormal, oResults.normal,
- "There were " + oResults.normal + " normal windows to repoen");
- });
-}
-
-add_task(function* test_closed_window_states() {
- // This test takes quite some time, and timeouts frequently, so we require
- // more time to run.
- // See Bug 518970.
- requestLongerTimeout(2);
-
- let windowsToOpen = [{isPopup: false},
- {isPopup: false},
- {isPopup: true},
- {isPopup: true},
- {isPopup: true}];
- let expectedResults = {mac: {popup: 3, normal: 0},
- other: {popup: 3, normal: 1}};
-
- yield testWindows(windowsToOpen, expectedResults);
-
-
- let windowsToOpen2 = [{isPopup: false},
- {isPopup: false},
- {isPopup: false},
- {isPopup: false},
- {isPopup: false}];
- let expectedResults2 = {mac: {popup: 0, normal: 3},
- other: {popup: 0, normal: 3}};
-
- yield testWindows(windowsToOpen2, expectedResults2);
-}); \ No newline at end of file
diff --git a/browser/components/sessionstore/test/browser_394759_perwindowpb.js b/browser/components/sessionstore/test/browser_394759_perwindowpb.js
deleted file mode 100644
index 83eec3070..000000000
--- a/browser/components/sessionstore/test/browser_394759_perwindowpb.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TESTS = [
- { url: "about:config",
- key: "bug 394759 Non-PB",
- value: "uniq" + r() },
- { url: "about:mozilla",
- key: "bug 394759 PB",
- value: "uniq" + r() },
-];
-
-function promiseTestOpenCloseWindow(aIsPrivate, aTest) {
- return Task.spawn(function*() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ "private": aIsPrivate });
- win.gBrowser.selectedBrowser.loadURI(aTest.url);
- yield promiseBrowserLoaded(win.gBrowser.selectedBrowser);
- yield Promise.resolve();
- // Mark the window with some unique data to be restored later on.
- ss.setWindowValue(win, aTest.key, aTest.value);
- yield TabStateFlusher.flushWindow(win);
- // Close.
- yield BrowserTestUtils.closeWindow(win);
- });
-}
-
-function promiseTestOnWindow(aIsPrivate, aValue) {
- return Task.spawn(function*() {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ "private": aIsPrivate });
- yield TabStateFlusher.flushWindow(win);
- let data = JSON.parse(ss.getClosedWindowData())[0];
- is(ss.getClosedWindowCount(), 1, "Check that the closed window count hasn't changed");
- ok(JSON.stringify(data).indexOf(aValue) > -1,
- "Check the closed window data was stored correctly");
- registerCleanupFunction(() => BrowserTestUtils.closeWindow(win));
- });
-}
-
-add_task(function* init() {
- forgetClosedWindows();
- while (ss.getClosedTabCount(window) > 0) {
- ss.forgetClosedTab(window, 0);
- }
-});
-
-add_task(function* main() {
- yield promiseTestOpenCloseWindow(false, TESTS[0]);
- yield promiseTestOpenCloseWindow(true, TESTS[1]);
- yield promiseTestOnWindow(false, TESTS[0].value);
- yield promiseTestOnWindow(true, TESTS[0].value);
-});
-
diff --git a/browser/components/sessionstore/test/browser_394759_purge.js b/browser/components/sessionstore/test/browser_394759_purge.js
deleted file mode 100644
index 75144aba1..000000000
--- a/browser/components/sessionstore/test/browser_394759_purge.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/* 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/. */
-
-Components.utils.import("resource://gre/modules/ForgetAboutSite.jsm");
-
-function waitForClearHistory(aCallback) {
- let observer = {
- observe: function(aSubject, aTopic, aData) {
- Services.obs.removeObserver(this, "browser:purge-domain-data");
- setTimeout(aCallback, 0);
- }
- };
- Services.obs.addObserver(observer, "browser:purge-domain-data", false);
-}
-
-function test() {
- waitForExplicitFinish();
- // utility functions
- function countClosedTabsByTitle(aClosedTabList, aTitle) {
- return aClosedTabList.filter(aData => aData.title == aTitle).length;
- }
-
- function countOpenTabsByTitle(aOpenTabList, aTitle) {
- return aOpenTabList.filter(aData => aData.entries.some(aEntry => aEntry.title == aTitle)).length;
- }
-
- // backup old state
- let oldState = ss.getBrowserState();
- let oldState_wins = JSON.parse(oldState).windows.length;
- if (oldState_wins != 1)
- ok(false, "oldState in test_purge has " + oldState_wins + " windows instead of 1");
-
- // create a new state for testing
- const REMEMBER = Date.now(), FORGET = Math.random();
- let testState = {
- windows: [ { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 } ],
- _closedWindows : [
- // _closedWindows[0]
- {
- tabs: [
- { entries: [{ url: "http://example.com/", title: REMEMBER }] },
- { entries: [{ url: "http://mozilla.org/", title: FORGET }] }
- ],
- selected: 2,
- title: "mozilla.org",
- _closedTabs: []
- },
- // _closedWindows[1]
- {
- tabs: [
- { entries: [{ url: "http://mozilla.org/", title: FORGET }] },
- { entries: [{ url: "http://example.com/", title: REMEMBER }] },
- { entries: [{ url: "http://example.com/", title: REMEMBER }] },
- { entries: [{ url: "http://mozilla.org/", title: FORGET }] },
- { entries: [{ url: "http://example.com/", title: REMEMBER }] }
- ],
- selected: 5,
- _closedTabs: []
- },
- // _closedWindows[2]
- {
- tabs: [
- { entries: [{ url: "http://example.com/", title: REMEMBER }] }
- ],
- selected: 1,
- _closedTabs: [
- {
- state: {
- entries: [
- { url: "http://mozilla.org/", title: FORGET },
- { url: "http://mozilla.org/again", title: "doesn't matter" }
- ]
- },
- pos: 1,
- title: FORGET
- },
- {
- state: {
- entries: [
- { url: "http://example.com", title: REMEMBER }
- ]
- },
- title: REMEMBER
- }
- ]
- }
- ]
- };
-
- // set browser to test state
- ss.setBrowserState(JSON.stringify(testState));
-
- // purge domain & check that we purged correctly for closed windows
- ForgetAboutSite.removeDataFromDomain("mozilla.org");
- waitForClearHistory(function() {
- let closedWindowData = JSON.parse(ss.getClosedWindowData());
-
- // First set of tests for _closedWindows[0] - tests basics
- let win = closedWindowData[0];
- is(win.tabs.length, 1, "1 tab was removed");
- is(countOpenTabsByTitle(win.tabs, FORGET), 0,
- "The correct tab was removed");
- is(countOpenTabsByTitle(win.tabs, REMEMBER), 1,
- "The correct tab was remembered");
- is(win.selected, 1, "Selected tab has changed");
- is(win.title, REMEMBER, "The window title was correctly updated");
-
- // Test more complicated case
- win = closedWindowData[1];
- is(win.tabs.length, 3, "2 tabs were removed");
- is(countOpenTabsByTitle(win.tabs, FORGET), 0,
- "The correct tabs were removed");
- is(countOpenTabsByTitle(win.tabs, REMEMBER), 3,
- "The correct tabs were remembered");
- is(win.selected, 3, "Selected tab has changed");
- is(win.title, REMEMBER, "The window title was correctly updated");
-
- // Tests handling of _closedTabs
- win = closedWindowData[2];
- is(countClosedTabsByTitle(win._closedTabs, REMEMBER), 1,
- "The correct number of tabs were removed, and the correct ones");
- is(countClosedTabsByTitle(win._closedTabs, FORGET), 0,
- "All tabs to be forgotten were indeed removed");
-
- // restore pre-test state
- ss.setBrowserState(oldState);
- finish();
- });
-}
diff --git a/browser/components/sessionstore/test/browser_423132.js b/browser/components/sessionstore/test/browser_423132.js
deleted file mode 100644
index 584002cff..000000000
--- a/browser/components/sessionstore/test/browser_423132.js
+++ /dev/null
@@ -1,59 +0,0 @@
-"use strict";
-
-/**
- * Tests that cookies are stored and restored correctly
- * by sessionstore (bug 423132).
- */
-add_task(function*() {
- const testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_423132_sample.html";
-
- Services.cookies.removeAll();
- // make sure that sessionstore.js can be forced to be created by setting
- // the interval pref to 0
- yield SpecialPowers.pushPrefEnv({
- set: [["browser.sessionstore.interval", 0]]
- });
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let browser = win.gBrowser.selectedBrowser;
- browser.loadURI(testURL);
- yield BrowserTestUtils.browserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
-
- // get the sessionstore state for the window
- let state = ss.getWindowState(win);
-
- // verify our cookie got set during pageload
- let enumerator = Services.cookies.enumerator;
- let cookie;
- let i = 0;
- while (enumerator.hasMoreElements()) {
- cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
- i++;
- }
- Assert.equal(i, 1, "expected one cookie");
-
- // remove the cookie
- Services.cookies.removeAll();
-
- // restore the window state
- ss.setWindowState(win, state, true);
-
- // at this point, the cookie should be restored...
- enumerator = Services.cookies.enumerator;
- let cookie2;
- while (enumerator.hasMoreElements()) {
- cookie2 = enumerator.getNext().QueryInterface(Ci.nsICookie);
- if (cookie.name == cookie2.name)
- break;
- }
- is(cookie.name, cookie2.name, "cookie name successfully restored");
- is(cookie.value, cookie2.value, "cookie value successfully restored");
- is(cookie.path, cookie2.path, "cookie path successfully restored");
-
- // clean up
- Services.cookies.removeAll();
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/sessionstore/test/browser_423132_sample.html b/browser/components/sessionstore/test/browser_423132_sample.html
deleted file mode 100644
index 6ff7e7aa3..000000000
--- a/browser/components/sessionstore/test/browser_423132_sample.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <script type="text/javascript">
- // generate an enormous random number...
- var r = Math.floor(Math.random() * Math.pow(2, 62)).toString();
-
- // ... and use it to set a randomly named cookie
- document.cookie = r + "=value; path=/ohai";
- </script>
-<body>
-</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_447951.js b/browser/components/sessionstore/test/browser_447951.js
deleted file mode 100644
index a7b6a5ee8..000000000
--- a/browser/components/sessionstore/test/browser_447951.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 447951 **/
-
- waitForExplicitFinish();
- const baseURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_447951_sample.html#";
-
- // Make sure the functionality added in bug 943339 doesn't affect the results
- gPrefService.setIntPref("browser.sessionstore.max_serialize_back", -1);
- gPrefService.setIntPref("browser.sessionstore.max_serialize_forward", -1);
- registerCleanupFunction(function () {
- gPrefService.clearUserPref("browser.sessionstore.max_serialize_back");
- gPrefService.clearUserPref("browser.sessionstore.max_serialize_forward");
- });
-
- let tab = gBrowser.addTab();
- promiseBrowserLoaded(tab.linkedBrowser).then(() => {
- let tabState = { entries: [] };
- let max_entries = gPrefService.getIntPref("browser.sessionhistory.max_entries");
- for (let i = 0; i < max_entries; i++)
- tabState.entries.push({ url: baseURL + i });
-
- promiseTabState(tab, tabState).then(() => {
- return TabStateFlusher.flush(tab.linkedBrowser);
- }).then(() => {
- tabState = JSON.parse(ss.getTabState(tab));
- is(tabState.entries.length, max_entries, "session history filled to the limit");
- is(tabState.entries[0].url, baseURL + 0, "... but not more");
-
- // visit yet another anchor (appending it to session history)
- ContentTask.spawn(tab.linkedBrowser, null, function() {
- content.window.document.querySelector("a").click();
- }).then(flushAndCheck);
-
- function flushAndCheck() {
- TabStateFlusher.flush(tab.linkedBrowser).then(check);
- }
-
- function check() {
- tabState = JSON.parse(ss.getTabState(tab));
- if (tab.linkedBrowser.currentURI.spec != baseURL + "end") {
- // It may take a few passes through the event loop before we
- // get the right URL.
- executeSoon(flushAndCheck);
- return;
- }
-
- is(tab.linkedBrowser.currentURI.spec, baseURL + "end",
- "the new anchor was loaded");
- is(tabState.entries[tabState.entries.length - 1].url, baseURL + "end",
- "... and ignored");
- is(tabState.entries[0].url, baseURL + 1,
- "... and the first item was removed");
-
- // clean up
- gBrowser.removeTab(tab);
- finish();
- }
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_447951_sample.html b/browser/components/sessionstore/test/browser_447951_sample.html
deleted file mode 100644
index 00282f25e..000000000
--- a/browser/components/sessionstore/test/browser_447951_sample.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE html>
-<meta charset="utf-8">
-<title>Testcase for bug 447951</title>
-
-<a href="#end">click me</a>
diff --git a/browser/components/sessionstore/test/browser_454908.js b/browser/components/sessionstore/test/browser_454908.js
deleted file mode 100644
index fb8206e2f..000000000
--- a/browser/components/sessionstore/test/browser_454908.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_454908_sample.html";
-const PASS = "pwd-" + Math.random();
-
-/**
- * Bug 454908 - Don't save/restore values of password fields.
- */
-add_task(function* test_dont_save_passwords() {
- // Make sure we do save form data.
- Services.prefs.clearUserPref("browser.sessionstore.privacy_level");
-
- // Add a tab with a password field.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Fill in some values.
- let usernameValue = "User " + Math.random();
- yield setInputValue(browser, {id: "username", value: usernameValue});
- yield setInputValue(browser, {id: "passwd", value: PASS});
-
- // Close and restore the tab.
- yield promiseRemoveTab(tab);
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that password fields aren't saved/restored.
- let username = yield getInputValue(browser, {id: "username"});
- is(username, usernameValue, "username was saved/restored");
- let passwd = yield getInputValue(browser, {id: "passwd"});
- is(passwd, "", "password wasn't saved/restored");
-
- // Write to disk and read our file.
- yield forceSaveState();
- yield promiseForEachSessionRestoreFile((state, key) =>
- // Ensure that we have not saved our password.
- ok(!state.includes(PASS), "password has not been written to file " + key)
- );
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_454908_sample.html b/browser/components/sessionstore/test/browser_454908_sample.html
deleted file mode 100644
index 02f40bf20..000000000
--- a/browser/components/sessionstore/test/browser_454908_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<title>Test for bug 454908</title>
-
-<h3>Dummy Login</h3>
-<form>
-<p>Username: <input type="text" id="username">
-<p>Password: <input type="password" id="passwd">
-</form>
diff --git a/browser/components/sessionstore/test/browser_456342.js b/browser/components/sessionstore/test/browser_456342.js
deleted file mode 100644
index d7ed33ee5..000000000
--- a/browser/components/sessionstore/test/browser_456342.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_456342_sample.xhtml";
-
-/**
- * Bug 456342 - Restore values from non-standard input field types.
- */
-add_task(function test_restore_nonstandard_input_values() {
- // Add tab with various non-standard input field types.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Fill in form values.
- let expectedValue = Math.random();
- yield setFormElementValues(browser, {value: expectedValue});
-
- // Remove tab and check collected form data.
- yield promiseRemoveTab(tab);
- let undoItems = JSON.parse(ss.getClosedTabData(window));
- let savedFormData = undoItems[0].state.formdata;
-
- let countGood = 0, countBad = 0;
- for (let id of Object.keys(savedFormData.id)) {
- if (savedFormData.id[id] == expectedValue) {
- countGood++;
- } else {
- countBad++;
- }
- }
-
- for (let exp of Object.keys(savedFormData.xpath)) {
- if (savedFormData.xpath[exp] == expectedValue) {
- countGood++;
- } else {
- countBad++;
- }
- }
-
- is(countGood, 4, "Saved text for non-standard input fields");
- is(countBad, 0, "Didn't save text for ignored field types");
-});
-
-function setFormElementValues(browser, data) {
- return sendMessage(browser, "ss-test:setFormElementValues", data);
-}
diff --git a/browser/components/sessionstore/test/browser_456342_sample.xhtml b/browser/components/sessionstore/test/browser_456342_sample.xhtml
deleted file mode 100644
index a08777a8d..000000000
--- a/browser/components/sessionstore/test/browser_456342_sample.xhtml
+++ /dev/null
@@ -1,36 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-
-<head><title>Test for bug 456342</title></head>
-
-<body>
-<form>
-<h3>Non-standard &lt;input&gt;s</h3>
-<p>Search <input type="search" id="searchTerm"/></p>
-<p>Image Search: <input type="image search" /></p>
-<p>Autocomplete: <input type="autocomplete" name="fill-in"/></p>
-<p>Mistyped: <input type="txet" name="mistyped"/></p>
-
-<h3>Ignored types</h3>
-<input type="hidden" name="hideme"/>
-<input type="HIDDEN" name="hideme2"/>
-<input type="submit" name="submit"/>
-<input type="reset" name="reset"/>
-<input type="image" name="image"/>
-<input type="button" name="button"/>
-<input type="password" name="password"/>
-<input type="PassWord" name="password2"/>
-<input type="PASSWORD" name="password3"/>
-<input autocomplete="off" name="auto1"/>
-<input type="text" autocomplete="OFF" name="auto2"/>
-<textarea autocomplete="off" name="auto3"/>
-<select autocomplete="off" name="auto4">
- <option value="1" selected="true"/>
- <option value="2"/>
- <option value="3"/>
-</select>
-</form>
-
-</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_459906.js b/browser/components/sessionstore/test/browser_459906.js
deleted file mode 100644
index cadab3e5c..000000000
--- a/browser/components/sessionstore/test/browser_459906.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 459906 **/
-
- waitForExplicitFinish();
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_459906_sample.html";
- let uniqueValue = "<b>Unique:</b> " + Date.now();
-
- var frameCount = 0;
- let tab = gBrowser.addTab(testURL);
- tab.linkedBrowser.addEventListener("load", function(aEvent) {
- // wait for all frames to load completely
- if (frameCount++ < 2)
- return;
- tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- let iframes = tab.linkedBrowser.contentWindow.frames;
- iframes[1].document.body.innerHTML = uniqueValue;
-
- frameCount = 0;
- let tab2 = gBrowser.duplicateTab(tab);
- tab2.linkedBrowser.addEventListener("load", function(aEvent) {
- // wait for all frames to load (and reload!) completely
- if (frameCount++ < 2)
- return;
- tab2.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- executeSoon(function() {
- let iframes = tab2.linkedBrowser.contentWindow.frames;
- if (iframes[1].document.body.innerHTML !== uniqueValue) {
- // Poll again the value, since we can't ensure to run
- // after SessionStore has injected innerHTML value.
- // See bug 521802.
- info("Polling for innerHTML value");
- setTimeout(arguments.callee, 100);
- return;
- }
-
- is(iframes[1].document.body.innerHTML, uniqueValue,
- "rich textarea's content correctly duplicated");
-
- let innerDomain = null;
- try {
- innerDomain = iframes[0].document.domain;
- }
- catch (ex) { /* throws for chrome: documents */ }
- is(innerDomain, "mochi.test", "XSS exploit prevented!");
-
- // clean up
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-
- finish();
- });
- }, true);
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_459906_empty.html b/browser/components/sessionstore/test/browser_459906_empty.html
deleted file mode 100644
index e01aaa339..000000000
--- a/browser/components/sessionstore/test/browser_459906_empty.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<title>Cross Domain File for bug 459906</title>
-
-cheers from localhost
diff --git a/browser/components/sessionstore/test/browser_459906_sample.html b/browser/components/sessionstore/test/browser_459906_sample.html
deleted file mode 100644
index 39b789776..000000000
--- a/browser/components/sessionstore/test/browser_459906_sample.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<!-- Testcase originally by David Bloom <bloom@google.com> -->
-
-<!DOCTYPE html>
-<title>Test for bug 459906</title>
-
-<body>
-<iframe src="data:text/html;charset=utf-8,not_on_localhost"></iframe>
-<iframe></iframe>
-
-<script type="application/javascript">
- var loadCount = 0;
- frames[0].addEventListener("DOMContentLoaded", handleLoad, false);
- frames[1].addEventListener("DOMContentLoaded", handleLoad, false);
- function handleLoad() {
- if (++loadCount < 2)
- return;
- frames[0].removeEventListener("DOMContentLoaded", handleLoad, false);
- frames[1].removeEventListener("DOMContentLoaded", handleLoad, false);
- frames[0].document.designMode = "on";
- frames[0].document.__defineGetter__("designMode", function() {
- // inject a cross domain file ...
- var documentInjected = false;
- document.getElementsByTagName("iframe")[0].onload =
- function() { documentInjected = true; };
- frames[0].location = "browser_459906_empty.html";
-
- // ... and ensure that it has time to load
- for (var c = 0; !documentInjected && c < 20; c++) {
- var r = new XMLHttpRequest();
- r.open("GET", location.href, false);
- r.overrideMimeType("text/plain");
- r.send(null);
- }
-
- return "on";
- });
-
- frames[1].document.designMode = "on";
- };
-</script>
-</body>
diff --git a/browser/components/sessionstore/test/browser_461634.js b/browser/components/sessionstore/test/browser_461634.js
deleted file mode 100644
index 01d3a4b0d..000000000
--- a/browser/components/sessionstore/test/browser_461634.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* 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/. */
-
-Cu.import("resource:///modules/sessionstore/SessionStore.jsm");
-
-function test() {
- /** Test for Bug 461634 **/
-
- waitForExplicitFinish();
-
- const REMEMBER = Date.now(), FORGET = Math.random();
- let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [
- { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER },
- { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER },
- ] }] };
- let remember_count = 2;
-
- function countByTitle(aClosedTabList, aTitle) {
- return aClosedTabList.filter(aData => aData.title == aTitle).length;
- }
-
- function testForError(aFunction) {
- try {
- aFunction();
- return false;
- }
- catch (ex) {
- return ex.name == "NS_ERROR_ILLEGAL_VALUE";
- }
- }
-
- // Open a window and add the above closed tab list.
- let newWin = openDialog(location, "", "chrome,all,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
- test_state.windows[0]._closedTabs.length);
- ss.setWindowState(newWin, JSON.stringify(test_state), true);
-
- let closedTabs = SessionStore.getClosedTabData(newWin, false);
-
- // Verify that non JSON serialized data is the same as JSON serialized data.
- is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
- "Non-serialized data is the same as serialized data")
-
- is(closedTabs.length, test_state.windows[0]._closedTabs.length,
- "Closed tab list has the expected length");
- is(countByTitle(closedTabs, FORGET),
- test_state.windows[0]._closedTabs.length - remember_count,
- "The correct amout of tabs are to be forgotten");
- is(countByTitle(closedTabs, REMEMBER), remember_count,
- "Everything is set up");
-
- // All of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE.
- ok(testForError(() => ss.forgetClosedTab({}, 0)),
- "Invalid window for forgetClosedTab throws");
- ok(testForError(() => ss.forgetClosedTab(newWin, -1)),
- "Invalid tab for forgetClosedTab throws");
- ok(testForError(() => ss.forgetClosedTab(newWin, test_state.windows[0]._closedTabs.length + 1)),
- "Invalid tab for forgetClosedTab throws");
-
- // Remove third tab, then first tab.
- ss.forgetClosedTab(newWin, 2);
- ss.forgetClosedTab(newWin, null);
-
- closedTabs = SessionStore.getClosedTabData(newWin, false);
-
- // Verify that non JSON serialized data is the same as JSON serialized data.
- is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
- "Non-serialized data is the same as serialized data")
-
- is(closedTabs.length, remember_count,
- "The correct amout of tabs was removed");
- is(countByTitle(closedTabs, FORGET), 0,
- "All tabs specifically forgotten were indeed removed");
- is(countByTitle(closedTabs, REMEMBER), remember_count,
- "... and tabs not specifically forgetten weren't");
-
- // Clean up.
- gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
- BrowserTestUtils.closeWindow(newWin).then(finish);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_461743.js b/browser/components/sessionstore/test/browser_461743.js
deleted file mode 100644
index 263fff5f2..000000000
--- a/browser/components/sessionstore/test/browser_461743.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 461743 **/
-
- waitForExplicitFinish();
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_461743_sample.html";
-
- let frameCount = 0;
- let tab = gBrowser.addTab(testURL);
- tab.linkedBrowser.addEventListener("load", function(aEvent) {
- // Wait for all frames to load completely.
- if (frameCount++ < 2)
- return;
- tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
- let tab2 = gBrowser.duplicateTab(tab);
- tab2.linkedBrowser.addEventListener("461743", function(aEvent) {
- tab2.linkedBrowser.removeEventListener("461743", arguments.callee, true);
- is(aEvent.data, "done", "XSS injection was attempted");
-
- executeSoon(function() {
- let iframes = tab2.linkedBrowser.contentWindow.frames;
- let innerHTML = iframes[1].document.body.innerHTML;
- isnot(innerHTML, Components.utils.reportError.toString(),
- "chrome access denied!");
-
- // Clean up.
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-
- finish();
- });
- }, true, true);
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_461743_sample.html b/browser/components/sessionstore/test/browser_461743_sample.html
deleted file mode 100644
index 80c9e612a..000000000
--- a/browser/components/sessionstore/test/browser_461743_sample.html
+++ /dev/null
@@ -1,56 +0,0 @@
-<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> -->
-
-<!DOCTYPE html>
-<title>Test for bug 461743</title>
-
-<body>
-<iframe src="data:text/html;charset=utf-8,empty"></iframe>
-<iframe></iframe>
-
-<script type="application/javascript">
- var chromeUrl = "chrome://global/content/mozilla.xhtml";
- var exploitUrl = "javascript:try { document.body.innerHTML = Components.utils.reportError; } catch (ex) { }";
-
- var loadCount = 0;
- frames[0].addEventListener("DOMContentLoaded", handleLoad, false);
- frames[1].addEventListener("DOMContentLoaded", handleLoad, false);
- function handleLoad() {
- if (++loadCount < 2)
- return;
- frames[0].removeEventListener("DOMContentLoaded", handleLoad, false);
- frames[1].removeEventListener("DOMContentLoaded", handleLoad, false);
-
- var flip = 0;
- MutationEvent.prototype.toString = function() {
- return flip++ == 0 ? chromeUrl : exploitUrl;
- };
-
- var href = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(frames[1].location), "href").get;
- var loadChrome = { handleEvent: href };
- var loadExploit = { handleEvent: href };
-
- function delay() {
- var xhr = new XMLHttpRequest();
- xhr.open("GET", location.href, false);
- xhr.send(null);
- }
- function done() {
- var event = new MessageEvent('461743', { bubbles: true, cancelable: false,
- data: "done", origin: location.href,
- source: window });
- document.dispatchEvent(event);
- frames[0].document.removeEventListener("DOMNodeInserted", loadChrome, true);
- frames[0].document.removeEventListener("DOMNodeInserted", delay, true);
- frames[0].document.removeEventListener("DOMNodeInserted", loadExploit, true);
- frames[0].document.removeEventListener("DOMNodeInserted", done, true);
- }
-
- frames[0].document.addEventListener("DOMNodeInserted", loadChrome, true);
- frames[0].document.addEventListener("DOMNodeInserted", delay, true);
- frames[0].document.addEventListener("DOMNodeInserted", loadExploit, true);
- frames[0].document.addEventListener("DOMNodeInserted", done, true);
-
- frames[0].document.designMode = "on";
- };
-</script>
-</body>
diff --git a/browser/components/sessionstore/test/browser_463205.js b/browser/components/sessionstore/test/browser_463205.js
deleted file mode 100644
index ad3f22794..000000000
--- a/browser/components/sessionstore/test/browser_463205.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_463205_sample.html";
-
-/**
- * Bug 463205 - Check URLs before restoring form data to make sure a malicious
- * website can't modify frame URLs and make us inject form data into the wrong
- * web pages.
- */
-add_task(function test_check_urls_before_restoring() {
- // Add a blank tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Restore form data with a valid URL.
- yield promiseTabState(tab, getState(URL));
-
- let value = yield getInputValue(browser, {id: "text"});
- is(value, "foobar", "value was restored");
-
- // Restore form data with an invalid URL.
- yield promiseTabState(tab, getState("http://example.com/"));
-
- value = yield getInputValue(browser, {id: "text"});
- is(value, "", "value was not restored");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-function getState(url) {
- return JSON.stringify({
- entries: [{url: URL}],
- formdata: {url: url, id: {text: "foobar"}}
- });
-}
diff --git a/browser/components/sessionstore/test/browser_463205_sample.html b/browser/components/sessionstore/test/browser_463205_sample.html
deleted file mode 100644
index 6591401b6..000000000
--- a/browser/components/sessionstore/test/browser_463205_sample.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<!DOCTYPE html>
-<meta charset="utf-8">
-<title>bug 463205</title>
-
-<body>
- <input type="text" id="text" />
-</body>
diff --git a/browser/components/sessionstore/test/browser_463206.js b/browser/components/sessionstore/test/browser_463206.js
deleted file mode 100644
index 99ee8373e..000000000
--- a/browser/components/sessionstore/test/browser_463206.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const TEST_URL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_463206_sample.html";
-
-add_task(function* () {
- // Add a new tab.
- let tab = gBrowser.addTab(TEST_URL);
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- // "Type in" some random values.
- yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- function typeText(aTextField, aValue) {
- aTextField.value = aValue;
-
- let event = aTextField.ownerDocument.createEvent("UIEvents");
- event.initUIEvent("input", true, true, aTextField.ownerGlobal, 0);
- aTextField.dispatchEvent(event);
- }
-
- typeText(content.document.getElementById("out1"), Date.now());
- typeText(content.document.getElementsByName("1|#out2")[0], Math.random());
- typeText(content.frames[0].frames[1].document.getElementById("in1"), new Date());
- });
-
- // Duplicate the tab.
- let tab2 = gBrowser.duplicateTab(tab);
- yield promiseTabRestored(tab2);
-
- // Query a few values from the top and its child frames.
- yield ContentTask.spawn(tab2.linkedBrowser, null, function* () {
- Assert.notEqual(content.document.getElementById("out1").value,
- content.frames[1].document.getElementById("out1").value,
- "text isn't reused for frames");
- Assert.notEqual(content.document.getElementsByName("1|#out2")[0].value,
- "", "text containing | and # is correctly restored");
- Assert.equal(content.frames[1].document.getElementById("out2").value,
- "", "id prefixes can't be faked");
- // Disabled for now, Bug 588077
- //Assert.equal(content.frames[0].frames[1].document.getElementById("in1").value,
- // "", "id prefixes aren't mixed up");
- Assert.equal(content.frames[1].frames[0].document.getElementById("in1").value,
- "", "id prefixes aren't mixed up");
- });
-
- // Cleanup.
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_463206_sample.html b/browser/components/sessionstore/test/browser_463206_sample.html
deleted file mode 100644
index 0d31f2906..000000000
--- a/browser/components/sessionstore/test/browser_463206_sample.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> -->
-
-<!DOCTYPE html>
-<meta charset="utf-8">
-<title>Test for bug 463206</title>
-
-<iframe src="data:text/html;charset=utf-8,<iframe></iframe><iframe%20src='data:text/html;charset=utf-8,<input%2520id=%2522in1%2522>'></iframe>"></iframe>
-<iframe src="data:text/html;charset=utf-8,<input%20id='out1'><input%20id='out2'><iframe%20src='data:text/html;charset=utf-8,<input%2520id=%2522in1%2522>'>"></iframe>
-
-<input id="out1">
-<input name="1|#out2">
diff --git a/browser/components/sessionstore/test/browser_464199.js b/browser/components/sessionstore/test/browser_464199.js
deleted file mode 100644
index 36f07832c..000000000
--- a/browser/components/sessionstore/test/browser_464199.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* 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/. */
-
-Components.utils.import("resource://gre/modules/ForgetAboutSite.jsm");
-
-function waitForClearHistory(aCallback) {
- let observer = {
- observe: function(aSubject, aTopic, aData) {
- Services.obs.removeObserver(this, "browser:purge-domain-data");
- setTimeout(aCallback, 0);
- }
- };
- Services.obs.addObserver(observer, "browser:purge-domain-data", false);
-}
-
-function test() {
- /** Test for Bug 464199 **/
-
- waitForExplicitFinish();
-
- const REMEMBER = Date.now(), FORGET = Math.random();
- let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [
- { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://www.example.org/" }] }, title: REMEMBER },
- { state: { entries: [{ url: "http://www.example.net/" },
- { url: "http://www.example.org/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://example.net/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://sub.example.net/" }] }, title: FORGET },
- { state: { entries: [{ url: "http://www.example.net:8080/" }] }, title: FORGET },
- { state: { entries: [{ url: "about:license" }] }, title: REMEMBER },
- { state: { entries: [{ url: "http://www.example.org/frameset",
- children: [
- { url: "http://www.example.org/frame" },
- { url: "http://www.example.org:8080/frame2" }
- ] }] }, title: REMEMBER },
- { state: { entries: [{ url: "http://www.example.org/frameset",
- children: [
- { url: "http://www.example.org/frame" },
- { url: "http://www.example.net/frame" }
- ] }] }, title: FORGET },
- { state: { entries: [{ url: "http://www.example.org/form",
- formdata: { id: { "url": "http://www.example.net/" } }
- }] }, title: REMEMBER },
- { state: { entries: [{ url: "http://www.example.org/form" }],
- extData: { "setTabValue": "http://example.net:80" } }, title: REMEMBER }
- ] }] };
- let remember_count = 5;
-
- function countByTitle(aClosedTabList, aTitle) {
- return aClosedTabList.filter(aData => aData.title == aTitle).length;
- }
-
- // open a window and add the above closed tab list
- let newWin = openDialog(location, "", "chrome,all,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
- test_state.windows[0]._closedTabs.length);
- ss.setWindowState(newWin, JSON.stringify(test_state), true);
-
- let closedTabs = JSON.parse(ss.getClosedTabData(newWin));
- is(closedTabs.length, test_state.windows[0]._closedTabs.length,
- "Closed tab list has the expected length");
- is(countByTitle(closedTabs, FORGET),
- test_state.windows[0]._closedTabs.length - remember_count,
- "The correct amout of tabs are to be forgotten");
- is(countByTitle(closedTabs, REMEMBER), remember_count,
- "Everything is set up.");
-
- ForgetAboutSite.removeDataFromDomain("example.net");
- waitForClearHistory(function() {
- closedTabs = JSON.parse(ss.getClosedTabData(newWin));
- is(closedTabs.length, remember_count,
- "The correct amout of tabs was removed");
- is(countByTitle(closedTabs, FORGET), 0,
- "All tabs to be forgotten were indeed removed");
- is(countByTitle(closedTabs, REMEMBER), remember_count,
- "... and tabs to be remembered weren't.");
-
- // clean up
- gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
- BrowserTestUtils.closeWindow(newWin).then(finish);
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_464620_a.html b/browser/components/sessionstore/test/browser_464620_a.html
deleted file mode 100644
index 1f03c92c7..000000000
--- a/browser/components/sessionstore/test/browser_464620_a.html
+++ /dev/null
@@ -1,54 +0,0 @@
-<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> -->
-
-<title>Test for bug 464620 (injection on input)</title>
-
-<iframe></iframe>
-<iframe onload="setup()"></iframe>
-
-<script>
- var targetUrl = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_464620_xd.html";
- var firstPass;
-
- function setup() {
- if (firstPass !== undefined)
- return;
- firstPass = frames[1].location.href == "about:blank";
- if (firstPass) {
- frames[0].location = 'data:text/html;charset=utf-8,<body onload="if (parent.firstPass) parent.step();"><input id="x" oninput="parent.xss()">XXX</body>';
- }
- frames[1].location = targetUrl;
- }
-
- function step() {
- var x = frames[0].document.getElementById("x");
- if (x.value == "")
- x.value = "ready";
- x.style.display = "none";
- frames[0].document.designMode = "on";
- }
-
- function xss() {
- step();
-
- var documentInjected = false;
- document.getElementsByTagName("iframe")[0].onload =
- function() { documentInjected = true; };
- frames[0].location = targetUrl;
-
- for (var c = 0; !documentInjected && c < 20; c++) {
- var r = new XMLHttpRequest();
- r.open("GET", location.href, false);
- r.overrideMimeType("text/plain");
- r.send(null);
- }
- document.getElementById("state").textContent = "done";
-
- var event = new MessageEvent('464620_a', { bubbles: true, cancelable: false,
- data: "done", origin: location.href,
- source: window });
- document.dispatchEvent(event);
- }
-</script>
-
-<p id="state">pending</p>
diff --git a/browser/components/sessionstore/test/browser_464620_a.js b/browser/components/sessionstore/test/browser_464620_a.js
deleted file mode 100644
index 9756fa703..000000000
--- a/browser/components/sessionstore/test/browser_464620_a.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 464620 (injection on input) **/
-
- waitForExplicitFinish();
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_464620_a.html";
-
- var frameCount = 0;
- let tab = gBrowser.addTab(testURL);
- tab.linkedBrowser.addEventListener("load", function(aEvent) {
- // wait for all frames to load completely
- if (frameCount++ < 4)
- return;
- this.removeEventListener("load", arguments.callee, true);
-
- executeSoon(function() {
- frameCount = 0;
- let tab2 = gBrowser.duplicateTab(tab);
- tab2.linkedBrowser.addEventListener("464620_a", function(aEvent) {
- tab2.linkedBrowser.removeEventListener("464620_a", arguments.callee, true);
- is(aEvent.data, "done", "XSS injection was attempted");
-
- // let form restoration complete and take into account the
- // setTimeout(..., 0) in sss_restoreDocument_proxy
- executeSoon(function() {
- setTimeout(function() {
- let win = tab2.linkedBrowser.contentWindow;
- isnot(win.frames[0].document.location, testURL,
- "cross domain document was loaded");
- ok(!/XXX/.test(win.frames[0].document.body.innerHTML),
- "no content was injected");
-
- // clean up
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-
- finish();
- }, 0);
- });
- }, true, true);
- });
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_464620_b.html b/browser/components/sessionstore/test/browser_464620_b.html
deleted file mode 100644
index 8c86d2152..000000000
--- a/browser/components/sessionstore/test/browser_464620_b.html
+++ /dev/null
@@ -1,58 +0,0 @@
-<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> -->
-
-<title>Test for bug 464620 (injection on DOM node insertion)</title>
-
-<iframe></iframe>
-<iframe></iframe>
-<iframe onload="setup()"></iframe>
-
-<script>
- var targetUrl = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_464620_xd.html";
- var firstPass;
-
- function setup() {
- if (firstPass !== undefined)
- return;
- firstPass = frames[2].location.href == "about:blank";
- if (firstPass) {
- frames[0].location = 'data:text/html;charset=utf-8,<body onload="parent.step()">a</body>';
- frames[1].location = 'data:text/html;charset=utf-8,<body onload="document.designMode=\'on\';">XXX</body>';
- }
- frames[2].location = targetUrl;
- }
-
- function step() {
- frames[0].document.designMode = "on";
- if (firstPass)
- return;
-
- var body = frames[0].document.body;
- body.addEventListener("DOMNodeInserted", function() {
- body.removeEventListener("DOMNodeInserted", arguments.callee, true);
- xss();
- }, true);
- }
-
- function xss() {
- var documentInjected = false;
- document.getElementsByTagName("iframe")[1].onload =
- function() { documentInjected = true; };
- frames[1].location = targetUrl;
-
- for (var c = 0; !documentInjected && c < 20; c++) {
- var r = new XMLHttpRequest();
- r.open("GET", location.href, false);
- r.overrideMimeType("text/plain");
- r.send(null);
- }
- document.getElementById("state").textContent = "done";
-
- var event = new MessageEvent('464620_b', { bubbles: true, cancelable: false,
- data: "done", origin: location.href,
- source: window });
- document.dispatchEvent(event);
- }
-</script>
-
-<p id="state">pending</p>
diff --git a/browser/components/sessionstore/test/browser_464620_b.js b/browser/components/sessionstore/test/browser_464620_b.js
deleted file mode 100644
index cf23aa460..000000000
--- a/browser/components/sessionstore/test/browser_464620_b.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 464620 (injection on DOM node insertion) **/
-
- waitForExplicitFinish();
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_464620_b.html";
-
- var frameCount = 0;
- let tab = gBrowser.addTab(testURL);
- tab.linkedBrowser.addEventListener("load", function(aEvent) {
- // wait for all frames to load completely
- if (frameCount++ < 6)
- return;
- this.removeEventListener("load", arguments.callee, true);
-
- executeSoon(function() {
- frameCount = 0;
- let tab2 = gBrowser.duplicateTab(tab);
- tab2.linkedBrowser.addEventListener("464620_b", function(aEvent) {
- tab2.linkedBrowser.removeEventListener("464620_b", arguments.callee, true);
- is(aEvent.data, "done", "XSS injection was attempted");
-
- // let form restoration complete and take into account the
- // setTimeout(..., 0) in sss_restoreDocument_proxy
- executeSoon(function() {
- setTimeout(function() {
- let win = tab2.linkedBrowser.contentWindow;
- isnot(win.frames[1].document.location, testURL,
- "cross domain document was loaded");
- ok(!/XXX/.test(win.frames[1].document.body.innerHTML),
- "no content was injected");
-
- // clean up
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-
- finish();
- }, 0);
- });
- }, true, true);
- });
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_464620_xd.html b/browser/components/sessionstore/test/browser_464620_xd.html
deleted file mode 100644
index 9ec51c4c7..000000000
--- a/browser/components/sessionstore/test/browser_464620_xd.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<title>Cross Document File for bug 464620</title>
-
-<body onload="document.designMode='on';" bgcolor="red">
- This document is editable.
-</body>
diff --git a/browser/components/sessionstore/test/browser_465215.js b/browser/components/sessionstore/test/browser_465215.js
deleted file mode 100644
index 3a0a7b9c5..000000000
--- a/browser/components/sessionstore/test/browser_465215.js
+++ /dev/null
@@ -1,28 +0,0 @@
-"use strict";
-
-var uniqueName = "bug 465215";
-var uniqueValue1 = "as good as unique: " + Date.now();
-var uniqueValue2 = "as good as unique: " + Math.random();
-
-add_task(function* () {
- // set a unique value on a new, blank tab
- let tab1 = gBrowser.addTab("about:blank");
- yield promiseBrowserLoaded(tab1.linkedBrowser);
- ss.setTabValue(tab1, uniqueName, uniqueValue1);
-
- // duplicate the tab with that value
- let tab2 = ss.duplicateTab(window, tab1);
- yield promiseTabRestored(tab2);
- is(ss.getTabValue(tab2, uniqueName), uniqueValue1, "tab value was duplicated");
-
- ss.setTabValue(tab2, uniqueName, uniqueValue2);
- isnot(ss.getTabValue(tab1, uniqueName), uniqueValue2, "tab values aren't sync'd");
-
- // overwrite the tab with the value which should remove it
- yield promiseTabState(tab1, {entries: []});
- is(ss.getTabValue(tab1, uniqueName), "", "tab value was cleared");
-
- // clean up
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab1);
-});
diff --git a/browser/components/sessionstore/test/browser_465223.js b/browser/components/sessionstore/test/browser_465223.js
deleted file mode 100644
index 04f888b30..000000000
--- a/browser/components/sessionstore/test/browser_465223.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 465223 **/
-
- // test setup
- waitForExplicitFinish();
-
- let uniqueKey1 = "bug 465223.1";
- let uniqueKey2 = "bug 465223.2";
- let uniqueValue1 = "unik" + Date.now();
- let uniqueValue2 = "pi != " + Math.random();
-
- // open a window and set a value on it
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- ss.setWindowValue(newWin, uniqueKey1, uniqueValue1);
-
- let newState = { windows: [{ tabs:[{ entries: [] }], extData: {} }] };
- newState.windows[0].extData[uniqueKey2] = uniqueValue2;
- ss.setWindowState(newWin, JSON.stringify(newState), false);
-
- is(newWin.gBrowser.tabs.length, 2,
- "original tab wasn't overwritten");
- is(ss.getWindowValue(newWin, uniqueKey1), uniqueValue1,
- "window value wasn't overwritten when the tabs weren't");
- is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue2,
- "new window value was correctly added");
-
- newState.windows[0].extData[uniqueKey2] = uniqueValue1;
- ss.setWindowState(newWin, JSON.stringify(newState), true);
-
- is(newWin.gBrowser.tabs.length, 1,
- "original tabs were overwritten");
- is(ss.getWindowValue(newWin, uniqueKey1), "",
- "window value was cleared");
- is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue1,
- "window value was correctly overwritten");
-
- // clean up
- BrowserTestUtils.closeWindow(newWin).then(finish);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_466937.js b/browser/components/sessionstore/test/browser_466937.js
deleted file mode 100644
index 0a07caa0c..000000000
--- a/browser/components/sessionstore/test/browser_466937.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_466937_sample.html";
-
-/**
- * Bug 466937 - Prevent file stealing with sessionstore.
- */
-add_task(function test_prevent_file_stealing() {
- // Add a tab with some file input fields.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Generate a path to a 'secret' file.
- let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
- file.append("466937_test.file");
- file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666);
- let testPath = file.path;
-
- // Fill in form values.
- yield setInputValue(browser, {id: "reverse_thief", value: "/home/user/secret2"});
- yield setInputValue(browser, {id: "bystander", value: testPath});
-
- // Duplicate and check form values.
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- let thief = yield getInputValue(browser2, {id: "thief"});
- is(thief, "", "file path wasn't set to text field value");
- let reverse_thief = yield getInputValue(browser2, {id: "reverse_thief"});
- is(reverse_thief, "", "text field value wasn't set to full file path");
- let bystander = yield getInputValue(browser2, {id: "bystander"});
- is(bystander, testPath, "normal case: file path was correctly preserved");
-
- // Cleanup.
- gBrowser.removeTab(tab);
- gBrowser.removeTab(tab2);
-});
diff --git a/browser/components/sessionstore/test/browser_466937_sample.html b/browser/components/sessionstore/test/browser_466937_sample.html
deleted file mode 100644
index 1d46c649a..000000000
--- a/browser/components/sessionstore/test/browser_466937_sample.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> -->
-
-<!DOCTYPE html>
-<meta charset="utf-8">
-<title>Test for bug 466937</title>
-
-<input id="thief" value="/home/user/secret">
-<input type="file" id="reverse_thief">
-<input type="file" id="bystander">
-
-<script>
- window.addEventListener("DOMContentLoaded", function() {
- window.removeEventListener("DOMContentLoaded", arguments.callee, false);
- if (!document.location.hash) {
- document.location.hash = "#ready";
- }
- else {
- document.getElementById("thief").type = "file";
- document.getElementById("reverse_thief").type = "text";
- }
- }, false);
-</script>
diff --git a/browser/components/sessionstore/test/browser_467409-backslashplosion.js b/browser/components/sessionstore/test/browser_467409-backslashplosion.js
deleted file mode 100644
index 0e990c614..000000000
--- a/browser/components/sessionstore/test/browser_467409-backslashplosion.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Test Summary:
-// 1. Open about:sessionrestore where formdata is a JS object, not a string
-// 1a. Check that #sessionData on the page is readable after JSON.parse (skipped, checking formdata is sufficient)
-// 1b. Check that there are no backslashes in the formdata
-// 1c. Check that formdata doesn't require JSON.parse
-//
-// 2. Use the current state (currently about:sessionrestore with data) and then open that in a new instance of about:sessionrestore
-// 2a. Check that there are no backslashes in the formdata
-// 2b. Check that formdata doesn't require JSON.parse
-//
-// 3. [backwards compat] Use a stringified state as formdata when opening about:sessionrestore
-// 3a. Make sure there are nodes in the tree on about:sessionrestore (skipped, checking formdata is sufficient)
-// 3b. Check that there are no backslashes in the formdata
-// 3c. Check that formdata doesn't require JSON.parse
-
-const CRASH_STATE = {windows: [{tabs: [{entries: [{url: "about:mozilla" }]}]}]};
-const STATE = createEntries(CRASH_STATE);
-const STATE2 = createEntries({windows: [{tabs: [STATE]}]});
-const STATE3 = createEntries(JSON.stringify(CRASH_STATE));
-
-function createEntries(sessionData) {
- return {
- entries: [{url: "about:sessionrestore"}],
- formdata: {id: {sessionData: sessionData}, url: "about:sessionrestore"}
- };
-}
-
-add_task(function test_nested_about_sessionrestore() {
- // Prepare a blank tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // test 1
- yield promiseTabState(tab, STATE);
- yield checkState("test1", tab);
-
- // test 2
- yield promiseTabState(tab, STATE2);
- yield checkState("test2", tab);
-
- // test 3
- yield promiseTabState(tab, STATE3);
- yield checkState("test3", tab);
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-function* checkState(prefix, tab) {
- // Flush and query tab state.
- yield TabStateFlusher.flush(tab.linkedBrowser);
- let {formdata} = JSON.parse(ss.getTabState(tab));
-
- ok(formdata.id["sessionData"], prefix + ": we have form data for about:sessionrestore");
-
- let sessionData_raw = JSON.stringify(formdata.id["sessionData"]);
- ok(!/\\/.test(sessionData_raw), prefix + ": #sessionData contains no backslashes");
- info(sessionData_raw);
-
- let gotError = false;
- try {
- JSON.parse(formdata.id["sessionData"]);
- } catch (e) {
- info(prefix + ": got error: " + e);
- gotError = true;
- }
- ok(gotError, prefix + ": attempting to JSON.parse form data threw error");
-}
diff --git a/browser/components/sessionstore/test/browser_477657.js b/browser/components/sessionstore/test/browser_477657.js
deleted file mode 100644
index 1a8ee3412..000000000
--- a/browser/components/sessionstore/test/browser_477657.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 477657 **/
- waitForExplicitFinish();
-
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- let newState = { windows: [{
- tabs: [{ entries: [] }],
- _closedTabs: [{
- state: { entries: [{ url: "about:" }]},
- title: "About:"
- }],
- sizemode: "maximized"
- }] };
-
- let uniqueKey = "bug 477657";
- let uniqueValue = "unik" + Date.now();
-
- ss.setWindowValue(newWin, uniqueKey, uniqueValue);
- is(ss.getWindowValue(newWin, uniqueKey), uniqueValue,
- "window value was set before the window was overwritten");
- ss.setWindowState(newWin, JSON.stringify(newState), true);
-
- // use newWin.setTimeout(..., 0) to mirror sss_restoreWindowFeatures
- newWin.setTimeout(function() {
- is(ss.getWindowValue(newWin, uniqueKey), "",
- "window value was implicitly cleared");
-
- is(newWin.windowState, newWin.STATE_MAXIMIZED,
- "the window was maximized");
-
- is(JSON.parse(ss.getClosedTabData(newWin)).length, 1,
- "the closed tab was added before the window was overwritten");
- delete newState.windows[0]._closedTabs;
- delete newState.windows[0].sizemode;
- ss.setWindowState(newWin, JSON.stringify(newState), true);
-
- newWin.setTimeout(function() {
- is(JSON.parse(ss.getClosedTabData(newWin)).length, 0,
- "closed tabs were implicitly cleared");
-
- is(newWin.windowState, newWin.STATE_MAXIMIZED,
- "the window remains maximized");
- newState.windows[0].sizemode = "normal";
- ss.setWindowState(newWin, JSON.stringify(newState), true);
-
- newWin.setTimeout(function() {
- isnot(newWin.windowState, newWin.STATE_MAXIMIZED,
- "the window was explicitly unmaximized");
-
- BrowserTestUtils.closeWindow(newWin).then(finish);
- }, 0);
- }, 0);
- }, 0);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_480893.js b/browser/components/sessionstore/test/browser_480893.js
deleted file mode 100644
index e3ddb39b7..000000000
--- a/browser/components/sessionstore/test/browser_480893.js
+++ /dev/null
@@ -1,47 +0,0 @@
-"use strict";
-
-/**
- * Tests that we get sent to the right page when the user clicks
- * the "Close" button in about:sessionrestore
- */
-add_task(function*() {
- yield SpecialPowers.pushPrefEnv({
- "set": [
- ["browser.startup.page", 0],
- ]
- });
-
- let tab = gBrowser.addTab("about:sessionrestore");
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- yield BrowserTestUtils.browserLoaded(browser, false, "about:sessionrestore");
-
- let doc = browser.contentDocument;
-
- // Click on the "Close" button after about:sessionrestore is loaded.
- doc.getElementById("errorCancel").click();
-
- yield BrowserTestUtils.browserLoaded(browser, false, "about:blank");
-
- // Test that starting a new session loads the homepage (set to http://mochi.test:8888)
- // if Firefox is configured to display a homepage at startup (browser.startup.page = 1)
- let homepage = "http://mochi.test:8888/";
- yield SpecialPowers.pushPrefEnv({
- "set": [
- ["browser.startup.homepage", homepage],
- ["browser.startup.page", 1],
- ]
- });
-
- browser.loadURI("about:sessionrestore");
- yield BrowserTestUtils.browserLoaded(browser, false, "about:sessionrestore");
- doc = browser.contentDocument;
-
- // Click on the "Close" button after about:sessionrestore is loaded.
- doc.getElementById("errorCancel").click();
- yield BrowserTestUtils.browserLoaded(browser);
-
- is(browser.currentURI.spec, homepage, "loaded page is the homepage");
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_485482.js b/browser/components/sessionstore/test/browser_485482.js
deleted file mode 100644
index 68ec9941b..000000000
--- a/browser/components/sessionstore/test/browser_485482.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_485482_sample.html";
-
-/**
- * Bug 485482 - Make sure that we produce valid XPath expressions even for very
- * weird HTML documents.
- */
-add_task(function test_xpath_exp_for_strange_documents() {
- // Load a page with weird tag names.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Fill in some values.
- let uniqueValue = Math.random();
- yield setInputValue(browser, {selector: "input[type=text]", value: uniqueValue});
- yield setInputChecked(browser, {selector: "input[type=checkbox]", checked: true});
-
- // Duplicate the tab.
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- // Check that we generated valid XPath expressions to restore form values.
- let text = yield getInputValue(browser2, {selector: "input[type=text]"});
- is(text, uniqueValue, "generated XPath expression was valid");
- let checkbox = yield getInputChecked(browser2, {selector: "input[type=checkbox]"});
- ok(checkbox, "generated XPath expression was valid");
-
- // Cleanup.
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_485482_sample.html b/browser/components/sessionstore/test/browser_485482_sample.html
deleted file mode 100644
index c2097b593..000000000
--- a/browser/components/sessionstore/test/browser_485482_sample.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<title>Test for bug 485482</title>
-
-<bad=name>
- <input type="text">
-</bad=name>
-
-<worse=name>
- <l0c@l+na~e"'§>
- <input type="checkbox" name="check"> Check
- </l0c@l+na~e"'§>
-</worse=name>
diff --git a/browser/components/sessionstore/test/browser_485563.js b/browser/components/sessionstore/test/browser_485563.js
deleted file mode 100644
index f4e6b31cc..000000000
--- a/browser/components/sessionstore/test/browser_485563.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 485563 **/
-
- waitForExplicitFinish();
-
- let uniqueValue = Math.random() + "\u2028Second line\u2029Second paragraph\u2027";
-
- let tab = gBrowser.addTab();
- promiseBrowserLoaded(tab.linkedBrowser).then(() => {
- ss.setTabValue(tab, "bug485563", uniqueValue);
- let tabState = JSON.parse(ss.getTabState(tab));
- is(tabState.extData["bug485563"], uniqueValue,
- "unicode line separator wasn't over-encoded");
- ss.deleteTabValue(tab, "bug485563");
- ss.setTabState(tab, JSON.stringify(tabState));
- is(ss.getTabValue(tab, "bug485563"), uniqueValue,
- "unicode line separator was correctly preserved");
-
- gBrowser.removeTab(tab);
- finish();
- });
-}
diff --git a/browser/components/sessionstore/test/browser_490040.js b/browser/components/sessionstore/test/browser_490040.js
deleted file mode 100644
index bc680c32f..000000000
--- a/browser/components/sessionstore/test/browser_490040.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-// Only windows with open tabs are restorable. Windows where a lone tab is
-// detached may have _closedTabs, but is left with just an empty tab.
-const STATES = [{
- shouldBeAdded: true,
- windowState: {
- windows: [{
- tabs: [{ entries: [{ url: "http://example.com", title: "example.com" }] }],
- selected: 1,
- _closedTabs: []
- }]
- }
- }, {
- shouldBeAdded: false,
- windowState: {
- windows: [{
- tabs: [{ entries: [] }],
- _closedTabs: []
- }]
- }
- }, {
- shouldBeAdded: false,
- windowState: {
- windows: [{
- tabs: [{ entries: [] }],
- _closedTabs: [{ state: { entries: [{ url: "http://example.com", index: 1 }] } }]
- }]
- }
- }, {
- shouldBeAdded: false,
- windowState: {
- windows: [{
- tabs: [{ entries: [] }],
- _closedTabs: [],
- extData: { keyname: "pi != " + Math.random() }
- }]
- }
- }];
-
-add_task(function* test_bug_490040() {
- for (let state of STATES) {
- // Ensure we can store the window if needed.
- let startingClosedWindowCount = ss.getClosedWindowCount();
- yield pushPrefs(["browser.sessionstore.max_windows_undo",
- startingClosedWindowCount + 1]);
-
- let curClosedWindowCount = ss.getClosedWindowCount();
- let win = yield BrowserTestUtils.openNewBrowserWindow();
-
- ss.setWindowState(win, JSON.stringify(state.windowState), true);
- if (state.windowState.windows[0].tabs.length) {
- yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
- }
-
- yield BrowserTestUtils.closeWindow(win);
-
- is(ss.getClosedWindowCount(),
- curClosedWindowCount + (state.shouldBeAdded ? 1 : 0),
- "That window should " + (state.shouldBeAdded ? "" : "not ") +
- "be restorable");
- }
-});
diff --git a/browser/components/sessionstore/test/browser_491168.js b/browser/components/sessionstore/test/browser_491168.js
deleted file mode 100644
index ae66afe77..000000000
--- a/browser/components/sessionstore/test/browser_491168.js
+++ /dev/null
@@ -1,42 +0,0 @@
-"use strict";
-
-const REFERRER1 = "http://example.org/?" + Date.now();
-const REFERRER2 = "http://example.org/?" + Math.random();
-
-add_task(function* () {
- function* checkDocumentReferrer(referrer, msg) {
- yield ContentTask.spawn(gBrowser.selectedBrowser, { referrer, msg }, function* (args) {
- Assert.equal(content.document.referrer, args.referrer, args.msg);
- });
- }
-
- // Add a new tab.
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Load a new URI with a specific referrer.
- let referrerURI = Services.io.newURI(REFERRER1, null, null);
- browser.loadURI("http://example.org", referrerURI, null);
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
- let tabState = JSON.parse(ss.getTabState(tab));
- is(tabState.entries[0].referrer, REFERRER1,
- "Referrer retrieved via getTabState matches referrer set via loadURI.");
-
- tabState.entries[0].referrer = REFERRER2;
- yield promiseTabState(tab, tabState);
-
- yield checkDocumentReferrer(REFERRER2,
- "document.referrer matches referrer set via setTabState.");
- gBrowser.removeCurrentTab();
-
- // Restore the closed tab.
- tab = ss.undoCloseTab(window, 0);
- yield promiseTabRestored(tab);
-
- yield checkDocumentReferrer(REFERRER2,
- "document.referrer is still correct after closing and reopening the tab.");
- gBrowser.removeCurrentTab();
-});
diff --git a/browser/components/sessionstore/test/browser_491577.js b/browser/components/sessionstore/test/browser_491577.js
deleted file mode 100644
index 0e088d702..000000000
--- a/browser/components/sessionstore/test/browser_491577.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 491577 **/
-
- // test setup
- waitForExplicitFinish();
-
- const REMEMBER = Date.now(), FORGET = Math.random();
- let test_state = {
- windows: [ { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 } ],
- _closedWindows : [
- // _closedWindows[0]
- {
- tabs: [
- { entries: [{ url: "http://example.com/", title: "title" }] },
- { entries: [{ url: "http://mozilla.org/", title: "title" }] }
- ],
- selected: 2,
- title: FORGET,
- _closedTabs: []
- },
- // _closedWindows[1]
- {
- tabs: [
- { entries: [{ url: "http://mozilla.org/", title: "title" }] },
- { entries: [{ url: "http://example.com/", title: "title" }] },
- { entries: [{ url: "http://mozilla.org/", title: "title" }] },
- ],
- selected: 3,
- title: REMEMBER,
- _closedTabs: []
- },
- // _closedWindows[2]
- {
- tabs: [
- { entries: [{ url: "http://example.com/", title: "title" }] }
- ],
- selected: 1,
- title: FORGET,
- _closedTabs: [
- {
- state: {
- entries: [
- { url: "http://mozilla.org/", title: "title" },
- { url: "http://mozilla.org/again", title: "title" }
- ]
- },
- pos: 1,
- title: "title"
- },
- {
- state: {
- entries: [
- { url: "http://example.com", title: "title" }
- ]
- },
- title: "title"
- }
- ]
- }
- ]
- };
- let remember_count = 1;
-
- function countByTitle(aClosedWindowList, aTitle) {
- return aClosedWindowList.filter(aData => aData.title == aTitle).length;
- }
-
- function testForError(aFunction) {
- try {
- aFunction();
- return false;
- }
- catch (ex) {
- return ex.name == "NS_ERROR_ILLEGAL_VALUE";
- }
- }
-
- // open a window and add the above closed window list
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- gPrefService.setIntPref("browser.sessionstore.max_windows_undo",
- test_state._closedWindows.length);
- ss.setWindowState(newWin, JSON.stringify(test_state), true);
-
- let closedWindows = JSON.parse(ss.getClosedWindowData());
- is(closedWindows.length, test_state._closedWindows.length,
- "Closed window list has the expected length");
- is(countByTitle(closedWindows, FORGET),
- test_state._closedWindows.length - remember_count,
- "The correct amount of windows are to be forgotten");
- is(countByTitle(closedWindows, REMEMBER), remember_count,
- "Everything is set up.");
-
- // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE
- ok(testForError(() => ss.forgetClosedWindow(-1)),
- "Invalid window for forgetClosedWindow throws");
- ok(testForError(() => ss.forgetClosedWindow(test_state._closedWindows.length + 1)),
- "Invalid window for forgetClosedWindow throws");
-
- // Remove third window, then first window
- ss.forgetClosedWindow(2);
- ss.forgetClosedWindow(null);
-
- closedWindows = JSON.parse(ss.getClosedWindowData());
- is(closedWindows.length, remember_count,
- "The correct amount of windows were removed");
- is(countByTitle(closedWindows, FORGET), 0,
- "All windows specifically forgotten were indeed removed");
- is(countByTitle(closedWindows, REMEMBER), remember_count,
- "... and windows not specifically forgetten weren't.");
-
- // clean up
- gPrefService.clearUserPref("browser.sessionstore.max_windows_undo");
- BrowserTestUtils.closeWindow(newWin).then(finish);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_495495.js b/browser/components/sessionstore/test/browser_495495.js
deleted file mode 100644
index 658f81c20..000000000
--- a/browser/components/sessionstore/test/browser_495495.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 495495 **/
-
- waitForExplicitFinish();
-
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no,toolbar=yes");
- promiseWindowLoaded(newWin).then(() => {
- let state1 = ss.getWindowState(newWin);
- BrowserTestUtils.closeWindow(newWin).then(() => {
-
- newWin = openDialog(location, "_blank",
- "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar=no,location,personal,directories,dialog=no");
- promiseWindowLoaded(newWin).then(() => {
- let state2 = ss.getWindowState(newWin);
-
- function testState(state, expected, callback) {
- let win = openDialog(location, "_blank", "chrome,all,dialog=no");
- promiseWindowLoaded(win).then(() => {
-
- is(win.gURLBar.readOnly, false,
- "URL bar should not be read-only before setting the state");
- is(win.gURLBar.getAttribute("enablehistory"), "true",
- "URL bar autocomplete should be enabled before setting the state");
- ss.setWindowState(win, state, true);
- is(win.gURLBar.readOnly, expected.readOnly,
- "URL bar read-only state should be restored correctly");
- is(win.gURLBar.getAttribute("enablehistory"), expected.enablehistory,
- "URL bar autocomplete state should be restored correctly");
-
- BrowserTestUtils.closeWindow(win).then(callback);
- });
- }
-
- BrowserTestUtils.closeWindow(newWin).then(() => {
- testState(state1, {readOnly: false, enablehistory: "true"}, function() {
- testState(state2, {readOnly: true, enablehistory: "false"}, finish);
- });
- });
- });
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_500328.js b/browser/components/sessionstore/test/browser_500328.js
deleted file mode 100644
index 44650ef8b..000000000
--- a/browser/components/sessionstore/test/browser_500328.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/* 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/. */
-
-let checkState = Task.async(function*(browser) {
- // Go back and then forward, and make sure that the state objects received
- // from the popState event are as we expect them to be.
- //
- // We also add a node to the document's body when after going back and make
- // sure it's still there after we go forward -- this is to test that the two
- // history entries correspond to the same document.
-
- let deferred = {};
- deferred.promise = new Promise(resolve => deferred.resolve = resolve);
-
- let popStateCount = 0;
-
- browser.addEventListener("popstate", function(aEvent) {
- if (popStateCount == 0) {
- popStateCount++;
-
- ok(aEvent.state, "Event should have a state property.");
-
- ContentTask.spawn(browser, null, function() {
- is(content.testState, "foo",
- "testState after going back");
- is(JSON.stringify(content.history.state), JSON.stringify({obj1:1}),
- "first popstate object.");
-
- // Add a node with id "new-elem" to the document.
- let doc = content.document;
- ok(!doc.getElementById("new-elem"),
- "doc shouldn't contain new-elem before we add it.");
- let elem = doc.createElement("div");
- elem.id = "new-elem";
- doc.body.appendChild(elem);
- }).then(() => {
- browser.goForward();
- });
- } else if (popStateCount == 1) {
- popStateCount++;
- // When content fires a PopStateEvent and we observe it from a chrome event
- // listener (as we do here, and, thankfully, nowhere else in the tree), the
- // state object will be a cross-compartment wrapper to an object that was
- // deserialized in the content scope. And in this case, since RegExps are
- // not currently Xrayable (see bug 1014991), trying to pull |obj3| (a RegExp)
- // off of an Xrayed Object won't work. So we need to waive.
- ContentTask.spawn(browser, aEvent.state, function(state) {
- Assert.equal(Cu.waiveXrays(state).obj3.toString(),
- "/^a$/", "second popstate object.");
-
- // Make sure that the new-elem node is present in the document. If it's
- // not, then this history entry has a different doc identifier than the
- // previous entry, which is bad.
- let doc = content.document;
- let newElem = doc.getElementById("new-elem");
- ok(newElem, "doc should contain new-elem.");
- newElem.parentNode.removeChild(newElem);
- ok(!doc.getElementById("new-elem"), "new-elem should be removed.");
- }).then(() => {
- browser.removeEventListener("popstate", arguments.callee, true);
- deferred.resolve();
- });
- }
- });
-
- // Set some state in the page's window. When we go back(), the page should
- // be retrieved from bfcache, and this state should still be there.
- yield ContentTask.spawn(browser, null, function() {
- content.testState = "foo";
- });
-
- // Now go back. This should trigger the popstate event handler above.
- browser.goBack();
-
- yield deferred.promise;
-});
-
-add_task(function* test() {
- // Tests session restore functionality of history.pushState and
- // history.replaceState(). (Bug 500328)
-
- // We open a new blank window, let it load, and then load in
- // http://example.com. We need to load the blank window first, otherwise the
- // docshell gets confused and doesn't have a current history entry.
- let state;
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
- BrowserTestUtils.loadURI(browser, "http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
-
- // After these push/replaceState calls, the window should have three
- // history entries:
- // testURL (state object: null) <-- oldest
- // testURL (state object: {obj1:1})
- // testURL?page2 (state object: {obj3:/^a$/}) <-- newest
- function contentTest() {
- let history = content.window.history;
- history.pushState({obj1:1}, "title-obj1");
- history.pushState({obj2:2}, "title-obj2", "?page2");
- history.replaceState({obj3:/^a$/}, "title-obj3");
- }
- yield ContentTask.spawn(browser, null, contentTest);
- yield TabStateFlusher.flush(browser);
-
- state = ss.getTabState(gBrowser.getTabForBrowser(browser));
- });
-
- // Restore the state into a new tab. Things don't work well when we
- // restore into the old tab, but that's not a real use case anyway.
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
- let tab2 = gBrowser.getTabForBrowser(browser);
-
- let tabRestoredPromise = promiseTabRestored(tab2);
- ss.setTabState(tab2, state, true);
-
- // Run checkState() once the tab finishes loading its restored state.
- yield tabRestoredPromise;
- yield checkState(browser);
- });
-});
diff --git a/browser/components/sessionstore/test/browser_506482.js b/browser/components/sessionstore/test/browser_506482.js
deleted file mode 100644
index 6e5bd83bd..000000000
--- a/browser/components/sessionstore/test/browser_506482.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 506482 **/
-
- // test setup
- waitForExplicitFinish();
-
- // read the sessionstore.js mtime (picked from browser_248970_a.js)
- let profilePath = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties).
- get("ProfD", Ci.nsIFile);
- function getSessionstoreFile() {
- let sessionStoreJS = profilePath.clone();
- sessionStoreJS.append("sessionstore.js");
- return sessionStoreJS;
- }
- function getSessionstorejsModificationTime() {
- let file = getSessionstoreFile();
- if (file.exists())
- return file.lastModifiedTime;
- else
- return -1;
- }
-
- // delete existing sessionstore.js, to make sure we're not reading
- // the mtime of an old one initially.
- let sessionStoreJS = getSessionstoreFile();
- if (sessionStoreJS.exists())
- sessionStoreJS.remove(false);
-
- // test content URL
- const TEST_URL = "data:text/html;charset=utf-8,"
- + "<body style='width: 100000px; height: 100000px;'><p>top</p></body>"
-
- // preferences that we use
- const PREF_INTERVAL = "browser.sessionstore.interval";
-
- // make sure sessionstore.js is saved ASAP on all events
- gPrefService.setIntPref(PREF_INTERVAL, 0);
-
- // get the initial sessionstore.js mtime (-1 if it doesn't exist yet)
- let mtime0 = getSessionstorejsModificationTime();
-
- // create and select a first tab
- let tab = gBrowser.addTab(TEST_URL);
- promiseBrowserLoaded(tab.linkedBrowser).then(() => {
- // step1: the above has triggered some saveStateDelayed(), sleep until
- // it's done, and get the initial sessionstore.js mtime
- setTimeout(function step1(e) {
- let mtime1 = getSessionstorejsModificationTime();
- isnot(mtime1, mtime0, "initial sessionstore.js update");
-
- // step2: test sessionstore.js is not updated on tab selection
- // or content scrolling
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.contentWindow.scrollTo(1100, 1200);
- setTimeout(function step2(e) {
- let mtime2 = getSessionstorejsModificationTime();
- is(mtime2, mtime1,
- "tab selection and scrolling: sessionstore.js not updated");
-
- // ok, done, cleanup and finish
- if (gPrefService.prefHasUserValue(PREF_INTERVAL))
- gPrefService.clearUserPref(PREF_INTERVAL);
- gBrowser.removeTab(tab);
- finish();
- }, 3500); // end of sleep after tab selection and scrolling
- }, 3500); // end of sleep after initial saveStateDelayed()
- });
-}
diff --git a/browser/components/sessionstore/test/browser_514751.js b/browser/components/sessionstore/test/browser_514751.js
deleted file mode 100644
index ff80245c4..000000000
--- a/browser/components/sessionstore/test/browser_514751.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 514751 (Wallpaper) **/
-
- waitForExplicitFinish();
-
- let state = {
- windows: [{
- tabs: [{
- entries: [
- { url: "about:mozilla", title: "Mozilla" },
- {}
- ]
- }]
- }]
- };
-
- var theWin = openDialog(location, "", "chrome,all,dialog=no");
- theWin.addEventListener("load", function () {
- theWin.removeEventListener("load", arguments.callee, false);
-
- executeSoon(function () {
- var gotError = false;
- try {
- ss.setWindowState(theWin, JSON.stringify(state), true);
- } catch (e) {
- if (/NS_ERROR_MALFORMED_URI/.test(e))
- gotError = true;
- }
- ok(!gotError, "Didn't get a malformed URI error.");
- BrowserTestUtils.closeWindow(theWin).then(finish);
- });
- }, false);
-}
-
diff --git a/browser/components/sessionstore/test/browser_522375.js b/browser/components/sessionstore/test/browser_522375.js
deleted file mode 100644
index 50b74d6cd..000000000
--- a/browser/components/sessionstore/test/browser_522375.js
+++ /dev/null
@@ -1,21 +0,0 @@
-function test() {
- var startup_info = Components.classes["@mozilla.org/toolkit/app-startup;1"].getService(Components.interfaces.nsIAppStartup).getStartupInfo();
- // No .process info on mac
-
- // Check if we encountered a telemetry error for the the process creation
- // timestamp and turn the first test into a known failure.
- var telemetry = Cc["@mozilla.org/base/telemetry;1"].getService(Ci.nsITelemetry);
- var snapshot = telemetry.getHistogramById("STARTUP_MEASUREMENT_ERRORS")
- .snapshot();
-
- if (snapshot.counts[0] == 0)
- ok(startup_info.process <= startup_info.main, "process created before main is run " + uneval(startup_info));
- else
- todo(false, "An error occurred while recording the process creation timestamp, skipping this test");
-
- // on linux firstPaint can happen after everything is loaded (especially with remote X)
- if (startup_info.firstPaint)
- ok(startup_info.main <= startup_info.firstPaint, "main ran before first paint " + uneval(startup_info));
-
- ok(startup_info.main < startup_info.sessionRestored, "Session restored after main " + uneval(startup_info));
-}
diff --git a/browser/components/sessionstore/test/browser_522545.js b/browser/components/sessionstore/test/browser_522545.js
deleted file mode 100644
index f4d373166..000000000
--- a/browser/components/sessionstore/test/browser_522545.js
+++ /dev/null
@@ -1,269 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 522545 **/
-
- waitForExplicitFinish();
- requestLongerTimeout(4);
-
- // This tests the following use case:
- // User opens a new tab which gets focus. The user types something into the
- // address bar, then crashes or quits.
- function test_newTabFocused() {
- let state = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:mozilla" }] },
- { entries: [], userTypedValue: "example.com", userTypedClear: 0 }
- ],
- selected: 2
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.selectedBrowser;
- is(browser.currentURI.spec, "about:blank",
- "No history entries still sets currentURI to about:blank");
- is(browser.userTypedValue, "example.com",
- "userTypedValue was correctly restored");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "We still know that no load is ongoing");
- is(gURLBar.value, "example.com",
- "Address bar's value correctly restored");
- // Change tabs to make sure address bar value gets updated
- gBrowser.selectedTab = gBrowser.tabContainer.getItemAtIndex(0);
- is(gURLBar.value, "about:mozilla",
- "Address bar's value correctly updated");
- runNextTest();
- });
- }
-
- // This tests the following use case:
- // User opens a new tab which gets focus. The user types something into the
- // address bar, switches back to the first tab, then crashes or quits.
- function test_newTabNotFocused() {
- let state = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:mozilla" }] },
- { entries: [], userTypedValue: "example.org", userTypedClear: 0 }
- ],
- selected: 1
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.getBrowserAtIndex(1);
- is(browser.currentURI.spec, "about:blank",
- "No history entries still sets currentURI to about:blank");
- is(browser.userTypedValue, "example.org",
- "userTypedValue was correctly restored");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "We still know that no load is ongoing");
- is(gURLBar.value, "about:mozilla",
- "Address bar's value correctly restored");
- // Change tabs to make sure address bar value gets updated
- gBrowser.selectedTab = gBrowser.tabContainer.getItemAtIndex(1);
- is(gURLBar.value, "example.org",
- "Address bar's value correctly updated");
- runNextTest();
- });
- }
-
- // This tests the following use case:
- // User is in a tab with session history, then types something in the
- // address bar, then crashes or quits.
- function test_existingSHEnd_noClear() {
- let state = {
- windows: [{
- tabs: [{
- entries: [{ url: "about:mozilla" }, { url: "about:config" }],
- index: 2,
- userTypedValue: "example.com",
- userTypedClear: 0
- }]
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.selectedBrowser;
- is(browser.currentURI.spec, "about:config",
- "browser.currentURI set to current entry in SH");
- is(browser.userTypedValue, "example.com",
- "userTypedValue was correctly restored");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "We still know that no load is ongoing");
- is(gURLBar.value, "example.com",
- "Address bar's value correctly restored to userTypedValue");
- runNextTest();
- });
- }
-
- // This tests the following use case:
- // User is in a tab with session history, presses back at some point, then
- // types something in the address bar, then crashes or quits.
- function test_existingSHMiddle_noClear() {
- let state = {
- windows: [{
- tabs: [{
- entries: [{ url: "about:mozilla" }, { url: "about:config" }],
- index: 1,
- userTypedValue: "example.org",
- userTypedClear: 0
- }]
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.selectedBrowser;
- is(browser.currentURI.spec, "about:mozilla",
- "browser.currentURI set to current entry in SH");
- is(browser.userTypedValue, "example.org",
- "userTypedValue was correctly restored");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "We still know that no load is ongoing");
- is(gURLBar.value, "example.org",
- "Address bar's value correctly restored to userTypedValue");
- runNextTest();
- });
- }
-
- // This test simulates lots of tabs opening at once and then quitting/crashing.
- function test_getBrowserState_lotsOfTabsOpening() {
- gBrowser.stop();
-
- let uris = [];
- for (let i = 0; i < 25; i++)
- uris.push("http://example.com/" + i);
-
- // We're waiting for the first location change, which should indicate
- // one of the tabs has loaded and the others haven't. So one should
- // be in a non-userTypedValue case, while others should still have
- // userTypedValue and userTypedClear set.
- gBrowser.addTabsProgressListener({
- onLocationChange: function (aBrowser) {
- if (uris.indexOf(aBrowser.currentURI.spec) > -1) {
- gBrowser.removeTabsProgressListener(this);
- firstLocationChange();
- }
- }
- });
-
- function firstLocationChange() {
- let state = JSON.parse(ss.getBrowserState());
- let hasUTV = state.windows[0].tabs.some(function(aTab) {
- return aTab.userTypedValue && aTab.userTypedClear && !aTab.entries.length;
- });
-
- ok(hasUTV, "At least one tab has a userTypedValue with userTypedClear with no loaded URL");
-
- BrowserTestUtils.waitForMessage(gBrowser.selectedBrowser.messageManager, "SessionStore:update").then(firstLoad);
- }
-
- function firstLoad() {
- let state = JSON.parse(ss.getTabState(gBrowser.selectedTab));
- let hasSH = !("userTypedValue" in state) && state.entries[0].url;
- ok(hasSH, "The selected tab has its entry in SH");
-
- runNextTest();
- }
-
- gBrowser.loadTabs(uris);
- }
-
- // This simulates setting a userTypedValue and ensures that just typing in the
- // URL bar doesn't set userTypedClear as well.
- function test_getBrowserState_userTypedValue() {
- let state = {
- windows: [{
- tabs: [{ entries: [] }]
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.selectedBrowser;
- // Make sure this tab isn't loading and state is clear before we test.
- is(browser.userTypedValue, null, "userTypedValue is empty to start");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "Initially, no load should be ongoing");
-
- let inputText = "example.org";
- gURLBar.focus();
- gURLBar.value = inputText.slice(0, -1);
- EventUtils.synthesizeKey(inputText.slice(-1) , {});
-
- executeSoon(function () {
- is(browser.userTypedValue, "example.org",
- "userTypedValue was set when changing URLBar value");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "No load started since changing URLBar value");
-
- // Now make sure ss gets these values too
- let newState = JSON.parse(ss.getBrowserState());
- is(newState.windows[0].tabs[0].userTypedValue, "example.org",
- "sessionstore got correct userTypedValue");
- is(newState.windows[0].tabs[0].userTypedClear, 0,
- "sessionstore got correct userTypedClear");
- runNextTest();
- });
- });
- }
-
- // test_getBrowserState_lotsOfTabsOpening tested userTypedClear in a few cases,
- // but not necessarily any that had legitimate URIs in the state of loading
- // (eg, "http://example.com"), so this test will cover that case.
- function test_userTypedClearLoadURI() {
- let state = {
- windows: [{
- tabs: [
- { entries: [], userTypedValue: "http://example.com", userTypedClear: 2 }
- ]
- }]
- };
-
- waitForBrowserState(state, function() {
- let browser = gBrowser.selectedBrowser;
- is(browser.currentURI.spec, "http://example.com/",
- "userTypedClear=2 caused userTypedValue to be loaded");
- is(browser.userTypedValue, null,
- "userTypedValue was null after loading a URI");
- ok(!browser.didStartLoadSinceLastUserTyping(),
- "We should have reset the load state when the tab loaded");
- is(gURLBar.textValue, gURLBar.trimValue("http://example.com/"),
- "Address bar's value set after loading URI");
- runNextTest();
- });
- }
-
-
- let tests = [test_newTabFocused, test_newTabNotFocused,
- test_existingSHEnd_noClear, test_existingSHMiddle_noClear,
- test_getBrowserState_lotsOfTabsOpening,
- test_getBrowserState_userTypedValue, test_userTypedClearLoadURI];
- let originalState = JSON.parse(ss.getBrowserState());
- let state = {
- windows: [{
- tabs: [{ entries: [{ url: "about:blank" }] }]
- }]
- };
- function runNextTest() {
- if (tests.length) {
- waitForBrowserState(state, function() {
- gBrowser.selectedBrowser.userTypedValue = null;
- URLBarSetURI();
- (tests.shift())();
- });
- } else {
- waitForBrowserState(originalState, function() {
- gBrowser.selectedBrowser.userTypedValue = null;
- URLBarSetURI();
- finish();
- });
- }
- }
-
- // Run the tests!
- runNextTest();
-}
diff --git a/browser/components/sessionstore/test/browser_524745.js b/browser/components/sessionstore/test/browser_524745.js
deleted file mode 100644
index de53f6c92..000000000
--- a/browser/components/sessionstore/test/browser_524745.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 524745 **/
-
- let uniqKey = "bug524745";
- let uniqVal = Date.now().toString();
-
- waitForExplicitFinish();
-
- whenNewWindowLoaded({ private: false }, function (window_B) {
- waitForFocus(function() {
- // Add identifying information to window_B
- ss.setWindowValue(window_B, uniqKey, uniqVal);
- let state = JSON.parse(ss.getBrowserState());
- let selectedWindow = state.windows[state.selectedWindow - 1];
- is(selectedWindow.extData && selectedWindow.extData[uniqKey], uniqVal,
- "selectedWindow is window_B");
-
- // Now minimize window_B. The selected window shouldn't have the secret data
- window_B.minimize();
- waitForFocus(function() {
- state = JSON.parse(ss.getBrowserState());
- selectedWindow = state.windows[state.selectedWindow - 1];
- ok(!selectedWindow.extData || !selectedWindow.extData[uniqKey],
- "selectedWindow is not window_B after minimizing it");
-
- // Now minimize the last open window (assumes no other tests left windows open)
- window.minimize();
- state = JSON.parse(ss.getBrowserState());
- is(state.selectedWindow, 0,
- "selectedWindow should be 0 when all windows are minimized");
-
- // Cleanup
- window.restore();
- BrowserTestUtils.closeWindow(window_B).then(finish);
- });
- }, window_B);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_526613.js b/browser/components/sessionstore/test/browser_526613.js
deleted file mode 100644
index 7e7fe8059..000000000
--- a/browser/components/sessionstore/test/browser_526613.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* 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/. */
-
-function test() {
- /** Test for Bug 526613 **/
-
- // test setup
- waitForExplicitFinish();
-
- function browserWindowsCount(expected) {
- let count = 0;
- let e = Services.wm.getEnumerator("navigator:browser");
- while (e.hasMoreElements()) {
- if (!e.getNext().closed)
- ++count;
- }
- is(count, expected,
- "number of open browser windows according to nsIWindowMediator");
- let state = ss.getBrowserState();
- info(state);
- is(JSON.parse(state).windows.length, expected,
- "number of open browser windows according to getBrowserState");
- }
-
- browserWindowsCount(1);
-
- // backup old state
- let oldState = ss.getBrowserState();
- // create a new state for testing
- let testState = {
- windows: [
- { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 },
- { tabs: [{ entries: [{ url: "about:mozilla" }] }], selected: 1 },
- ],
- // make sure the first window is focused, otherwise when restoring the
- // old state, the first window is closed and the test harness gets unloaded
- selectedWindow: 1
- };
-
- let pass = 1;
- function observer(aSubject, aTopic, aData) {
- is(aTopic, "sessionstore-browser-state-restored",
- "The sessionstore-browser-state-restored notification was observed");
-
- if (pass++ == 1) {
- browserWindowsCount(2);
-
- // let the first window be focused (see above)
- function pollMostRecentWindow() {
- if (Services.wm.getMostRecentWindow("navigator:browser") == window) {
- ss.setBrowserState(oldState);
- } else {
- info("waiting for the current window to become active");
- setTimeout(pollMostRecentWindow, 0);
- window.focus(); //XXX Why is this needed?
- }
- }
- pollMostRecentWindow();
- }
- else {
- browserWindowsCount(1);
- ok(!window.closed, "Restoring the old state should have left this window open");
- Services.obs.removeObserver(observer, "sessionstore-browser-state-restored");
- finish();
- }
- }
- Services.obs.addObserver(observer, "sessionstore-browser-state-restored", false);
-
- // set browser to test state
- ss.setBrowserState(JSON.stringify(testState));
-}
diff --git a/browser/components/sessionstore/test/browser_528776.js b/browser/components/sessionstore/test/browser_528776.js
deleted file mode 100644
index d799c9740..000000000
--- a/browser/components/sessionstore/test/browser_528776.js
+++ /dev/null
@@ -1,21 +0,0 @@
-function browserWindowsCount(expected) {
- var count = 0;
- var e = Services.wm.getEnumerator("navigator:browser");
- while (e.hasMoreElements()) {
- if (!e.getNext().closed)
- ++count;
- }
- is(count, expected,
- "number of open browser windows according to nsIWindowMediator");
- is(JSON.parse(ss.getBrowserState()).windows.length, expected,
- "number of open browser windows according to getBrowserState");
-}
-
-add_task(function() {
- browserWindowsCount(1);
-
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- browserWindowsCount(2);
- yield BrowserTestUtils.closeWindow(win);
- browserWindowsCount(1);
-});
diff --git a/browser/components/sessionstore/test/browser_579868.js b/browser/components/sessionstore/test/browser_579868.js
deleted file mode 100644
index d6c6245d0..000000000
--- a/browser/components/sessionstore/test/browser_579868.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* 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/. */
-
-function test() {
- waitForExplicitFinish();
-
- let tab1 = gBrowser.addTab("about:rights");
- let tab2 = gBrowser.addTab("about:mozilla");
-
- promiseBrowserLoaded(tab1.linkedBrowser).then(() => {
- // Tell the session storer that the tab is pinned
- let newTabState = '{"entries":[{"url":"about:rights"}],"pinned":true,"userTypedValue":"Hello World!"}';
- ss.setTabState(tab1, newTabState);
-
- // Undo pinning
- gBrowser.unpinTab(tab1);
-
- // Close and restore tab
- gBrowser.removeTab(tab1);
- let savedState = JSON.parse(ss.getClosedTabData(window))[0].state;
- isnot(savedState.pinned, true, "Pinned should not be true");
- tab1 = ss.undoCloseTab(window, 0);
-
- isnot(tab1.pinned, true, "Should not be pinned");
- gBrowser.removeTab(tab1);
- gBrowser.removeTab(tab2);
- finish();
- });
-}
diff --git a/browser/components/sessionstore/test/browser_579879.js b/browser/components/sessionstore/test/browser_579879.js
deleted file mode 100644
index 6886be038..000000000
--- a/browser/components/sessionstore/test/browser_579879.js
+++ /dev/null
@@ -1,20 +0,0 @@
-"use strict";
-
-add_task(function* () {
- let tab1 = gBrowser.addTab("data:text/plain;charset=utf-8,foo");
- gBrowser.pinTab(tab1);
-
- yield promiseBrowserLoaded(tab1.linkedBrowser);
- let tab2 = gBrowser.addTab();
- gBrowser.pinTab(tab2);
-
- is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 is at the first position");
- yield promiseRemoveTab(tab1);
-
- tab1 = undoCloseTab();
- ok(tab1.pinned, "pinned tab 1 has been restored as a pinned tab");
- is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 has been restored to the first position");
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-});
diff --git a/browser/components/sessionstore/test/browser_580512.js b/browser/components/sessionstore/test/browser_580512.js
deleted file mode 100644
index ef048cd37..000000000
--- a/browser/components/sessionstore/test/browser_580512.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* 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/. */
-
-const URIS_PINNED = ["about:license", "about:about"];
-const URIS_NORMAL_A = ["about:mozilla"];
-const URIS_NORMAL_B = ["about:buildconfig"];
-
-function test() {
- waitForExplicitFinish();
-
- isnot(Services.prefs.getIntPref("browser.startup.page"), 3,
- "pref to save session must not be set for this test");
- ok(!Services.prefs.getBoolPref("browser.sessionstore.resume_session_once"),
- "pref to save session once must not be set for this test");
-
- document.documentElement.setAttribute("windowtype", "navigator:browsertestdummy");
-
- openWinWithCb(closeFirstWin, URIS_PINNED.concat(URIS_NORMAL_A));
-}
-
-function closeFirstWin(win) {
- win.gBrowser.pinTab(win.gBrowser.tabs[0]);
- win.gBrowser.pinTab(win.gBrowser.tabs[1]);
-
- let winClosed = BrowserTestUtils.windowClosed(win);
- // We need to call BrowserTryToCloseWindow in order to trigger
- // the machinery that chooses whether or not to save the session
- // for the last window.
- win.BrowserTryToCloseWindow();
- ok(win.closed, "window closed");
-
- winClosed.then(() => {
- openWinWithCb(checkSecondWin, URIS_NORMAL_B, URIS_PINNED.concat(URIS_NORMAL_B));
- });
-}
-
-function checkSecondWin(win) {
- is(win.gBrowser.browsers[0].currentURI.spec, URIS_PINNED[0], "first pinned tab restored");
- is(win.gBrowser.browsers[1].currentURI.spec, URIS_PINNED[1], "second pinned tab restored");
- ok(win.gBrowser.tabs[0].pinned, "first pinned tab is still pinned");
- ok(win.gBrowser.tabs[1].pinned, "second pinned tab is still pinned");
-
- BrowserTestUtils.closeWindow(win).then(() => {
- // cleanup
- document.documentElement.setAttribute("windowtype", "navigator:browser");
- finish();
- });
-}
-
-function openWinWithCb(cb, argURIs, expectedURIs) {
- if (!expectedURIs)
- expectedURIs = argURIs;
-
- var win = openDialog(getBrowserURL(), "_blank",
- "chrome,all,dialog=no", argURIs.join("|"));
-
- win.addEventListener("load", function () {
- win.removeEventListener("load", arguments.callee, false);
- info("the window loaded");
-
- var expectedLoads = expectedURIs.length;
-
- win.gBrowser.addTabsProgressListener({
- onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
- if (aRequest &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
- expectedURIs.indexOf(aRequest.QueryInterface(Ci.nsIChannel).originalURI.spec) > -1 &&
- --expectedLoads <= 0) {
- win.gBrowser.removeTabsProgressListener(this);
- info("all tabs loaded");
- is(win.gBrowser.tabs.length, expectedURIs.length, "didn't load any unexpected tabs");
- executeSoon(function () {
- cb(win);
- });
- }
- }
- });
- }, false);
-}
diff --git a/browser/components/sessionstore/test/browser_581937.js b/browser/components/sessionstore/test/browser_581937.js
deleted file mode 100644
index 74ddaa9d2..000000000
--- a/browser/components/sessionstore/test/browser_581937.js
+++ /dev/null
@@ -1,19 +0,0 @@
-// Tests that an about:blank tab with no history will not be saved into
-// session store and thus, it will not show up in Recently Closed Tabs.
-
-"use strict";
-
-add_task(function* () {
- let tab = gBrowser.addTab("about:blank");
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- is(tab.linkedBrowser.currentURI.spec, "about:blank",
- "we will be removing an about:blank tab");
-
- let r = `rand-${Math.random()}`;
- ss.setTabValue(tab, "foobar", r);
-
- yield promiseRemoveTab(tab);
- let closedTabData = ss.getClosedTabData(window);
- ok(!closedTabData.includes(r), "tab not stored in _closedTabs");
-});
diff --git a/browser/components/sessionstore/test/browser_586068-apptabs.js b/browser/components/sessionstore/test/browser_586068-apptabs.js
deleted file mode 100644
index f8727c04f..000000000
--- a/browser/components/sessionstore/test/browser_586068-apptabs.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/* 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/. */
-
-requestLongerTimeout(2);
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } },
- ], selected: 5 }] };
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- loadCount++;
-
- // We'll make sure that the loads we get come from pinned tabs or the
- // the selected tab.
-
- // get the tab
- let tab;
- for (let i = 0; i < window.gBrowser.tabs.length; i++) {
- if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser)
- tab = window.gBrowser.tabs[i];
- }
-
- ok(tab.pinned || tab.selected,
- "load came from pinned or selected tab");
-
- // We should get 4 loads: 3 app tabs + 1 normal selected tab
- if (loadCount < 4)
- return;
-
- gProgressListener.unsetCallback();
- resolve();
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js b/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js
deleted file mode 100644
index b58aa649b..000000000
--- a/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-const PREF_RESTORE_PINNED_TABS_ON_DEMAND = "browser.sessionstore.restore_pinned_tabs_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true);
- Services.prefs.setBoolPref(PREF_RESTORE_PINNED_TABS_ON_DEMAND, true);
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- Services.prefs.clearUserPref(PREF_RESTORE_PINNED_TABS_ON_DEMAND);
- });
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() }, pinned: true },
- { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } },
- ], selected: 5 }] };
-
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- // get the tab
- let tab;
- for (let i = 0; i < window.gBrowser.tabs.length; i++) {
- if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser)
- tab = window.gBrowser.tabs[i];
- }
-
- // Check that the load only comes from the selected tab.
- ok(tab.selected, "load came from selected tab");
- is(aNeedRestore, 6, "six tabs left to restore");
- is(aRestoring, 1, "one tab is restoring");
- is(aRestored, 0, "no tabs have been restored, yet");
-
- gProgressListener.unsetCallback();
- resolve();
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js b/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js
deleted file mode 100644
index de8f1aba0..000000000
--- a/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-requestLongerTimeout(2);
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // The first state will be loaded using setBrowserState, followed by the 2nd
- // state also being loaded using setBrowserState, interrupting the first restore.
- let state1 = { windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } }
- ],
- selected: 1
- },
- {
- tabs: [
- { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } },
- ],
- selected: 3
- }
- ] };
- let state2 = { windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#6" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#7" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#8" }], extData: { "uniq": r() } }
- ],
- selected: 3
- },
- {
- tabs: [
- { entries: [{ url: "http://example.com#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#6" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#7" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#8" }], extData: { "uniq": r() } },
- ],
- selected: 1
- }
- ] };
-
- // interruptedAfter will be set after the selected tab from each window have loaded.
- let interruptedAfter = 0;
- let loadedWindow1 = false;
- let loadedWindow2 = false;
- let numTabs = state2.windows[0].tabs.length + state2.windows[1].tabs.length;
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- loadCount++;
-
- if (aBrowser.currentURI.spec == state1.windows[0].tabs[2].entries[0].url)
- loadedWindow1 = true;
- if (aBrowser.currentURI.spec == state1.windows[1].tabs[0].entries[0].url)
- loadedWindow2 = true;
-
- if (!interruptedAfter && loadedWindow1 && loadedWindow2) {
- interruptedAfter = loadCount;
- ss.setBrowserState(JSON.stringify(state2));
- return;
- }
-
- if (loadCount < numTabs + interruptedAfter)
- return;
-
- // We don't actually care about load order in this test, just that they all
- // do load.
- is(loadCount, numTabs + interruptedAfter, "all tabs were restored");
- is(aNeedRestore, 0, "there are no tabs left needing restore");
-
- // Remove the progress listener.
- gProgressListener.unsetCallback();
- resolve();
- });
- });
-
- // We also want to catch the extra windows (there should be 2), so we need to observe domwindowopened
- Services.ww.registerNotification(function observer(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- Services.ww.unregisterNotification(observer);
- win.gBrowser.addTabsProgressListener(gProgressListener);
- });
- }
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state1));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseAllButPrimaryWindowClosed();
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-cascade.js b/browser/components/sessionstore/test/browser_586068-cascade.js
deleted file mode 100644
index 041aea85c..000000000
--- a/browser/components/sessionstore/test/browser_586068-cascade.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }
- ] }] };
-
- let expectedCounts = [
- [3, 3, 0],
- [2, 3, 1],
- [1, 3, 2],
- [0, 3, 3],
- [0, 2, 4],
- [0, 1, 5]
- ];
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- loadCount++;
- let expected = expectedCounts[loadCount - 1];
-
- is(aNeedRestore, expected[0], "load " + loadCount + " - # tabs that need to be restored");
- is(aRestoring, expected[1], "load " + loadCount + " - # tabs that are restoring");
- is(aRestored, expected[2], "load " + loadCount + " - # tabs that has been restored");
-
- if (loadCount == state.windows[0].tabs.length) {
- gProgressListener.unsetCallback();
- resolve();
- }
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-multi_window.js b/browser/components/sessionstore/test/browser_586068-multi_window.js
deleted file mode 100644
index 03337568e..000000000
--- a/browser/components/sessionstore/test/browser_586068-multi_window.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // The first window will be put into the already open window and the second
- // window will be opened with _openWindowWithState, which is the source of the problem.
- let state = { windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org#0" }], extData: { "uniq": r() } }
- ],
- selected: 1
- },
- {
- tabs: [
- { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#6" }], extData: { "uniq": r() } }
- ],
- selected: 4
- }
- ] };
- let numTabs = state.windows[0].tabs.length + state.windows[1].tabs.length;
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- if (++loadCount == numTabs) {
- // We don't actually care about load order in this test, just that they all
- // do load.
- is(loadCount, numTabs, "all tabs were restored");
- is(aNeedRestore, 0, "there are no tabs left needing restore");
-
- gProgressListener.unsetCallback();
- resolve();
- }
- });
- });
-
- // We also want to catch the 2nd window, so we need to observe domwindowopened
- Services.ww.registerNotification(function observer(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- Services.ww.unregisterNotification(observer);
- win.gBrowser.addTabsProgressListener(gProgressListener);
- });
- }
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseAllButPrimaryWindowClosed();
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-reload.js b/browser/components/sessionstore/test/browser_586068-reload.js
deleted file mode 100644
index 630c91f2d..000000000
--- a/browser/components/sessionstore/test/browser_586068-reload.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#8" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org/#9" }], extData: { "uniq": r() } },
- ], selected: 1 }] };
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gBrowser.tabContainer.addEventListener("SSTabRestored", function onRestored(event) {
- let tab = event.target;
- let browser = tab.linkedBrowser;
- let tabData = state.windows[0].tabs[loadCount++];
-
- // double check that this tab was the right one
- is(browser.currentURI.spec, tabData.entries[0].url,
- "load " + loadCount + " - browser loaded correct url");
- is(ss.getTabValue(tab, "uniq"), tabData.extData.uniq,
- "load " + loadCount + " - correct tab was restored");
-
- if (loadCount == state.windows[0].tabs.length) {
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onRestored);
- resolve();
- } else {
- // reload the next tab
- gBrowser.browsers[loadCount].reload();
- }
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-select.js b/browser/components/sessionstore/test/browser_586068-select.js
deleted file mode 100644
index 433e1754c..000000000
--- a/browser/components/sessionstore/test/browser_586068-select.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }
- ], selected: 1 }] };
-
- let expectedCounts = [
- [5, 1, 0],
- [4, 1, 1],
- [3, 1, 2],
- [2, 1, 3],
- [1, 1, 4],
- [0, 1, 5]
- ];
- let tabOrder = [0, 5, 1, 4, 3, 2];
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- loadCount++;
- let expected = expectedCounts[loadCount - 1];
-
- is(aNeedRestore, expected[0], "load " + loadCount + " - # tabs that need to be restored");
- is(aRestoring, expected[1], "load " + loadCount + " - # tabs that are restoring");
- is(aRestored, expected[2], "load " + loadCount + " - # tabs that has been restored");
-
- if (loadCount < state.windows[0].tabs.length) {
- // double check that this tab was the right one
- let expectedData = state.windows[0].tabs[tabOrder[loadCount - 1]].extData.uniq;
- let tab;
- for (let i = 0; i < window.gBrowser.tabs.length; i++) {
- if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser)
- tab = window.gBrowser.tabs[i];
- }
-
- is(ss.getTabValue(tab, "uniq"), expectedData,
- "load " + loadCount + " - correct tab was restored");
-
- // select the next tab
- window.gBrowser.selectTabAtIndex(tabOrder[loadCount]);
- } else {
- gProgressListener.unsetCallback();
- resolve();
- }
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setBrowserState(JSON.stringify(state));
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-window_state.js b/browser/components/sessionstore/test/browser_586068-window_state.js
deleted file mode 100644
index 6097a70db..000000000
--- a/browser/components/sessionstore/test/browser_586068-window_state.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // We'll use 2 states so that we can make sure calling setWindowState doesn't
- // wipe out currently restoring data.
- let state1 = { windows: [{ tabs: [
- { entries: [{ url: "http://example.com#1" }] },
- { entries: [{ url: "http://example.com#2" }] },
- { entries: [{ url: "http://example.com#3" }] },
- { entries: [{ url: "http://example.com#4" }] },
- { entries: [{ url: "http://example.com#5" }] },
- ] }] };
- let state2 = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org#1" }] },
- { entries: [{ url: "http://example.org#2" }] },
- { entries: [{ url: "http://example.org#3" }] },
- { entries: [{ url: "http://example.org#4" }] },
- { entries: [{ url: "http://example.org#5" }] }
- ] }] };
- let numTabs = state1.windows[0].tabs.length + state2.windows[0].tabs.length;
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- // When loadCount == 2, we'll also restore state2 into the window
- if (++loadCount == 2) {
- ss.setWindowState(window, JSON.stringify(state2), false);
- }
-
- if (loadCount < numTabs) {
- return;
- }
-
- // We don't actually care about load order in this test, just that they all
- // do load.
- is(loadCount, numTabs, "test_setWindowStateNoOverwrite: all tabs were restored");
- is(aNeedRestore, 0, "there are no tabs left needing restore");
-
- gProgressListener.unsetCallback();
- resolve();
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setWindowState(window, JSON.stringify(state1), true);
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586068-window_state_override.js b/browser/components/sessionstore/test/browser_586068-window_state_override.js
deleted file mode 100644
index 731e03307..000000000
--- a/browser/components/sessionstore/test/browser_586068-window_state_override.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* 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/. */
-
-const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // We'll use 2 states so that we can make sure calling setWindowState doesn't
- // wipe out currently restoring data.
- let state1 = { windows: [{ tabs: [
- { entries: [{ url: "http://example.com#1" }] },
- { entries: [{ url: "http://example.com#2" }] },
- { entries: [{ url: "http://example.com#3" }] },
- { entries: [{ url: "http://example.com#4" }] },
- { entries: [{ url: "http://example.com#5" }] },
- ] }] };
- let state2 = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org#1" }] },
- { entries: [{ url: "http://example.org#2" }] },
- { entries: [{ url: "http://example.org#3" }] },
- { entries: [{ url: "http://example.org#4" }] },
- { entries: [{ url: "http://example.org#5" }] }
- ] }] };
- let numTabs = 2 + state2.windows[0].tabs.length;
-
- let loadCount = 0;
- let promiseRestoringTabs = new Promise(resolve => {
- gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) {
- // When loadCount == 2, we'll also restore state2 into the window
- if (++loadCount == 2) {
- executeSoon(() => ss.setWindowState(window, JSON.stringify(state2), true));
- }
-
- if (loadCount < numTabs) {
- return;
- }
-
- // We don't actually care about load order in this test, just that they all
- // do load.
- is(loadCount, numTabs, "all tabs were restored");
- is(aNeedRestore, 0, "there are no tabs left needing restore");
-
- gProgressListener.unsetCallback();
- resolve();
- });
- });
-
- let backupState = ss.getBrowserState();
- ss.setWindowState(window, JSON.stringify(state1), true);
- yield promiseRestoringTabs;
-
- // Cleanup.
- yield promiseBrowserState(backupState);
-});
diff --git a/browser/components/sessionstore/test/browser_586147.js b/browser/components/sessionstore/test/browser_586147.js
deleted file mode 100644
index fbfec53c7..000000000
--- a/browser/components/sessionstore/test/browser_586147.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* 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/. */
-
-function observeOneRestore(callback) {
- let topic = "sessionstore-browser-state-restored";
- Services.obs.addObserver(function onRestore() {
- Services.obs.removeObserver(onRestore, topic);
- callback();
- }, topic, false);
-};
-
-function test() {
- waitForExplicitFinish();
-
- // There should be one tab when we start the test
- let [origTab] = gBrowser.visibleTabs;
- let hiddenTab = gBrowser.addTab();
-
- is(gBrowser.visibleTabs.length, 2, "should have 2 tabs before hiding");
- gBrowser.showOnlyTheseTabs([origTab]);
- is(gBrowser.visibleTabs.length, 1, "only 1 after hiding");
- ok(hiddenTab.hidden, "sanity check that it's hidden");
-
- let extraTab = gBrowser.addTab();
- let state = ss.getBrowserState();
- let stateObj = JSON.parse(state);
- let tabs = stateObj.windows[0].tabs;
- is(tabs.length, 3, "just checking that browser state is correct");
- ok(!tabs[0].hidden, "first tab is visible");
- ok(tabs[1].hidden, "second is hidden");
- ok(!tabs[2].hidden, "third is visible");
-
- // Make the third tab hidden and then restore the modified state object
- tabs[2].hidden = true;
-
- observeOneRestore(function() {
- let testWindow = Services.wm.getEnumerator("navigator:browser").getNext();
- is(testWindow.gBrowser.visibleTabs.length, 1, "only restored 1 visible tab");
- let tabs = testWindow.gBrowser.tabs;
- ok(!tabs[0].hidden, "first is still visible");
- ok(tabs[1].hidden, "second tab is still hidden");
- ok(tabs[2].hidden, "third tab is now hidden");
-
- // Restore the original state and clean up now that we're done
- gBrowser.removeTab(hiddenTab);
- gBrowser.removeTab(extraTab);
-
- finish();
- });
- ss.setBrowserState(JSON.stringify(stateObj));
-}
diff --git a/browser/components/sessionstore/test/browser_588426.js b/browser/components/sessionstore/test/browser_588426.js
deleted file mode 100644
index d2462f2bd..000000000
--- a/browser/components/sessionstore/test/browser_588426.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- let state = { windows: [{ tabs: [
- {entries: [{url: "about:mozilla"}], hidden: true},
- {entries: [{url: "about:rights"}], hidden: true}
- ] }] };
-
- waitForExplicitFinish();
-
- newWindowWithState(state, function (win) {
- registerCleanupFunction(() => BrowserTestUtils.closeWindow(win));
-
- is(win.gBrowser.tabs.length, 2, "two tabs were restored");
- is(win.gBrowser.visibleTabs.length, 1, "one tab is visible");
-
- let tab = win.gBrowser.visibleTabs[0];
- is(tab.linkedBrowser.currentURI.spec, "about:mozilla", "visible tab is about:mozilla");
-
- finish();
- });
-}
-
-function newWindowWithState(state, callback) {
- let opts = "chrome,all,dialog=no,height=800,width=800";
- let win = window.openDialog(getBrowserURL(), "_blank", opts);
-
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
-
- executeSoon(function () {
- win.addEventListener("SSWindowStateReady", function onReady() {
- win.removeEventListener("SSWindowStateReady", onReady, false);
- promiseTabRestored(win.gBrowser.tabs[0]).then(() => callback(win));
- }, false);
-
- ss.setWindowState(win, JSON.stringify(state), true);
- });
- }, false);
-}
diff --git a/browser/components/sessionstore/test/browser_589246.js b/browser/components/sessionstore/test/browser_589246.js
deleted file mode 100644
index d1f539073..000000000
--- a/browser/components/sessionstore/test/browser_589246.js
+++ /dev/null
@@ -1,242 +0,0 @@
-/* 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/. */
-
-// Mirrors WINDOW_ATTRIBUTES IN nsSessionStore.js
-const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"];
-
-var stateBackup = ss.getBrowserState();
-
-var originalWarnOnClose = gPrefService.getBoolPref("browser.tabs.warnOnClose");
-var originalStartupPage = gPrefService.getIntPref("browser.startup.page");
-var originalWindowType = document.documentElement.getAttribute("windowtype");
-
-var gotLastWindowClosedTopic = false;
-var shouldPinTab = false;
-var shouldOpenTabs = false;
-var shouldCloseTab = false;
-var testNum = 0;
-var afterTestCallback;
-
-// Set state so we know the closed windows content
-var testState = {
- windows: [
- { tabs: [{ entries: [{ url: "http://example.org" }] }] }
- ],
- _closedWindows: []
-};
-
-// We'll push a set of conditions and callbacks into this array
-// Ideally we would also test win/linux under a complete set of conditions, but
-// the tests for osx mirror the other set of conditions possible on win/linux.
-var tests = [];
-
-// the third & fourth test share a condition check, keep it DRY
-function checkOSX34Generator(num) {
- return function(aPreviousState, aCurState) {
- // In here, we should have restored the pinned tab, so only the unpinned tab
- // should be in aCurState. So let's shape our expectations.
- let expectedState = JSON.parse(aPreviousState);
- expectedState[0].tabs.shift();
- // size attributes are stripped out in _prepDataForDeferredRestore in nsSessionStore.
- // This isn't the best approach, but neither is comparing JSON strings
- WINDOW_ATTRIBUTES.forEach(attr => delete expectedState[0][attr]);
-
- is(aCurState, JSON.stringify(expectedState),
- "test #" + num + ": closedWindowState is as expected");
- };
-}
-function checkNoWindowsGenerator(num) {
- return function(aPreviousState, aCurState) {
- is(aCurState, "[]", "test #" + num + ": there should be no closedWindowsLeft");
- };
-}
-
-// The first test has 0 pinned tabs and 1 unpinned tab
-tests.push({
- pinned: false,
- extra: false,
- close: false,
- checkWinLin: checkNoWindowsGenerator(1),
- checkOSX: function(aPreviousState, aCurState) {
- is(aCurState, aPreviousState, "test #1: closed window state is unchanged");
- }
-});
-
-// The second test has 1 pinned tab and 0 unpinned tabs.
-tests.push({
- pinned: true,
- extra: false,
- close: false,
- checkWinLin: checkNoWindowsGenerator(2),
- checkOSX: checkNoWindowsGenerator(2)
-});
-
-// The third test has 1 pinned tab and 2 unpinned tabs.
-tests.push({
- pinned: true,
- extra: true,
- close: false,
- checkWinLin: checkNoWindowsGenerator(3),
- checkOSX: checkOSX34Generator(3)
-});
-
-// The fourth test has 1 pinned tab, 2 unpinned tabs, and closes one unpinned tab.
-tests.push({
- pinned: true,
- extra: true,
- close: "one",
- checkWinLin: checkNoWindowsGenerator(4),
- checkOSX: checkOSX34Generator(4)
-});
-
-// The fifth test has 1 pinned tab, 2 unpinned tabs, and closes both unpinned tabs.
-tests.push({
- pinned: true,
- extra: true,
- close: "both",
- checkWinLin: checkNoWindowsGenerator(5),
- checkOSX: checkNoWindowsGenerator(5)
-});
-
-
-function test() {
- /** Test for Bug 589246 - Closed window state getting corrupted when closing
- and reopening last browser window without exiting browser **/
- waitForExplicitFinish();
- // windows opening & closing, so extending the timeout
- requestLongerTimeout(2);
-
- // We don't want the quit dialog pref
- gPrefService.setBoolPref("browser.tabs.warnOnClose", false);
- // Ensure that we would restore the session (important for Windows)
- gPrefService.setIntPref("browser.startup.page", 3);
-
- runNextTestOrFinish();
-}
-
-function runNextTestOrFinish() {
- if (tests.length) {
- setupForTest(tests.shift())
- }
- else {
- // some state is cleaned up at the end of each test, but not all
- ["browser.tabs.warnOnClose", "browser.startup.page"].forEach(function(p) {
- if (gPrefService.prefHasUserValue(p))
- gPrefService.clearUserPref(p);
- });
-
- ss.setBrowserState(stateBackup);
- executeSoon(finish);
- }
-}
-
-function setupForTest(aConditions) {
- // reset some checks
- gotLastWindowClosedTopic = false;
- shouldPinTab = aConditions.pinned;
- shouldOpenTabs = aConditions.extra;
- shouldCloseTab = aConditions.close;
- testNum++;
-
- // set our test callback
- afterTestCallback = /Mac/.test(navigator.platform) ? aConditions.checkOSX
- : aConditions.checkWinLin;
-
- // Add observers
- Services.obs.addObserver(onLastWindowClosed, "browser-lastwindow-close-granted", false);
-
- // Set the state
- Services.obs.addObserver(onStateRestored, "sessionstore-browser-state-restored", false);
- ss.setBrowserState(JSON.stringify(testState));
-}
-
-function onStateRestored(aSubject, aTopic, aData) {
- info("test #" + testNum + ": onStateRestored");
- Services.obs.removeObserver(onStateRestored, "sessionstore-browser-state-restored");
-
- // change this window's windowtype so that closing a new window will trigger
- // browser-lastwindow-close-granted.
- document.documentElement.setAttribute("windowtype", "navigator:testrunner");
-
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no", "http://example.com");
- newWin.addEventListener("load", function(aEvent) {
- newWin.removeEventListener("load", arguments.callee, false);
-
- promiseBrowserLoaded(newWin.gBrowser.selectedBrowser).then(() => {
- // pin this tab
- if (shouldPinTab)
- newWin.gBrowser.pinTab(newWin.gBrowser.selectedTab);
-
- newWin.addEventListener("unload", function () {
- newWin.removeEventListener("unload", arguments.callee, false);
- onWindowUnloaded();
- }, false);
- // Open a new tab as well. On Windows/Linux this will be restored when the
- // new window is opened below (in onWindowUnloaded). On OS X we'll just
- // restore the pinned tabs, leaving the unpinned tab in the closedWindowsData.
- if (shouldOpenTabs) {
- let newTab = newWin.gBrowser.addTab("about:config");
- let newTab2 = newWin.gBrowser.addTab("about:buildconfig");
-
- newTab.linkedBrowser.addEventListener("load", function() {
- newTab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-
- if (shouldCloseTab == "one") {
- newWin.gBrowser.removeTab(newTab2);
- }
- else if (shouldCloseTab == "both") {
- newWin.gBrowser.removeTab(newTab);
- newWin.gBrowser.removeTab(newTab2);
- }
- newWin.BrowserTryToCloseWindow();
- }, true);
- }
- else {
- newWin.BrowserTryToCloseWindow();
- }
- });
- }, false);
-}
-
-// This will be called before the window is actually closed
-function onLastWindowClosed(aSubject, aTopic, aData) {
- info("test #" + testNum + ": onLastWindowClosed");
- Services.obs.removeObserver(onLastWindowClosed, "browser-lastwindow-close-granted");
- gotLastWindowClosedTopic = true;
-}
-
-// This is the unload event listener on the new window (from onStateRestored).
-// Unload is fired after the window is closed, so sessionstore has already
-// updated _closedWindows (which is important). We'll open a new window here
-// which should actually trigger the bug.
-function onWindowUnloaded() {
- info("test #" + testNum + ": onWindowClosed");
- ok(gotLastWindowClosedTopic, "test #" + testNum + ": browser-lastwindow-close-granted was notified prior");
-
- let previousClosedWindowData = ss.getClosedWindowData();
-
- // Now we want to open a new window
- let newWin = openDialog(location, "_blank", "chrome,all,dialog=no", "about:mozilla");
- newWin.addEventListener("load", function(aEvent) {
- newWin.removeEventListener("load", arguments.callee, false);
-
- newWin.gBrowser.selectedBrowser.addEventListener("load", function () {
- newWin.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
-
- // Good enough for checking the state
- afterTestCallback(previousClosedWindowData, ss.getClosedWindowData());
- afterTestCleanup(newWin);
- }, true);
-
- }, false);
-}
-
-function afterTestCleanup(aNewWin) {
- executeSoon(function() {
- BrowserTestUtils.closeWindow(aNewWin).then(() => {
- document.documentElement.setAttribute("windowtype", originalWindowType);
- runNextTestOrFinish();
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_590268.js b/browser/components/sessionstore/test/browser_590268.js
deleted file mode 100644
index 2b0c2f32d..000000000
--- a/browser/components/sessionstore/test/browser_590268.js
+++ /dev/null
@@ -1,137 +0,0 @@
-/* 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/. */
-
-const NUM_TABS = 12;
-
-var stateBackup = ss.getBrowserState();
-
-function test() {
- /** Test for Bug 590268 - Provide access to sessionstore tab data sooner **/
- waitForExplicitFinish();
- requestLongerTimeout(2);
-
- let startedTest = false;
-
- // wasLoaded will be used to keep track of tabs that have already had SSTabRestoring
- // fired for them.
- let wasLoaded = { };
- let restoringTabsCount = 0;
- let restoredTabsCount = 0;
- let uniq2 = { };
- let uniq2Count = 0;
- let state = { windows: [{ tabs: [] }] };
- // We're going to put a bunch of tabs into this state
- for (let i = 0; i < NUM_TABS; i++) {
- let uniq = r();
- let tabData = {
- entries: [{ url: "http://example.com/#" + i }],
- extData: { "uniq": uniq, "baz": "qux" }
- };
- state.windows[0].tabs.push(tabData);
- wasLoaded[uniq] = false;
- }
-
-
- function onSSTabRestoring(aEvent) {
- restoringTabsCount++;
- let uniq = ss.getTabValue(aEvent.originalTarget, "uniq");
- wasLoaded[uniq] = true;
-
- is(ss.getTabValue(aEvent.originalTarget, "foo"), "",
- "There is no value for 'foo'");
-
- // On the first SSTabRestoring we're going to run the the real test.
- // We'll keep this listener around so we can keep marking tabs as restored.
- if (restoringTabsCount == 1)
- onFirstSSTabRestoring();
- else if (restoringTabsCount == NUM_TABS)
- onLastSSTabRestoring();
- }
-
- function onSSTabRestored(aEvent) {
- if (++restoredTabsCount < NUM_TABS)
- return;
- cleanup();
- }
-
- function onTabOpen(aEvent) {
- // To test bug 614708, we'll just set a value on the tab here. This value
- // would previously cause us to not recognize the values in extData until
- // much later. So testing "uniq" failed.
- ss.setTabValue(aEvent.originalTarget, "foo", "bar");
- }
-
- // This does the actual testing. SSTabRestoring should be firing on tabs from
- // left to right, so we're going to start with the rightmost tab.
- function onFirstSSTabRestoring() {
- info("onFirstSSTabRestoring...");
- for (let i = gBrowser.tabs.length - 1; i >= 0; i--) {
- let tab = gBrowser.tabs[i];
- let actualUniq = ss.getTabValue(tab, "uniq");
- let expectedUniq = state.windows[0].tabs[i].extData["uniq"];
-
- if (wasLoaded[actualUniq]) {
- info("tab " + i + ": already restored");
- continue;
- }
- is(actualUniq, expectedUniq, "tab " + i + ": extData was correct");
-
- // Now we're going to set a piece of data back on the tab so it can be read
- // to test setting a value "early".
- uniq2[actualUniq] = r();
- ss.setTabValue(tab, "uniq2", uniq2[actualUniq]);
-
- // Delete the value we have for "baz". This tests that deleteTabValue
- // will delete "early access" values (c.f. bug 617175). If this doesn't throw
- // then the test is successful.
- try {
- ss.deleteTabValue(tab, "baz");
- }
- catch (e) {
- ok(false, "no error calling deleteTabValue - " + e);
- }
-
- // This will be used in the final comparison to make sure we checked the
- // same number as we set.
- uniq2Count++;
- }
- }
-
- function onLastSSTabRestoring() {
- let checked = 0;
- for (let i = 0; i < gBrowser.tabs.length; i++) {
- let tab = gBrowser.tabs[i];
- let uniq = ss.getTabValue(tab, "uniq");
-
- // Look to see if we set a uniq2 value for this uniq value
- if (uniq in uniq2) {
- is(ss.getTabValue(tab, "uniq2"), uniq2[uniq], "tab " + i + " has correct uniq2 value");
- checked++;
- }
- }
- ok(uniq2Count > 0, "at least 1 tab properly checked 'early access'");
- is(checked, uniq2Count, "checked the same number of uniq2 as we set");
- }
-
- function cleanup() {
- // remove the event listener and clean up before finishing
- gBrowser.tabContainer.removeEventListener("SSTabRestoring", onSSTabRestoring, false);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true);
- gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen, false);
- // Put this in an executeSoon because we still haven't called restoreNextTab
- // in sessionstore for the last tab (we'll call it after this). We end up
- // trying to restore the tab (since we then add a closed tab to the array).
- executeSoon(function() {
- ss.setBrowserState(stateBackup);
- executeSoon(finish);
- });
- }
-
- // Add the event listeners
- gBrowser.tabContainer.addEventListener("SSTabRestoring", onSSTabRestoring, false);
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
- gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen, false);
- // Restore state
- ss.setBrowserState(JSON.stringify(state));
-}
diff --git a/browser/components/sessionstore/test/browser_590563.js b/browser/components/sessionstore/test/browser_590563.js
deleted file mode 100644
index 5d1d8f866..000000000
--- a/browser/components/sessionstore/test/browser_590563.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- let sessionData = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:mozilla" }], hidden: true },
- { entries: [{ url: "about:blank" }], hidden: false }
- ]
- }]
- };
- let url = "about:sessionrestore";
- let formdata = {id: {sessionData}, url};
- let state = { windows: [{ tabs: [{ entries: [{url}], formdata }] }] };
-
- waitForExplicitFinish();
-
- newWindowWithState(state, function (win) {
- registerCleanupFunction(() => BrowserTestUtils.closeWindow(win));
-
- is(gBrowser.tabs.length, 1, "The total number of tabs should be 1");
- is(gBrowser.visibleTabs.length, 1, "The total number of visible tabs should be 1");
-
- executeSoon(function () {
- waitForFocus(function () {
- middleClickTest(win);
- finish();
- }, win);
- });
- });
-}
-
-function middleClickTest(win) {
- let browser = win.gBrowser.selectedBrowser;
- let tree = browser.contentDocument.getElementById("tabList");
- is(tree.view.rowCount, 3, "There should be three items");
-
- // click on the first tab item
- var rect = tree.treeBoxObject.getCoordsForCellItem(1, tree.columns[1], "text");
- EventUtils.synthesizeMouse(tree.body, rect.x, rect.y, { button: 1 },
- browser.contentWindow);
- // click on the second tab item
- rect = tree.treeBoxObject.getCoordsForCellItem(2, tree.columns[1], "text");
- EventUtils.synthesizeMouse(tree.body, rect.x, rect.y, { button: 1 },
- browser.contentWindow);
-
- is(win.gBrowser.tabs.length, 3,
- "The total number of tabs should be 3 after restoring 2 tabs by middle click.");
- is(win.gBrowser.visibleTabs.length, 3,
- "The total number of visible tabs should be 3 after restoring 2 tabs by middle click");
-}
-
-function newWindowWithState(state, callback) {
- let opts = "chrome,all,dialog=no,height=800,width=800";
- let win = window.openDialog(getBrowserURL(), "_blank", opts);
-
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
-
- let tab = win.gBrowser.selectedTab;
-
- // The form data will be restored before SSTabRestored, so we want to listen
- // for that on the currently selected tab (it will be reused)
- tab.addEventListener("SSTabRestored", function onRestored() {
- tab.removeEventListener("SSTabRestored", onRestored, true);
- callback(win);
- }, true);
-
- executeSoon(function () {
- ss.setWindowState(win, JSON.stringify(state), true);
- });
- }, false);
-}
diff --git a/browser/components/sessionstore/test/browser_595601-restore_hidden.js b/browser/components/sessionstore/test/browser_595601-restore_hidden.js
deleted file mode 100644
index 4c2b2d24a..000000000
--- a/browser/components/sessionstore/test/browser_595601-restore_hidden.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var state = {windows:[{tabs:[
- {entries:[{url:"http://example.com#1"}]},
- {entries:[{url:"http://example.com#2"}]},
- {entries:[{url:"http://example.com#3"}]},
- {entries:[{url:"http://example.com#4"}]},
- {entries:[{url:"http://example.com#5"}], hidden: true},
- {entries:[{url:"http://example.com#6"}], hidden: true},
- {entries:[{url:"http://example.com#7"}], hidden: true},
- {entries:[{url:"http://example.com#8"}], hidden: true}
-]}]};
-
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(2);
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.restore_hidden_tabs");
- });
-
- // First stage: restoreHiddenTabs = true
- // Second stage: restoreHiddenTabs = false
- test_loadTabs(true, function () {
- test_loadTabs(false, finish);
- });
-}
-
-function test_loadTabs(restoreHiddenTabs, callback) {
- Services.prefs.setBoolPref("browser.sessionstore.restore_hidden_tabs", restoreHiddenTabs);
-
- let expectedTabs = restoreHiddenTabs ? 8 : 4;
- let firstProgress = true;
-
- newWindowWithState(state, function (win, needsRestore, isRestoring) {
- if (firstProgress) {
- firstProgress = false;
- is(isRestoring, 3, "restoring 3 tabs concurrently");
- } else {
- ok(isRestoring < 4, "restoring max. 3 tabs concurrently");
- }
-
- // We're explicity checking for (isRestoring == 1) here because the test
- // progress listener is called before the session store one. So when we're
- // called with one tab left to restore we know that the last tab has
- // finished restoring and will soon be handled by the SS listener.
- let tabsNeedingRestore = win.gBrowser.tabs.length - needsRestore;
- if (isRestoring == 1 && tabsNeedingRestore == expectedTabs) {
- is(win.gBrowser.visibleTabs.length, 4, "only 4 visible tabs");
-
- TabsProgressListener.uninit();
- executeSoon(callback);
- }
- });
-}
-
-var TabsProgressListener = {
- init: function (win) {
- this.window = win;
- Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false);
- },
-
- uninit: function () {
- Services.obs.removeObserver(this, "sessionstore-debug-tab-restored");
-
- delete this.window;
- delete this.callback;
- },
-
- setCallback: function (callback) {
- this.callback = callback;
- },
-
- observe: function (browser) {
- TabsProgressListener.onRestored(browser);
- },
-
- onRestored: function (browser) {
- if (this.callback && browser.__SS_restoreState == TAB_STATE_RESTORING)
- this.callback.apply(null, [this.window].concat(this.countTabs()));
- },
-
- countTabs: function () {
- let needsRestore = 0, isRestoring = 0;
-
- for (let i = 0; i < this.window.gBrowser.tabs.length; i++) {
- let browser = this.window.gBrowser.tabs[i].linkedBrowser;
- if (browser.__SS_restoreState == TAB_STATE_RESTORING)
- isRestoring++;
- else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE)
- needsRestore++;
- }
-
- return [needsRestore, isRestoring];
- }
-}
-
-// ----------
-function newWindowWithState(state, callback) {
- let opts = "chrome,all,dialog=no,height=800,width=800";
- let win = window.openDialog(getBrowserURL(), "_blank", opts);
-
- registerCleanupFunction(() => BrowserTestUtils.closeWindow(win));
-
- whenWindowLoaded(win, function onWindowLoaded(aWin) {
- TabsProgressListener.init(aWin);
- TabsProgressListener.setCallback(callback);
-
- ss.setWindowState(aWin, JSON.stringify(state), true);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_597071.js b/browser/components/sessionstore/test/browser_597071.js
deleted file mode 100644
index f8ddaaf54..000000000
--- a/browser/components/sessionstore/test/browser_597071.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Bug 597071 - Closed windows should only be resurrected when there is a single
- * popup window
- */
-add_task(function test_close_last_nonpopup_window() {
- // Purge the list of closed windows.
- forgetClosedWindows();
-
- let oldState = ss.getWindowState(window);
-
- let popupState = {windows: [
- {tabs: [{entries: []}], isPopup: true, hidden: "toolbar"}
- ]};
-
- // Set this window to be a popup.
- ss.setWindowState(window, JSON.stringify(popupState), true);
-
- // Open a new window with a tab.
- let win = yield BrowserTestUtils.openNewBrowserWindow({private: false});
- let tab = win.gBrowser.addTab("http://example.com/");
- yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
-
- // Make sure sessionstore sees this window.
- let state = JSON.parse(ss.getBrowserState());
- is(state.windows.length, 2, "sessionstore knows about this window");
-
- // Closed the window and check the closed window count.
- yield BrowserTestUtils.closeWindow(win);
- is(ss.getClosedWindowCount(), 1, "correct closed window count");
-
- // Cleanup.
- ss.setWindowState(window, oldState, true);
-});
diff --git a/browser/components/sessionstore/test/browser_599909.js b/browser/components/sessionstore/test/browser_599909.js
deleted file mode 100644
index 1d2c411fe..000000000
--- a/browser/components/sessionstore/test/browser_599909.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/* 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/. */
-
-var stateBackup = ss.getBrowserState();
-
-function cleanup() {
- // Reset the pref
- try {
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
- } catch (e) {}
- ss.setBrowserState(stateBackup);
- executeSoon(finish);
-}
-
-function test() {
- /** Bug 599909 - to-be-reloaded tabs don't show up in switch-to-tab **/
- waitForExplicitFinish();
-
- // Set the pref to true so we know exactly how many tabs should be restoring at
- // any given time. This guarantees that a finishing load won't start another.
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org/#1" }] },
- { entries: [{ url: "http://example.org/#2" }] },
- { entries: [{ url: "http://example.org/#3" }] },
- { entries: [{ url: "http://example.org/#4" }] }
- ], selected: 1 }] };
-
- let tabsForEnsure = {};
- state.windows[0].tabs.forEach(function(tab) {
- tabsForEnsure[tab.entries[0].url] = 1;
- });
-
- let tabsRestoring = 0;
- let tabsRestored = 0;
-
- function handleEvent(aEvent) {
- if (aEvent.type == "SSTabRestoring")
- tabsRestoring++;
- else
- tabsRestored++;
-
- if (tabsRestoring < state.windows[0].tabs.length ||
- tabsRestored < 1)
- return;
-
- gBrowser.tabContainer.removeEventListener("SSTabRestoring", handleEvent, true);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", handleEvent, true);
- executeSoon(function() {
- checkAutocompleteResults(tabsForEnsure, cleanup);
- });
- }
-
- // currentURI is set before SSTabRestoring is fired, so we can sucessfully check
- // after that has fired for all tabs. Since 1 tab will be restored though, we
- // also need to wait for 1 SSTabRestored since currentURI will be set, unset, then set.
- gBrowser.tabContainer.addEventListener("SSTabRestoring", handleEvent, true);
- gBrowser.tabContainer.addEventListener("SSTabRestored", handleEvent, true);
- ss.setBrowserState(JSON.stringify(state));
-}
-
-// The following was taken from browser/base/content/test/general/browser_tabMatchesInAwesomebar.js
-// so that we could do the same sort of checking.
-var gController = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
-function checkAutocompleteResults(aExpected, aCallback) {
- gController.input = {
- timeout: 10,
- textValue: "",
- searches: ["unifiedcomplete"],
- searchParam: "enable-actions",
- popupOpen: false,
- minResultsForPopup: 0,
- invalidate: function() {},
- disableAutoComplete: false,
- completeDefaultIndex: false,
- get popup() { return this; },
- onSearchBegin: function() {},
- onSearchComplete: function ()
- {
- info("Found " + gController.matchCount + " matches.");
- // Check to see the expected uris and titles match up (in any order)
- for (let i = 0; i < gController.matchCount; i++) {
- if (gController.getStyleAt(i).includes("heuristic")) {
- info("Skip heuristic match");
- continue;
- }
- let action = gURLBar.popup.input._parseActionUrl(gController.getValueAt(i));
- let uri = action.params.url;
-
- info("Search for '" + uri + "' in open tabs.");
- ok(uri in aExpected, "Registered open page found in autocomplete.");
- // Remove the found entry from expected results.
- delete aExpected[uri];
- }
-
- // Make sure there is no reported open page that is not open.
- for (let entry in aExpected) {
- ok(false, "'" + entry + "' not found in autocomplete.");
- }
-
- executeSoon(aCallback);
- },
- setSelectedIndex: function() {},
- get searchCount() { return this.searches.length; },
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- ])
- };
-
- info("Searching open pages.");
- gController.startSearch(Services.prefs.getCharPref("browser.urlbar.restrict.openpage"));
-}
diff --git a/browser/components/sessionstore/test/browser_600545.js b/browser/components/sessionstore/test/browser_600545.js
deleted file mode 100644
index 6852357c2..000000000
--- a/browser/components/sessionstore/test/browser_600545.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/* 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/. */
-
-requestLongerTimeout(2);
-
-var stateBackup = JSON.parse(ss.getBrowserState());
-
-function test() {
- /** Test for Bug 600545 **/
- waitForExplicitFinish();
- testBug600545();
-}
-
-function testBug600545() {
- // Set the pref to false to cause non-app tabs to be stripped out on a save
- Services.prefs.setBoolPref("browser.sessionstore.resume_from_crash", false);
- Services.prefs.setIntPref("browser.sessionstore.interval", 2000);
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.resume_from_crash");
- Services.prefs.clearUserPref("browser.sessionstore.interval");
- });
-
- // This tests the following use case: When multiple windows are open
- // and browser.sessionstore.resume_from_crash preference is false,
- // tab session data for non-active window is stripped for non-pinned
- // tabs. This occurs after "sessionstore-state-write-complete"
- // fires which will only fire in this case if there is at least one
- // pinned tab.
- let state = { windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org#0" }], pinned:true },
- { entries: [{ url: "http://example.com#1" }] },
- { entries: [{ url: "http://example.com#2" }] },
- ],
- selected: 2
- },
- {
- tabs: [
- { entries: [{ url: "http://example.com#3" }] },
- { entries: [{ url: "http://example.com#4" }] },
- { entries: [{ url: "http://example.com#5" }] },
- { entries: [{ url: "http://example.com#6" }] }
- ],
- selected: 3
- }
- ] };
-
- waitForBrowserState(state, function() {
- // Need to wait for SessionStore's saveState function to be called
- // so that non-pinned tabs will be stripped from non-active window
- waitForSaveState(function () {
- let expectedNumberOfTabs = getStateTabCount(state);
- let retrievedState = JSON.parse(ss.getBrowserState());
- let actualNumberOfTabs = getStateTabCount(retrievedState);
-
- is(actualNumberOfTabs, expectedNumberOfTabs,
- "Number of tabs in retreived session data, matches number of tabs set.");
-
- done();
- });
- });
-}
-
-function done() {
- // Enumerate windows and close everything but our primary window. We can't
- // use waitForFocus() because apparently it's buggy. See bug 599253.
- let windowsEnum = Services.wm.getEnumerator("navigator:browser");
- let closeWinPromises = [];
- while (windowsEnum.hasMoreElements()) {
- let currentWindow = windowsEnum.getNext();
- if (currentWindow != window)
- closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow));
- }
-
- Promise.all(closeWinPromises).then(() => {
- waitForBrowserState(stateBackup, finish);
- });
-}
-
-// Count up the number of tabs in the state data
-function getStateTabCount(aState) {
- let tabCount = 0;
- for (let i in aState.windows)
- tabCount += aState.windows[i].tabs.length;
- return tabCount;
-}
diff --git a/browser/components/sessionstore/test/browser_601955.js b/browser/components/sessionstore/test/browser_601955.js
deleted file mode 100644
index 797d5d7cc..000000000
--- a/browser/components/sessionstore/test/browser_601955.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-// This tests that pinning/unpinning a tab, on its own, eventually triggers a
-// session store.
-
-function test() {
- waitForExplicitFinish();
- // We speed up the interval between session saves to ensure that the test
- // runs quickly.
- Services.prefs.setIntPref("browser.sessionstore.interval", 2000);
-
- // Loading a tab causes a save state and this is meant to catch that event.
- waitForSaveState(testBug601955_1);
-
- // Assumption: Only one window is open and it has one tab open.
- gBrowser.addTab("about:mozilla");
-}
-
-function testBug601955_1() {
- // Because pinned tabs are at the front of |gBrowser.tabs|, pinning tabs
- // re-arranges the |tabs| array.
- ok(!gBrowser.tabs[0].pinned, "first tab should not be pinned yet");
- ok(!gBrowser.tabs[1].pinned, "second tab should not be pinned yet");
-
- waitForSaveState(testBug601955_2);
- gBrowser.pinTab(gBrowser.tabs[0]);
-}
-
-function testBug601955_2() {
- let state = JSON.parse(ss.getBrowserState());
- ok(state.windows[0].tabs[0].pinned, "first tab should be pinned by now");
- ok(!state.windows[0].tabs[1].pinned, "second tab should still not be pinned");
-
- waitForSaveState(testBug601955_3);
- gBrowser.unpinTab(window.gBrowser.tabs[0]);
-}
-
-function testBug601955_3() {
- let state = JSON.parse(ss.getBrowserState());
- ok(!state.windows[0].tabs[0].pinned, "first tab should not be pinned");
- ok(!state.windows[0].tabs[1].pinned, "second tab should not be pinned");
-
- done();
-}
-
-function done() {
- gBrowser.removeTab(window.gBrowser.tabs[1]);
-
- Services.prefs.clearUserPref("browser.sessionstore.interval");
-
- executeSoon(finish);
-}
diff --git a/browser/components/sessionstore/test/browser_607016.js b/browser/components/sessionstore/test/browser_607016.js
deleted file mode 100644
index ed4b03b9c..000000000
--- a/browser/components/sessionstore/test/browser_607016.js
+++ /dev/null
@@ -1,98 +0,0 @@
-"use strict";
-
-var stateBackup = ss.getBrowserState();
-
-add_task(function* () {
- /** Bug 607016 - If a tab is never restored, attributes (eg. hidden) aren't updated correctly **/
- ignoreAllUncaughtExceptions();
-
- // Set the pref to true so we know exactly how many tabs should be restoring at
- // any given time. This guarantees that a finishing load won't start another.
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- let state = { windows: [{ tabs: [
- { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } }, // overwriting
- { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } }, // hiding
- { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } }, // adding
- { entries: [{ url: "http://example.org#5" }], extData: { "uniq": r() } }, // deleting
- { entries: [{ url: "http://example.org#6" }] } // creating
- ], selected: 1 }] };
-
- function* progressCallback() {
- let curState = JSON.parse(ss.getBrowserState());
- for (let i = 0; i < curState.windows[0].tabs.length; i++) {
- let tabState = state.windows[0].tabs[i];
- let tabCurState = curState.windows[0].tabs[i];
- if (tabState.extData) {
- is(tabCurState.extData["uniq"], tabState.extData["uniq"],
- "sanity check that tab has correct extData");
- }
- else {
- // We aren't expecting there to be any data on extData, but panorama
- // may be setting something, so we need to make sure that if we do have
- // data, we just don't have anything for "uniq".
- ok(!("extData" in tabCurState) || !("uniq" in tabCurState.extData),
- "sanity check that tab doesn't have extData or extData doesn't have 'uniq'");
- }
- }
-
- // Now we'll set a new unique value on 1 of the tabs
- let newUniq = r();
- ss.setTabValue(gBrowser.tabs[1], "uniq", newUniq);
- let tabState = JSON.parse(ss.getTabState(gBrowser.tabs[1]));
- is(tabState.extData.uniq, newUniq,
- "(overwriting) new data is stored in extData");
-
- // hide the next tab before closing it
- gBrowser.hideTab(gBrowser.tabs[2]);
- tabState = JSON.parse(ss.getTabState(gBrowser.tabs[2]));
- ok(tabState.hidden, "(hiding) tab data has hidden == true");
-
- // set data that's not in a conflicting key
- let stillUniq = r();
- ss.setTabValue(gBrowser.tabs[3], "stillUniq", stillUniq);
- tabState = JSON.parse(ss.getTabState(gBrowser.tabs[3]));
- is(tabState.extData.stillUniq, stillUniq,
- "(adding) new data is stored in extData");
-
- // remove the uniq value and make sure it's not there in the closed data
- ss.deleteTabValue(gBrowser.tabs[4], "uniq");
- tabState = JSON.parse(ss.getTabState(gBrowser.tabs[4]));
- // Since Panorama might have put data in, first check if there is extData.
- // If there is explicitly check that "uniq" isn't in it. Otherwise, we're ok
- if ("extData" in tabState) {
- ok(!("uniq" in tabState.extData),
- "(deleting) uniq not in existing extData");
- }
- else {
- ok(true, "(deleting) no data is stored in extData");
- }
-
- // set unique data on the tab that never had any set, make sure that's saved
- let newUniq2 = r();
- ss.setTabValue(gBrowser.tabs[5], "uniq", newUniq2);
- tabState = JSON.parse(ss.getTabState(gBrowser.tabs[5]));
- is(tabState.extData.uniq, newUniq2,
- "(creating) new data is stored in extData where there was none");
-
- while (gBrowser.tabs.length > 1) {
- yield promiseRemoveTab(gBrowser.tabs[1]);
- }
- }
-
- // Set the test state.
- ss.setBrowserState(JSON.stringify(state));
-
- // Wait until the selected tab is restored and all others are pending.
- yield Promise.all(Array.map(gBrowser.tabs, tab => {
- return (tab == gBrowser.selectedTab) ?
- promiseTabRestored(tab) : promiseTabRestoring(tab)
- }));
-
- // Kick off the actual tests.
- yield progressCallback();
-
- // Cleanup.
- yield promiseBrowserState(stateBackup);
-});
diff --git a/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js b/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js
deleted file mode 100644
index 0b6b8faa6..000000000
--- a/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js
+++ /dev/null
@@ -1,361 +0,0 @@
-/* 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/. */
-
-const stateBackup = JSON.parse(ss.getBrowserState());
-const testState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:blank" }] },
- { entries: [{ url: "about:rights" }] }
- ]
- }]
-};
-const lameMultiWindowState = { windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } }
- ],
- selected: 1
- },
- {
- tabs: [
- { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } },
- { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } },
- ],
- selected: 3
- }
- ] };
-
-
-function getOuterWindowID(aWindow) {
- return aWindow.QueryInterface(Ci.nsIInterfaceRequestor).
- getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
-}
-
-function test() {
- /** Test for Bug 615394 - Session Restore should notify when it is beginning and ending a restore **/
- waitForExplicitFinish();
- // Preemptively extend the timeout to prevent [orange]
- requestLongerTimeout(4);
- runNextTest();
-}
-
-
-var tests = [
- test_setTabState,
- test_duplicateTab,
- test_undoCloseTab,
- test_setWindowState,
- test_setBrowserState,
- test_undoCloseWindow
-];
-function runNextTest() {
- // set an empty state & run the next test, or finish
- if (tests.length) {
- // Enumerate windows and close everything but our primary window. We can't
- // use waitForFocus() because apparently it's buggy. See bug 599253.
- var windowsEnum = Services.wm.getEnumerator("navigator:browser");
- let closeWinPromises = [];
- while (windowsEnum.hasMoreElements()) {
- var currentWindow = windowsEnum.getNext();
- if (currentWindow != window) {
- closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow));
- }
- }
-
- Promise.all(closeWinPromises).then(() => {
- let currentTest = tests.shift();
- info("prepping for " + currentTest.name);
- waitForBrowserState(testState, currentTest);
- });
- }
- else {
- waitForBrowserState(stateBackup, finish);
- }
-}
-
-/** ACTUAL TESTS **/
-
-function test_setTabState() {
- let tab = gBrowser.tabs[1];
- let newTabState = JSON.stringify({ entries: [{ url: "http://example.org" }], extData: { foo: "bar" } });
- let busyEventCount = 0;
- let readyEventCount = 0;
-
- function onSSWindowStateBusy(aEvent) {
- busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- readyEventCount++;
- is(ss.getTabValue(tab, "foo"), "bar");
- ss.setTabValue(tab, "baz", "qux");
- }
-
- function onSSTabRestored(aEvent) {
- is(busyEventCount, 1);
- is(readyEventCount, 1);
- is(ss.getTabValue(tab, "baz"), "qux");
- is(tab.linkedBrowser.currentURI.spec, "http://example.org/");
-
- window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
-
- runNextTest();
- }
-
- window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
- ss.setTabState(tab, newTabState);
-}
-
-
-function test_duplicateTab() {
- let tab = gBrowser.tabs[1];
- let busyEventCount = 0;
- let readyEventCount = 0;
- let newTab;
-
- // We'll look to make sure this value is on the duplicated tab
- ss.setTabValue(tab, "foo", "bar");
-
- function onSSWindowStateBusy(aEvent) {
- busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- newTab = gBrowser.tabs[2];
- readyEventCount++;
- is(ss.getTabValue(newTab, "foo"), "bar");
- ss.setTabValue(newTab, "baz", "qux");
- }
-
- function onSSTabRestored(aEvent) {
- is(busyEventCount, 1);
- is(readyEventCount, 1);
- is(ss.getTabValue(newTab, "baz"), "qux");
- is(newTab.linkedBrowser.currentURI.spec, "about:rights");
-
- window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
-
- runNextTest();
- }
-
- window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
-
- newTab = ss.duplicateTab(window, tab);
-}
-
-
-function test_undoCloseTab() {
- let tab = gBrowser.tabs[1],
- busyEventCount = 0,
- readyEventCount = 0,
- reopenedTab;
-
- ss.setTabValue(tab, "foo", "bar");
-
- function onSSWindowStateBusy(aEvent) {
- busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- reopenedTab = gBrowser.tabs[1];
- readyEventCount++;
- is(ss.getTabValue(reopenedTab, "foo"), "bar");
- ss.setTabValue(reopenedTab, "baz", "qux");
- }
-
- function onSSTabRestored(aEvent) {
- is(busyEventCount, 1);
- is(readyEventCount, 1);
- is(ss.getTabValue(reopenedTab, "baz"), "qux");
- is(reopenedTab.linkedBrowser.currentURI.spec, "about:rights");
-
- window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
-
- runNextTest();
- }
-
- window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
-
- gBrowser.removeTab(tab);
- reopenedTab = ss.undoCloseTab(window, 0);
-}
-
-
-function test_setWindowState() {
- let testState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:mozilla" }], extData: { "foo": "bar" } },
- { entries: [{ url: "http://example.org" }], extData: { "baz": "qux" } }
- ]
- }]
- };
-
- let busyEventCount = 0,
- readyEventCount = 0,
- tabRestoredCount = 0;
-
- function onSSWindowStateBusy(aEvent) {
- busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- readyEventCount++;
- is(ss.getTabValue(gBrowser.tabs[0], "foo"), "bar");
- is(ss.getTabValue(gBrowser.tabs[1], "baz"), "qux");
- }
-
- function onSSTabRestored(aEvent) {
- if (++tabRestoredCount < 2)
- return;
-
- is(busyEventCount, 1);
- is(readyEventCount, 1);
- is(gBrowser.tabs[0].linkedBrowser.currentURI.spec, "about:mozilla");
- is(gBrowser.tabs[1].linkedBrowser.currentURI.spec, "http://example.org/");
-
- window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
-
- runNextTest();
- }
-
- window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
-
- ss.setWindowState(window, JSON.stringify(testState), true);
-}
-
-
-function test_setBrowserState() {
- // We'll track events per window so we are sure that they are each happening once
- // pre window.
- let windowEvents = {};
- windowEvents[getOuterWindowID(window)] = { busyEventCount: 0, readyEventCount: 0 };
-
- // waitForBrowserState does it's own observing for windows, but doesn't attach
- // the listeners we want here, so do it ourselves.
- let newWindow;
- function windowObserver(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
- newWindow.addEventListener("load", function() {
- newWindow.removeEventListener("load", arguments.callee, false);
-
- Services.ww.unregisterNotification(windowObserver);
-
- windowEvents[getOuterWindowID(newWindow)] = { busyEventCount: 0, readyEventCount: 0 };
-
- newWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- newWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- }, false);
- }
- }
-
- function onSSWindowStateBusy(aEvent) {
- windowEvents[getOuterWindowID(aEvent.originalTarget)].busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- windowEvents[getOuterWindowID(aEvent.originalTarget)].readyEventCount++;
- }
-
- window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- Services.ww.registerNotification(windowObserver);
-
- waitForBrowserState(lameMultiWindowState, function() {
- let checkedWindows = 0;
- for (let id of Object.keys(windowEvents)) {
- let winEvents = windowEvents[id];
- is(winEvents.busyEventCount, 1,
- "[test_setBrowserState] window" + id + " busy event count correct");
- is(winEvents.readyEventCount, 1,
- "[test_setBrowserState] window" + id + " ready event count correct");
- checkedWindows++;
- }
- is(checkedWindows, 2,
- "[test_setBrowserState] checked 2 windows");
- window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- newWindow.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- newWindow.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- runNextTest();
- });
-}
-
-
-function test_undoCloseWindow() {
- let newWindow, reopenedWindow;
-
- function firstWindowObserver(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
- Services.ww.unregisterNotification(firstWindowObserver);
- }
- }
- Services.ww.registerNotification(firstWindowObserver);
-
- waitForBrowserState(lameMultiWindowState, function() {
- // Close the window which isn't window
- BrowserTestUtils.closeWindow(newWindow).then(() => {
- // Now give it time to close
- reopenedWindow = ss.undoCloseWindow(0);
- reopenedWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- reopenedWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false);
-
- reopenedWindow.addEventListener("load", function() {
- reopenedWindow.removeEventListener("load", arguments.callee, false);
-
- reopenedWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
- }, false);
- });
- });
-
- let busyEventCount = 0,
- readyEventCount = 0,
- tabRestoredCount = 0;
- // These will listen to the reopened closed window...
- function onSSWindowStateBusy(aEvent) {
- busyEventCount++;
- }
-
- function onSSWindowStateReady(aEvent) {
- readyEventCount++;
- }
-
- function onSSTabRestored(aEvent) {
- if (++tabRestoredCount < 4)
- return;
-
- is(busyEventCount, 1);
- is(readyEventCount, 1);
-
- reopenedWindow.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false);
- reopenedWindow.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false);
- reopenedWindow.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
-
- BrowserTestUtils.closeWindow(reopenedWindow).then(runNextTest);
- }
-}
diff --git a/browser/components/sessionstore/test/browser_618151.js b/browser/components/sessionstore/test/browser_618151.js
deleted file mode 100644
index bdc268e6c..000000000
--- a/browser/components/sessionstore/test/browser_618151.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* 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/. */
-
-const stateBackup = ss.getBrowserState();
-const testState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:blank" }] },
- { entries: [{ url: "about:mozilla" }] }
- ]
- }]
-};
-
-
-function test() {
- /** Test for Bug 618151 - Overwriting state can lead to unrestored tabs **/
- waitForExplicitFinish();
- runNextTest();
-}
-
-// Just a subset of tests from bug 615394 that causes a timeout.
-var tests = [test_setup, test_hang];
-function runNextTest() {
- // set an empty state & run the next test, or finish
- if (tests.length) {
- // Enumerate windows and close everything but our primary window. We can't
- // use waitForFocus() because apparently it's buggy. See bug 599253.
- var windowsEnum = Services.wm.getEnumerator("navigator:browser");
- let closeWinPromises = [];
- while (windowsEnum.hasMoreElements()) {
- var currentWindow = windowsEnum.getNext();
- if (currentWindow != window) {
- closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow));
- }
- }
-
- Promise.all(closeWinPromises).then(() => {
- let currentTest = tests.shift();
- info("running " + currentTest.name);
- waitForBrowserState(testState, currentTest);
- });
- }
- else {
- ss.setBrowserState(stateBackup);
- executeSoon(finish);
- }
-}
-
-function test_setup() {
- function onSSTabRestored(aEvent) {
- gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
- runNextTest();
- }
-
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
- ss.setTabState(gBrowser.tabs[1], JSON.stringify({
- entries: [{ url: "http://example.org" }],
- extData: { foo: "bar" } }));
-}
-
-function test_hang() {
- ok(true, "test didn't time out");
- runNextTest();
-}
diff --git a/browser/components/sessionstore/test/browser_623779.js b/browser/components/sessionstore/test/browser_623779.js
deleted file mode 100644
index 267bccb2d..000000000
--- a/browser/components/sessionstore/test/browser_623779.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-add_task(function* () {
- gBrowser.pinTab(gBrowser.selectedTab);
-
- let newTab = gBrowser.duplicateTab(gBrowser.selectedTab);
- yield promiseTabRestored(newTab);
-
- ok(!newTab.pinned, "duplicating a pinned tab creates unpinned tab");
- yield promiseRemoveTab(newTab);
-
- gBrowser.unpinTab(gBrowser.selectedTab);
-});
diff --git a/browser/components/sessionstore/test/browser_624727.js b/browser/components/sessionstore/test/browser_624727.js
deleted file mode 100644
index 85d6ff042..000000000
--- a/browser/components/sessionstore/test/browser_624727.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var TEST_STATE = { windows: [{ tabs: [{ url: "about:blank" }] }] };
-
-add_task(function* () {
- function assertNumberOfTabs(num, msg) {
- is(gBrowser.tabs.length, num, msg);
- }
-
- function assertNumberOfPinnedTabs(num, msg) {
- is(gBrowser._numPinnedTabs, num, msg);
- }
-
- // check prerequisites
- assertNumberOfTabs(1, "we start off with one tab");
- assertNumberOfPinnedTabs(0, "no pinned tabs so far");
-
- // setup
- gBrowser.addTab("about:blank");
- assertNumberOfTabs(2, "there are two tabs, now");
-
- let [tab1, tab2] = gBrowser.tabs;
- let linkedBrowser = tab1.linkedBrowser;
- gBrowser.pinTab(tab1);
- gBrowser.pinTab(tab2);
- assertNumberOfPinnedTabs(2, "both tabs are now pinned");
-
- // run the test
- yield promiseBrowserState(TEST_STATE);
-
- assertNumberOfTabs(1, "one tab left after setBrowserState()");
- assertNumberOfPinnedTabs(0, "there are no pinned tabs");
- is(gBrowser.tabs[0].linkedBrowser, linkedBrowser, "first tab's browser got re-used");
-});
diff --git a/browser/components/sessionstore/test/browser_625016.js b/browser/components/sessionstore/test/browser_625016.js
deleted file mode 100644
index b551fcbb3..000000000
--- a/browser/components/sessionstore/test/browser_625016.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- /** Test for Bug 625016 - Restore windows closed in succession to quit (non-OSX only) **/
-
- // We'll test this by opening a new window, waiting for the save
- // event, then closing that window. We'll observe the
- // "sessionstore-state-write-complete" notification and check that
- // the state contains no _closedWindows. We'll then add a new tab
- // and make sure that the state following that was reset and the
- // closed window is now in _closedWindows.
-
- requestLongerTimeout(2);
-
- yield forceSaveState();
-
- // We'll clear all closed windows to make sure our state is clean
- // forgetClosedWindow doesn't trigger a delayed save
- forgetClosedWindows();
- is(ss.getClosedWindowCount(), 0, "starting with no closed windows");
-});
-
-add_task(function* new_window() {
- let newWin;
- try {
- newWin = yield promiseNewWindowLoaded();
- let tab = newWin.gBrowser.addTab("http://example.com/browser_625016.js?" + Math.random());
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // Double check that we have no closed windows
- is(ss.getClosedWindowCount(), 0, "no closed windows on first save");
-
- yield BrowserTestUtils.closeWindow(newWin);
- newWin = null;
-
- let state = JSON.parse((yield promiseRecoveryFileContents()));
- is(state.windows.length, 2,
- "observe1: 2 windows in data written to disk");
- is(state._closedWindows.length, 0,
- "observe1: no closed windows in data written to disk");
-
- // The API still treats the closed window as closed, so ensure that window is there
- is(ss.getClosedWindowCount(), 1,
- "observe1: 1 closed window according to API");
- } finally {
- if (newWin) {
- yield BrowserTestUtils.closeWindow(newWin);
- }
- yield forceSaveState();
- }
-});
-
-// We'll open a tab, which should trigger another state save which would wipe
-// the _shouldRestore attribute from the closed window
-add_task(function* new_tab() {
- let newTab;
- try {
- newTab = gBrowser.addTab("about:mozilla");
-
- let state = JSON.parse((yield promiseRecoveryFileContents()));
- is(state.windows.length, 1,
- "observe2: 1 window in data being written to disk");
- is(state._closedWindows.length, 1,
- "observe2: 1 closed window in data being written to disk");
-
- // The API still treats the closed window as closed, so ensure that window is there
- is(ss.getClosedWindowCount(), 1,
- "observe2: 1 closed window according to API");
- } finally {
- gBrowser.removeTab(newTab);
- }
-});
-
-
-add_task(function* done() {
- // The API still represents the closed window as closed, so we can clear it
- // with the API, but just to make sure...
-// is(ss.getClosedWindowCount(), 1, "1 closed window according to API");
- forgetClosedWindows();
- Services.prefs.clearUserPref("browser.sessionstore.interval");
-});
diff --git a/browser/components/sessionstore/test/browser_628270.js b/browser/components/sessionstore/test/browser_628270.js
deleted file mode 100644
index f552cbfda..000000000
--- a/browser/components/sessionstore/test/browser_628270.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- let assertNumberOfTabs = function (num, msg) {
- is(gBrowser.tabs.length, num, msg);
- }
-
- let assertNumberOfVisibleTabs = function (num, msg) {
- is(gBrowser.visibleTabs.length, num, msg);
- }
-
- let assertNumberOfPinnedTabs = function (num, msg) {
- is(gBrowser._numPinnedTabs, num, msg);
- }
-
- waitForExplicitFinish();
-
- // check prerequisites
- assertNumberOfTabs(1, "we start off with one tab");
-
- // setup
- let tab = gBrowser.addTab("about:mozilla");
-
- whenTabIsLoaded(tab, function () {
- // hide the newly created tab
- assertNumberOfVisibleTabs(2, "there are two visible tabs");
- gBrowser.showOnlyTheseTabs([gBrowser.tabs[0]]);
- assertNumberOfVisibleTabs(1, "there is one visible tab");
- ok(tab.hidden, "newly created tab is now hidden");
-
- // close and restore hidden tab
- promiseRemoveTab(tab).then(() => {
- tab = ss.undoCloseTab(window, 0);
-
- // check that everything was restored correctly, clean up and finish
- whenTabIsLoaded(tab, function () {
- is(tab.linkedBrowser.currentURI.spec, "about:mozilla", "restored tab has correct url");
-
- gBrowser.removeTab(tab);
- finish();
- });
- });
- });
-}
-
-function whenTabIsLoaded(tab, callback) {
- tab.linkedBrowser.addEventListener("load", function onLoad() {
- tab.linkedBrowser.removeEventListener("load", onLoad, true);
- callback();
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_635418.js b/browser/components/sessionstore/test/browser_635418.js
deleted file mode 100644
index 3b21c5b0f..000000000
--- a/browser/components/sessionstore/test/browser_635418.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* 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/. */
-
-// This tests that hiding/showing a tab, on its own, eventually triggers a
-// session store.
-
-function test() {
- waitForExplicitFinish();
-
- // We speed up the interval between session saves to ensure that the test
- // runs quickly.
- Services.prefs.setIntPref("browser.sessionstore.interval", 2000);
-
- // Loading a tab causes a save state and this is meant to catch that event.
- waitForSaveState(testBug635418_1);
-
- // Assumption: Only one window is open and it has one tab open.
- gBrowser.addTab("about:mozilla");
-}
-
-function testBug635418_1() {
- ok(!gBrowser.tabs[0].hidden, "first tab should not be hidden");
- ok(!gBrowser.tabs[1].hidden, "second tab should not be hidden");
-
- waitForSaveState(testBug635418_2);
-
- // We can't hide the selected tab, so hide the new one
- gBrowser.hideTab(gBrowser.tabs[1]);
-}
-
-function testBug635418_2() {
- let state = JSON.parse(ss.getBrowserState());
- ok(!state.windows[0].tabs[0].hidden, "first tab should still not be hidden");
- ok(state.windows[0].tabs[1].hidden, "second tab should be hidden by now");
-
- waitForSaveState(testBug635418_3);
- gBrowser.showTab(gBrowser.tabs[1]);
-}
-
-function testBug635418_3() {
- let state = JSON.parse(ss.getBrowserState());
- ok(!state.windows[0].tabs[0].hidden, "first tab should still still not be hidden");
- ok(!state.windows[0].tabs[1].hidden, "second tab should not be hidden again");
-
- done();
-}
-
-function done() {
- gBrowser.removeTab(window.gBrowser.tabs[1]);
-
- Services.prefs.clearUserPref("browser.sessionstore.interval");
-
- executeSoon(finish);
-}
diff --git a/browser/components/sessionstore/test/browser_636279.js b/browser/components/sessionstore/test/browser_636279.js
deleted file mode 100644
index 250995606..000000000
--- a/browser/components/sessionstore/test/browser_636279.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var stateBackup = ss.getBrowserState();
-
-var statePinned = {windows:[{tabs:[
- {entries:[{url:"http://example.com#1"}], pinned: true}
-]}]};
-
-var state = {windows:[{tabs:[
- {entries:[{url:"http://example.com#1"}]},
- {entries:[{url:"http://example.com#2"}]},
- {entries:[{url:"http://example.com#3"}]},
- {entries:[{url:"http://example.com#4"}]},
-]}]};
-
-function test() {
- waitForExplicitFinish();
-
- registerCleanupFunction(function () {
- TabsProgressListener.uninit();
- ss.setBrowserState(stateBackup);
- });
-
-
- TabsProgressListener.init();
-
- window.addEventListener("SSWindowStateReady", function onReady() {
- window.removeEventListener("SSWindowStateReady", onReady, false);
-
- let firstProgress = true;
-
- TabsProgressListener.setCallback(function (needsRestore, isRestoring) {
- if (firstProgress) {
- firstProgress = false;
- is(isRestoring, 3, "restoring 3 tabs concurrently");
- } else {
- ok(isRestoring <= 3, "restoring max. 2 tabs concurrently");
- }
-
- if (0 == needsRestore) {
- TabsProgressListener.unsetCallback();
- waitForFocus(finish);
- }
- });
-
- ss.setBrowserState(JSON.stringify(state));
- }, false);
-
- ss.setBrowserState(JSON.stringify(statePinned));
-}
-
-function countTabs() {
- let needsRestore = 0, isRestoring = 0;
- let windowsEnum = Services.wm.getEnumerator("navigator:browser");
-
- while (windowsEnum.hasMoreElements()) {
- let window = windowsEnum.getNext();
- if (window.closed)
- continue;
-
- for (let i = 0; i < window.gBrowser.tabs.length; i++) {
- let browser = window.gBrowser.tabs[i].linkedBrowser;
- if (browser.__SS_restoreState == TAB_STATE_RESTORING)
- isRestoring++;
- else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE)
- needsRestore++;
- }
- }
-
- return [needsRestore, isRestoring];
-}
-
-var TabsProgressListener = {
- init: function () {
- Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false);
- },
-
- uninit: function () {
- Services.obs.removeObserver(this, "sessionstore-debug-tab-restored");
- this.unsetCallback();
- },
-
- setCallback: function (callback) {
- this.callback = callback;
- },
-
- unsetCallback: function () {
- delete this.callback;
- },
-
- observe: function (browser, topic, data) {
- TabsProgressListener.onRestored(browser);
- },
-
- onRestored: function (browser) {
- if (this.callback && browser.__SS_restoreState == TAB_STATE_RESTORING) {
- this.callback.apply(null, countTabs());
- }
- }
-}
diff --git a/browser/components/sessionstore/test/browser_637020.js b/browser/components/sessionstore/test/browser_637020.js
deleted file mode 100644
index 1c1f357d7..000000000
--- a/browser/components/sessionstore/test/browser_637020.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const TEST_URL = "http://mochi.test:8888/browser/browser/components/" +
- "sessionstore/test/browser_637020_slow.sjs";
-
-const TEST_STATE = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:mozilla" }] },
- { entries: [{ url: "about:robots" }] }
- ]
- }, {
- tabs: [
- { entries: [{ url: TEST_URL }] },
- { entries: [{ url: TEST_URL }] }
- ]
- }]
-};
-
-/**
- * This test ensures that windows that have just been restored will be marked
- * as dirty, otherwise _getCurrentState() might ignore them when collecting
- * state for the first time and we'd just save them as empty objects.
- *
- * The dirty state acts as a cache to not collect data from all windows all the
- * time, so at the beginning, each window must be dirty so that we collect
- * their state at least once.
- */
-
-add_task(function* test() {
- // Wait until the new window has been opened.
- let promiseWindow = new Promise(resolve => {
- Services.obs.addObserver(function onOpened(subject) {
- Services.obs.removeObserver(onOpened, "domwindowopened");
- resolve(subject);
- }, "domwindowopened", false);
- });
-
- // Set the new browser state that will
- // restore a window with two slowly loading tabs.
- let backupState = SessionStore.getBrowserState();
- SessionStore.setBrowserState(JSON.stringify(TEST_STATE));
- let win = yield promiseWindow;
-
- // The window has now been opened. Check the state that is returned,
- // this should come from the cache while the window isn't restored, yet.
- info("the window has been opened");
- checkWindows();
-
- // The history has now been restored and the tabs are loading. The data must
- // now come from the window, if it's correctly been marked as dirty before.
- yield new Promise(resolve => whenDelayedStartupFinished(win, resolve));
- info("the delayed startup has finished");
- checkWindows();
-
- // Cleanup.
- yield BrowserTestUtils.closeWindow(win);
- yield promiseBrowserState(backupState);
-});
-
-function checkWindows() {
- let state = JSON.parse(SessionStore.getBrowserState());
- is(state.windows[0].tabs.length, 2, "first window has two tabs");
- is(state.windows[1].tabs.length, 2, "second window has two tabs");
-}
diff --git a/browser/components/sessionstore/test/browser_637020_slow.sjs b/browser/components/sessionstore/test/browser_637020_slow.sjs
deleted file mode 100644
index 41da3c2ad..000000000
--- a/browser/components/sessionstore/test/browser_637020_slow.sjs
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-const DELAY_MS = "2000";
-
-let timer;
-
-function handleRequest(req, resp) {
- resp.processAsync();
- resp.setHeader("Cache-Control", "no-cache", false);
- resp.setHeader("Content-Type", "text/html;charset=utf-8", false);
-
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.init(() => {
- resp.write("hi");
- resp.finish();
- }, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
-}
diff --git a/browser/components/sessionstore/test/browser_644409-scratchpads.js b/browser/components/sessionstore/test/browser_644409-scratchpads.js
deleted file mode 100644
index 56826801a..000000000
--- a/browser/components/sessionstore/test/browser_644409-scratchpads.js
+++ /dev/null
@@ -1,68 +0,0 @@
- /* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const testState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:blank" }] },
- ]
- }],
- scratchpads: [
- { text: "text1", executionContext: 1 },
- { text: "", executionContext: 2, filename: "test.js" }
- ]
-};
-
-// only finish() when correct number of windows opened
-var restored = [];
-function addState(state) {
- restored.push(state);
-
- if (restored.length == testState.scratchpads.length) {
- ok(statesMatch(restored, testState.scratchpads),
- "Two scratchpad windows restored");
-
- Services.ww.unregisterNotification(windowObserver);
- finish();
- }
-}
-
-function test() {
- waitForExplicitFinish();
-
- Services.ww.registerNotification(windowObserver);
-
- ss.setBrowserState(JSON.stringify(testState));
-}
-
-function windowObserver(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
-
- if (win.Scratchpad) {
- win.Scratchpad.addObserver({
- onReady: function() {
- win.Scratchpad.removeObserver(this);
-
- let state = win.Scratchpad.getState();
- BrowserTestUtils.closeWindow(win).then(() => {
- addState(state);
- });
- },
- });
- }
- }, false);
- }
-}
-
-function statesMatch(restored, states) {
- return states.every(function(state) {
- return restored.some(function(restoredState) {
- return state.filename == restoredState.filename &&
- state.text == restoredState.text &&
- state.executionContext == restoredState.executionContext;
- })
- });
-}
diff --git a/browser/components/sessionstore/test/browser_645428.js b/browser/components/sessionstore/test/browser_645428.js
deleted file mode 100644
index 124a7aea9..000000000
--- a/browser/components/sessionstore/test/browser_645428.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const NOTIFICATION = "sessionstore-browser-state-restored";
-
-function test() {
- waitForExplicitFinish();
-
- function observe(subject, topic, data) {
- if (NOTIFICATION == topic) {
- finish();
- ok(true, "TOPIC received");
- }
- }
-
- Services.obs.addObserver(observe, NOTIFICATION, false);
- registerCleanupFunction(function () {
- Services.obs.removeObserver(observe, NOTIFICATION);
- });
-
- ss.setBrowserState(JSON.stringify({ windows: [] }));
-}
diff --git a/browser/components/sessionstore/test/browser_659591.js b/browser/components/sessionstore/test/browser_659591.js
deleted file mode 100644
index 60b1dcd2e..000000000
--- a/browser/components/sessionstore/test/browser_659591.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- waitForExplicitFinish();
-
- let eventReceived = false;
-
- registerCleanupFunction(function () {
- ok(eventReceived, "SSWindowClosing event received");
- });
-
- newWindow(function (win) {
- win.addEventListener("SSWindowClosing", function onWindowClosing() {
- win.removeEventListener("SSWindowClosing", onWindowClosing, false);
- eventReceived = true;
- }, false);
-
- BrowserTestUtils.closeWindow(win).then(() => {
- waitForFocus(finish);
- });
- });
-}
-
-function newWindow(callback) {
- let opts = "chrome,all,dialog=no,height=800,width=800";
- let win = window.openDialog(getBrowserURL(), "_blank", opts);
-
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- executeSoon(() => callback(win));
- }, false);
-}
diff --git a/browser/components/sessionstore/test/browser_662743.js b/browser/components/sessionstore/test/browser_662743.js
deleted file mode 100644
index 212180213..000000000
--- a/browser/components/sessionstore/test/browser_662743.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// This tests that session restore component does restore the right <select> option.
-// Session store should not rely only on previous user's selectedIndex, it should
-// check its value as well.
-
-function test() {
- /** Tests selected options **/
- requestLongerTimeout(2);
- waitForExplicitFinish();
-
- let testTabCount = 0;
- let formData = [
- // default case
- { },
-
- // new format
- // index doesn't match value (testing an option in between (two))
- { id:{ "select_id": {"selectedIndex":0,"value":"val2"} } },
- // index doesn't match value (testing an invalid value)
- { id:{ "select_id": {"selectedIndex":4,"value":"val8"} } },
- // index doesn't match value (testing an invalid index)
- { id:{ "select_id": {"selectedIndex":8,"value":"val5"} } },
- // index and value match position zero
- { id:{ "select_id": {"selectedIndex":0,"value":"val0"} }, xpath: {} },
- // index doesn't match value (testing the last option (seven))
- { id:{},"xpath":{ "/xhtml:html/xhtml:body/xhtml:select[@name='select_name']": {"selectedIndex":1,"value":"val7"} } },
- // index and value match the default option "selectedIndex":3,"value":"val3"
- { xpath: { "/xhtml:html/xhtml:body/xhtml:select[@name='select_name']" : {"selectedIndex":3,"value":"val3"} } },
- // index matches default option however it doesn't match value
- { id:{ "select_id": {"selectedIndex":3,"value":"val4"} } },
- ];
-
- let expectedValues = [
- null, // default value
- "val2",
- null, // default value (invalid value)
- "val5", // value is still valid (even it has an invalid index)
- "val0",
- "val7",
- null,
- "val4",
- ];
- let callback = function() {
- testTabCount--;
- if (testTabCount == 0) {
- finish();
- }
- };
-
- for (let i = 0; i < formData.length; i++) {
- testTabCount++;
- testTabRestoreData(formData[i], expectedValues[i], callback);
- }
-}
-
-function testTabRestoreData(aFormData, aExpectedValue, aCallback) {
- let testURL =
- getRootDirectory(gTestPath) + "browser_662743_sample.html";
- let tab = gBrowser.addTab(testURL);
-
- aFormData.url = testURL;
- let tabState = { entries: [{ url: testURL, }], formdata: aFormData };
-
- promiseBrowserLoaded(tab.linkedBrowser).then(() => {
- promiseTabState(tab, tabState).then(() => {
- // Flush to make sure we have the latest form data.
- return TabStateFlusher.flush(tab.linkedBrowser);
- }).then(() => {
- let doc = tab.linkedBrowser.contentDocument;
- let select = doc.getElementById("select_id");
- let value = select.options[select.selectedIndex].value;
- let restoredTabState = JSON.parse(ss.getTabState(tab));
-
- // If aExpectedValue=null we don't expect any form data to be collected.
- if (!aExpectedValue) {
- ok(!restoredTabState.hasOwnProperty("formdata"), "no formdata collected");
- gBrowser.removeTab(tab);
- aCallback();
- return;
- }
-
- // test select options values
- is(value, aExpectedValue,
- "Select Option by selectedIndex &/or value has been restored correctly");
-
- let restoredFormData = restoredTabState.formdata;
- let selectIdFormData = restoredFormData.id.select_id;
- value = restoredFormData.id.select_id.value;
-
- // test format
- ok("id" in restoredFormData || "xpath" in restoredFormData,
- "FormData format is valid");
- // test format
- ok("selectedIndex" in selectIdFormData && "value" in selectIdFormData,
- "select format is valid");
- // test set collection values
- is(value, aExpectedValue,
- "Collection has been saved correctly");
-
- // clean up
- gBrowser.removeTab(tab);
-
- aCallback();
- });
- });
-}
diff --git a/browser/components/sessionstore/test/browser_662743_sample.html b/browser/components/sessionstore/test/browser_662743_sample.html
deleted file mode 100644
index de48fa0c9..000000000
--- a/browser/components/sessionstore/test/browser_662743_sample.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE html>
-<title>Test 662743</title>
-
-<!-- Select events -->
-<h3>Select options</h3>
-<select id="select_id" name="select_name">
- <option value="val0">Zero</option>
- <option value="val1">One</option>
- <option value="val2">Two</option>
- <option value="val3" selected="selected">Three</option>
- <option value="val4">Four</option>
- <option value="val5">Five</option>
- <option value="val6">Six</option>
- <option value="val7">Seven</option>
-</select> \ No newline at end of file
diff --git a/browser/components/sessionstore/test/browser_662812.js b/browser/components/sessionstore/test/browser_662812.js
deleted file mode 100644
index 1bbaf67dc..000000000
--- a/browser/components/sessionstore/test/browser_662812.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- waitForExplicitFinish();
-
- window.addEventListener("SSWindowStateBusy", function onBusy() {
- window.removeEventListener("SSWindowStateBusy", onBusy, false);
-
- let state = JSON.parse(ss.getWindowState(window));
- ok(state.windows[0].busy, "window is busy");
-
- window.addEventListener("SSWindowStateReady", function onReady() {
- window.removeEventListener("SSWindowStateReady", onReady, false);
-
- let state = JSON.parse(ss.getWindowState(window));
- ok(!state.windows[0].busy, "window is not busy");
-
- executeSoon(() => {
- gBrowser.removeTab(gBrowser.tabs[1]);
- finish();
- });
- }, false);
- }, false);
-
- // create a new tab
- let tab = gBrowser.addTab("about:mozilla");
- let browser = tab.linkedBrowser;
-
- // close and restore it
- browser.addEventListener("load", function onLoad() {
- browser.removeEventListener("load", onLoad, true);
- gBrowser.removeTab(tab);
- ss.undoCloseTab(window, 0);
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_665702-state_session.js b/browser/components/sessionstore/test/browser_665702-state_session.js
deleted file mode 100644
index 524b4969f..000000000
--- a/browser/components/sessionstore/test/browser_665702-state_session.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function compareArray(a, b) {
- if (a.length !== b.length) {
- return false;
- }
- for (let i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) {
- return false;
- }
- }
- return true;
-}
-
-function test() {
- let currentState = JSON.parse(ss.getBrowserState());
- ok(currentState.session, "session data returned by getBrowserState");
-
- let keys = Object.keys(currentState.session);
- let expectedKeys = ["lastUpdate", "startTime", "recentCrashes"];
- ok(compareArray(keys.sort(), expectedKeys.sort()),
- "session object from getBrowserState has correct keys");
-}
diff --git a/browser/components/sessionstore/test/browser_682507.js b/browser/components/sessionstore/test/browser_682507.js
deleted file mode 100644
index 52b95341b..000000000
--- a/browser/components/sessionstore/test/browser_682507.js
+++ /dev/null
@@ -1,16 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
- gBrowser.addTab("about:mozilla");
-
- ss.setTabState(gBrowser.tabs[1], ss.getTabState(gBrowser.tabs[1]));
- ok(gBrowser.tabs[1].hasAttribute("pending"), "second tab should have 'pending' attribute");
-
- gBrowser.selectedTab = gBrowser.tabs[1];
- ok(!gBrowser.tabs[1].hasAttribute("pending"), "second tab should have not 'pending' attribute");
-
- gBrowser.removeTab(gBrowser.tabs[1]);
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
-}
diff --git a/browser/components/sessionstore/test/browser_687710.js b/browser/components/sessionstore/test/browser_687710.js
deleted file mode 100644
index 372ecf7ae..000000000
--- a/browser/components/sessionstore/test/browser_687710.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that sessionrestore handles cycles in the shentry graph properly.
-//
-// These cycles shouldn't be there in the first place, but they cause hangs
-// when they mysteriously appear (bug 687710). Docshell code assumes this
-// graph is a tree and tires to walk to the root. But if there's a cycle,
-// there is no root, and we loop forever.
-
-var stateBackup = ss.getBrowserState();
-
-var state = {windows:[{tabs:[{entries:[
- {
- docIdentifier: 1,
- url: "http://example.com",
- children: [
- {
- docIdentifier: 2,
- url: "http://example.com"
- }
- ]
- },
- {
- docIdentifier: 2,
- url: "http://example.com",
- children: [
- {
- docIdentifier: 1,
- url: "http://example.com"
- }
- ]
- }
-]}]}]}
-
-function test() {
- registerCleanupFunction(function () {
- ss.setBrowserState(stateBackup);
- });
-
- /* This test fails by hanging. */
- ss.setBrowserState(JSON.stringify(state));
- ok(true, "Didn't hang!");
-}
diff --git a/browser/components/sessionstore/test/browser_687710_2.js b/browser/components/sessionstore/test/browser_687710_2.js
deleted file mode 100644
index c22e73750..000000000
--- a/browser/components/sessionstore/test/browser_687710_2.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/* eslint-env mozilla/frame-script */
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that the fix for bug 687710 isn't too aggressive -- shentries which are
-// cousins should be able to share bfcache entries.
-
-var stateBackup = ss.getBrowserState();
-
-var state = {entries:[
- {
- docIdentifier: 1,
- url: "http://example.com?1",
- children: [{ docIdentifier: 10,
- url: "http://example.com?10" }]
- },
- {
- docIdentifier: 1,
- url: "http://example.com?1#a",
- children: [{ docIdentifier: 10,
- url: "http://example.com?10#aa" }]
- }
-]};
-
-add_task(function* test() {
- let tab = gBrowser.addTab("about:blank");
- yield promiseTabState(tab, state);
- yield ContentTask.spawn(tab.linkedBrowser, null, function() {
- function compareEntries(i, j, history) {
- let e1 = history.getEntryAtIndex(i, false)
- .QueryInterface(Ci.nsISHEntry)
- .QueryInterface(Ci.nsISHContainer);
-
- let e2 = history.getEntryAtIndex(j, false)
- .QueryInterface(Ci.nsISHEntry)
- .QueryInterface(Ci.nsISHContainer);
-
- ok(e1.sharesDocumentWith(e2),
- `${i} should share doc with ${j}`);
- is(e1.childCount, e2.childCount,
- `Child count mismatch (${i}, ${j})`);
-
- for (let c = 0; c < e1.childCount; c++) {
- let c1 = e1.GetChildAt(c);
- let c2 = e2.GetChildAt(c);
-
- ok(c1.sharesDocumentWith(c2),
- `Cousins should share documents. (${i}, ${j}, ${c})`);
- }
- }
-
- let history = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
-
- is(history.count, 2, "history.count");
- for (let i = 0; i < history.count; i++) {
- for (let j = 0; j < history.count; j++) {
- compareEntries(i, j, history);
- }
- }
- });
-
- ss.setBrowserState(stateBackup);
-});
diff --git a/browser/components/sessionstore/test/browser_694378.js b/browser/components/sessionstore/test/browser_694378.js
deleted file mode 100644
index 8578428d8..000000000
--- a/browser/components/sessionstore/test/browser_694378.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test Summary:
-// 1. call ss.setWindowState with a broken state
-// 1a. ensure that it doesn't throw.
-
-function test() {
- waitForExplicitFinish();
-
- let brokenState = {
- windows: [
- { tabs: [{ entries: [{ url: "about:mozilla" }] }] }
- ],
- selectedWindow: 2
- };
- let brokenStateString = JSON.stringify(brokenState);
-
- let gotError = false;
- try {
- ss.setWindowState(window, brokenStateString, true);
- }
- catch (ex) {
- gotError = true;
- info(ex);
- }
-
- ok(!gotError, "ss.setWindowState did not throw an error");
-
- // Make sure that we reset the state. Use a full state just in case things get crazy.
- let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]};
- waitForBrowserState(blankState, finish);
-}
diff --git a/browser/components/sessionstore/test/browser_701377.js b/browser/components/sessionstore/test/browser_701377.js
deleted file mode 100644
index 1bf2625ef..000000000
--- a/browser/components/sessionstore/test/browser_701377.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var state = {windows:[{tabs:[
- {entries:[{url:"http://example.com#1"}]},
- {entries:[{url:"http://example.com#2"}], hidden: true}
-]}]};
-
-function test() {
- waitForExplicitFinish();
-
- newWindowWithState(state, function (aWindow) {
- let tab = aWindow.gBrowser.tabs[1];
- ok(tab.hidden, "the second tab is hidden");
-
- let tabShown = false;
- let tabShowCallback = () => tabShown = true;
- tab.addEventListener("TabShow", tabShowCallback, false);
-
- let tabState = ss.getTabState(tab);
- ss.setTabState(tab, tabState);
-
- tab.removeEventListener("TabShow", tabShowCallback, false);
- ok(tab.hidden && !tabShown, "tab remains hidden");
-
- finish();
- });
-}
-
-// ----------
-function newWindowWithState(aState, aCallback) {
- let opts = "chrome,all,dialog=no,height=800,width=800";
- let win = window.openDialog(getBrowserURL(), "_blank", opts);
-
- registerCleanupFunction(() => BrowserTestUtils.closeWindow(win));
-
- whenWindowLoaded(win, function onWindowLoaded(aWin) {
- ss.setWindowState(aWin, JSON.stringify(aState), true);
- executeSoon(() => aCallback(aWin));
- });
-}
diff --git a/browser/components/sessionstore/test/browser_705597.js b/browser/components/sessionstore/test/browser_705597.js
deleted file mode 100644
index efadcfe88..000000000
--- a/browser/components/sessionstore/test/browser_705597.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var tabState = {
- entries: [{url: "about:robots", children: [{url: "about:mozilla"}]}]
-};
-
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(2);
-
- Services.prefs.setIntPref("browser.sessionstore.interval", 4000);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.interval");
- });
-
- let tab = gBrowser.addTab("about:blank");
-
- let browser = tab.linkedBrowser;
-
- promiseTabState(tab, tabState).then(() => {
- let sessionHistory = browser.sessionHistory;
- let entry = sessionHistory.getEntryAtIndex(0, false);
- entry.QueryInterface(Ci.nsISHContainer);
-
- whenChildCount(entry, 1, function () {
- whenChildCount(entry, 2, function () {
- promiseBrowserLoaded(browser).then(() => {
- return TabStateFlusher.flush(browser);
- }).then(() => {
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "tab has one history entry");
- ok(!entries[0].children, "history entry has no subframes");
-
- // Make sure that we reset the state.
- let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]};
- waitForBrowserState(blankState, finish);
- });
-
- // reload the browser to deprecate the subframes
- browser.reload();
- });
-
- // create a dynamic subframe
- let doc = browser.contentDocument;
- let iframe = doc.createElement("iframe");
- doc.body.appendChild(iframe);
- iframe.setAttribute("src", "about:mozilla");
- });
- });
-}
-
-function whenChildCount(aEntry, aChildCount, aCallback) {
- if (aEntry.childCount == aChildCount)
- aCallback();
- else
- setTimeout(() => whenChildCount(aEntry, aChildCount, aCallback), 100);
-}
diff --git a/browser/components/sessionstore/test/browser_707862.js b/browser/components/sessionstore/test/browser_707862.js
deleted file mode 100644
index e12c44af4..000000000
--- a/browser/components/sessionstore/test/browser_707862.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var tabState = {
- entries: [{url: "about:robots", children: [{url: "about:mozilla"}]}]
-};
-
-function test() {
- waitForExplicitFinish();
- requestLongerTimeout(2);
-
- Services.prefs.setIntPref("browser.sessionstore.interval", 4000);
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.interval");
- });
-
- let tab = gBrowser.addTab("about:blank");
-
- let browser = tab.linkedBrowser;
-
- promiseTabState(tab, tabState).then(() => {
- let sessionHistory = browser.sessionHistory;
- let entry = sessionHistory.getEntryAtIndex(0, false);
- entry.QueryInterface(Ci.nsISHContainer);
-
- whenChildCount(entry, 1, function () {
- whenChildCount(entry, 2, function () {
- promiseBrowserLoaded(browser).then(() => {
- let sessionHistory = browser.sessionHistory;
- let entry = sessionHistory.getEntryAtIndex(0, false);
-
- whenChildCount(entry, 0, function () {
- // Make sure that we reset the state.
- let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]};
- waitForBrowserState(blankState, finish);
- });
- });
-
- // reload the browser to deprecate the subframes
- browser.reload();
- });
-
- // create a dynamic subframe
- let doc = browser.contentDocument;
- let iframe = doc.createElement("iframe");
- doc.body.appendChild(iframe);
- iframe.setAttribute("src", "about:mozilla");
- });
- });
-
- // This test relies on the test timing out in order to indicate failure so
- // let's add a dummy pass.
- ok(true, "Each test requires at least one pass, fail or todo so here is a pass.");
-}
-
-function whenChildCount(aEntry, aChildCount, aCallback) {
- if (aEntry.childCount == aChildCount)
- aCallback();
- else
- setTimeout(() => whenChildCount(aEntry, aChildCount, aCallback), 100);
-}
diff --git a/browser/components/sessionstore/test/browser_739531.js b/browser/components/sessionstore/test/browser_739531.js
deleted file mode 100644
index e5927caf6..000000000
--- a/browser/components/sessionstore/test/browser_739531.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test ensures that attempts made to save/restore ("duplicate") pages
-// using designmode AND make changes to document structure (remove body)
-// don't result in uncaught errors and a broken browser state.
-
-function test() {
- waitForExplicitFinish();
-
- let testURL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_739531_sample.html";
-
- let loadCount = 0;
- let tab = gBrowser.addTab(testURL);
- tab.linkedBrowser.addEventListener("load", function onLoad(aEvent) {
- // make sure both the page and the frame are loaded
- if (++loadCount < 2)
- return;
- tab.linkedBrowser.removeEventListener("load", onLoad, true);
-
- // executeSoon to allow the JS to execute on the page
- executeSoon(function() {
-
- let tab2;
- let caughtError = false;
- try {
- tab2 = ss.duplicateTab(window, tab);
- }
- catch (e) {
- caughtError = true;
- info(e);
- }
-
- is(gBrowser.tabs.length, 3, "there should be 3 tabs")
-
- ok(!caughtError, "duplicateTab didn't throw");
-
- // if the test fails, we don't want to try to close a tab that doesn't exist
- if (tab2)
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-
- finish();
- });
- }, true);
-}
diff --git a/browser/components/sessionstore/test/browser_739531_sample.html b/browser/components/sessionstore/test/browser_739531_sample.html
deleted file mode 100644
index ad317ab0c..000000000
--- a/browser/components/sessionstore/test/browser_739531_sample.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!-- originally a crash test for bug 713417
- https://bug713417.bugzilla.mozilla.org/attachment.cgi?id=584240 -->
-<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-<script>
-
-function boom()
-{
- var w = document.getElementById("f").contentWindow;
- var d = w.document;
- d.designMode = 'on';
- var r = d.documentElement;
- d.removeChild(r);
- document.adoptNode(r);
-}
-
-</script>
-</head>
-<body onload="boom();">
-<iframe src="data:text/html;charset=utf-8,1" id="f"></iframe>
-</body>
-</html>
-
diff --git a/browser/components/sessionstore/test/browser_739805.js b/browser/components/sessionstore/test/browser_739805.js
deleted file mode 100644
index f00871661..000000000
--- a/browser/components/sessionstore/test/browser_739805.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var url = "data:text/html;charset=utf-8,<input%20id='foo'>";
-var tabState = {
- entries: [{ url }], formdata: { id: { "foo": "bar" }, url }
-};
-
-function test() {
- waitForExplicitFinish();
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- registerCleanupFunction(function () {
- if (gBrowser.tabs.length > 1)
- gBrowser.removeTab(gBrowser.tabs[1]);
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
- });
-
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
-
- promiseBrowserLoaded(browser).then(() => {
- isnot(gBrowser.selectedTab, tab, "newly created tab is not selected");
-
- ss.setTabState(tab, JSON.stringify(tabState));
- is(browser.__SS_restoreState, TAB_STATE_NEEDS_RESTORE, "tab needs restoring");
-
- let {formdata} = JSON.parse(ss.getTabState(tab));
- is(formdata && formdata.id["foo"], "bar", "tab state's formdata is valid");
-
- promiseTabRestored(tab).then(() => {
- ContentTask.spawn(browser, null, function() {
- let input = content.document.getElementById("foo");
- is(input.value, "bar", "formdata has been restored correctly");
- }).then(() => { finish(); });
- });
-
- // Restore the tab by selecting it.
- gBrowser.selectedTab = tab;
- });
-}
diff --git a/browser/components/sessionstore/test/browser_819510_perwindowpb.js b/browser/components/sessionstore/test/browser_819510_perwindowpb.js
deleted file mode 100644
index 21f916f0d..000000000
--- a/browser/components/sessionstore/test/browser_819510_perwindowpb.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test opening default mochitest-normal-private-normal-private windows
-// (saving the state with last window being private)
-
-requestLongerTimeout(2);
-
-add_task(function* test_1() {
- let win = yield promiseNewWindowLoaded();
- win.gBrowser.addTab("http://www.example.com/1");
-
- win = yield promiseNewWindowLoaded({private: true});
- win.gBrowser.addTab("http://www.example.com/2");
-
- win = yield promiseNewWindowLoaded();
- win.gBrowser.addTab("http://www.example.com/3");
-
- win = yield promiseNewWindowLoaded({private: true});
- win.gBrowser.addTab("http://www.example.com/4");
-
- let curState = JSON.parse(ss.getBrowserState());
- is(curState.windows.length, 5, "Browser has opened 5 windows");
- is(curState.windows[2].isPrivate, true, "Window is private");
- is(curState.windows[4].isPrivate, true, "Last window is private");
- is(curState.selectedWindow, 5, "Last window opened is the one selected");
-
- let state = JSON.parse(yield promiseRecoveryFileContents());
-
- is(state.windows.length, 3,
- "sessionstore state: 3 windows in data being written to disk");
- is(state.selectedWindow, 3,
- "Selected window is updated to match one of the saved windows");
- ok(state.windows.every(win => !win.isPrivate),
- "Saved windows are not private");
- is(state._closedWindows.length, 0,
- "sessionstore state: no closed windows in data being written to disk");
-
- // Cleanup.
- yield promiseAllButPrimaryWindowClosed();
- forgetClosedWindows();
-});
-
-// Test opening default mochitest window + 2 private windows
-add_task(function* test_2() {
- let win = yield promiseNewWindowLoaded({private: true});
- win.gBrowser.addTab("http://www.example.com/1");
-
- win = yield promiseNewWindowLoaded({private: true});
- win.gBrowser.addTab("http://www.example.com/2");
-
- let curState = JSON.parse(ss.getBrowserState());
- is(curState.windows.length, 3, "Browser has opened 3 windows");
- is(curState.windows[1].isPrivate, true, "Window 1 is private");
- is(curState.windows[2].isPrivate, true, "Window 2 is private");
- is(curState.selectedWindow, 3, "Last window opened is the one selected");
-
- let state = JSON.parse(yield promiseRecoveryFileContents());
-
- is(state.windows.length, 1,
- "sessionstore state: 1 windows in data being written to disk");
- is(state.selectedWindow, 1,
- "Selected window is updated to match one of the saved windows");
- is(state._closedWindows.length, 0,
- "sessionstore state: no closed windows in data being written to disk");
-
- // Cleanup.
- yield promiseAllButPrimaryWindowClosed();
- forgetClosedWindows();
-});
-
-// Test opening default-normal-private-normal windows and closing a normal window
-add_task(function* test_3() {
- let normalWindow = yield promiseNewWindowLoaded();
- yield promiseTabLoad(normalWindow, "http://www.example.com/");
-
- let win = yield promiseNewWindowLoaded({private: true});
- yield promiseTabLoad(win, "http://www.example.com/");
-
- win = yield promiseNewWindowLoaded();
- yield promiseTabLoad(win, "http://www.example.com/");
-
- let curState = JSON.parse(ss.getBrowserState());
- is(curState.windows.length, 4, "Browser has opened 4 windows");
- is(curState.windows[2].isPrivate, true, "Window 2 is private");
- is(curState.selectedWindow, 4, "Last window opened is the one selected");
-
- yield BrowserTestUtils.closeWindow(normalWindow);
-
- // Pin and unpin a tab before checking the written state so that
- // the list of restoring windows gets cleared. Otherwise the
- // window we just closed would be marked as not closed.
- let tab = win.gBrowser.tabs[0];
- win.gBrowser.pinTab(tab);
- win.gBrowser.unpinTab(tab);
-
- let state = JSON.parse(yield promiseRecoveryFileContents());
-
- is(state.windows.length, 2,
- "sessionstore state: 2 windows in data being written to disk");
- is(state.selectedWindow, 2,
- "Selected window is updated to match one of the saved windows");
- ok(state.windows.every(win => !win.isPrivate),
- "Saved windows are not private");
- is(state._closedWindows.length, 1,
- "sessionstore state: 1 closed window in data being written to disk");
- ok(state._closedWindows.every(win => !win.isPrivate),
- "Closed windows are not private");
-
- // Cleanup.
- yield promiseAllButPrimaryWindowClosed();
- forgetClosedWindows();
-});
-
-function* promiseTabLoad(win, url) {
- let browser = win.gBrowser.selectedBrowser;
- browser.loadURI(url);
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-}
diff --git a/browser/components/sessionstore/test/browser_911547.js b/browser/components/sessionstore/test/browser_911547.js
deleted file mode 100644
index 58b2e9ef1..000000000
--- a/browser/components/sessionstore/test/browser_911547.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This tests that session restore component does restore the right content
-// security policy with the document.
-// The policy being tested disallows inline scripts
-
-add_task(function* test() {
- // create a tab that has a CSP
- let testURL = "http://mochi.test:8888/browser/browser/components/sessionstore/test/browser_911547_sample.html";
- let tab = gBrowser.selectedTab = gBrowser.addTab(testURL);
- gBrowser.selectedTab = tab;
-
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // this is a baseline to ensure CSP is active
- // attempt to inject and run a script via inline (pre-restore, allowed)
- yield injectInlineScript(browser, `document.getElementById("test_id").value = "fail";`);
-
- let loadedPromise = promiseBrowserLoaded(browser);
- yield ContentTask.spawn(browser, null, function() {
- is(content.document.getElementById("test_id").value, "ok",
- "CSP should block the inline script that modifies test_id");
-
- // attempt to click a link to a data: URI (will inherit the CSP of the
- // origin document) and navigate to the data URI in the link.
- content.document.getElementById("test_data_link").click();
- });
-
- yield loadedPromise;
-
- yield ContentTask.spawn(browser, null, function() {
- is(content.document.getElementById("test_id2").value, "ok",
- "CSP should block the script loaded by the clicked data URI");
- });
-
- // close the tab
- yield promiseRemoveTab(tab);
-
- // open new tab and recover the state
- tab = ss.undoCloseTab(window, 0);
- yield promiseTabRestored(tab);
- browser = tab.linkedBrowser;
-
- yield ContentTask.spawn(browser, null, function() {
- is(content.document.getElementById("test_id2").value, "ok",
- "CSP should block the script loaded by the clicked data URI after restore");
- });
-
- // clean up
- gBrowser.removeTab(tab);
-});
-
-// injects an inline script element (with a text body)
-function injectInlineScript(browser, scriptText) {
- return ContentTask.spawn(browser, scriptText, function(text) {
- let scriptElt = content.document.createElement("script");
- scriptElt.type = "text/javascript";
- scriptElt.text = text;
- content.document.body.appendChild(scriptElt);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_911547_sample.html b/browser/components/sessionstore/test/browser_911547_sample.html
deleted file mode 100644
index ccc201159..000000000
--- a/browser/components/sessionstore/test/browser_911547_sample.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- <title>Test 911547</title>
- </head>
-<body>
-
- <!--
- this element gets modified by an injected script;
- that script should be blocked by CSP.
- Inline scripts can modify it, but not data uris.
- -->
- <input type="text" id="test_id" value="ok">
-
- <a id="test_data_link" href="data:text/html;charset=utf-8,<input type='text' id='test_id2' value='ok'/> <script>document.getElementById('test_id2').value = 'fail';</script>">Test Link</a>
-
-</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_911547_sample.html^headers^ b/browser/components/sessionstore/test/browser_911547_sample.html^headers^
deleted file mode 100644
index 4623dec30..000000000
--- a/browser/components/sessionstore/test/browser_911547_sample.html^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Content-Security-Policy: script-src 'self'
diff --git a/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js b/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js
deleted file mode 100644
index 3050bd4c1..000000000
--- a/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js
+++ /dev/null
@@ -1,21 +0,0 @@
-"use strict";
-
-// Tests that an about:privatebrowsing tab with no history will not
-// be saved into session store and thus, it will not show up in
-// Recently Closed Tabs.
-
-add_task(function* () {
- let tab = gBrowser.addTab("about:privatebrowsing");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- is(gBrowser.browsers[1].currentURI.spec, "about:privatebrowsing",
- "we will be removing an about:privatebrowsing tab");
-
- let r = `rand-${Math.random()}`;
- ss.setTabValue(tab, "foobar", r);
-
- yield promiseRemoveTab(tab);
- let closedTabData = ss.getClosedTabData(window);
- ok(!closedTabData.includes(r), "tab not stored in _closedTabs");
-});
diff --git a/browser/components/sessionstore/test/browser_aboutSessionRestore.js b/browser/components/sessionstore/test/browser_aboutSessionRestore.js
deleted file mode 100644
index 8ab91e4df..000000000
--- a/browser/components/sessionstore/test/browser_aboutSessionRestore.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const CRASH_URL = "about:mozilla";
-const CRASH_FAVICON = "chrome://branding/content/icon32.png";
-const CRASH_SHENTRY = {url: CRASH_URL};
-const CRASH_TAB = {entries: [CRASH_SHENTRY], image: CRASH_FAVICON};
-const CRASH_STATE = {windows: [{tabs: [CRASH_TAB]}]};
-
-const TAB_URL = "about:sessionrestore";
-const TAB_FORMDATA = {url: TAB_URL, id: {sessionData: CRASH_STATE}};
-const TAB_SHENTRY = {url: TAB_URL};
-const TAB_STATE = {entries: [TAB_SHENTRY], formdata: TAB_FORMDATA};
-
-const FRAME_SCRIPT = "data:," +
- "content.document.getElementById('errorTryAgain').click()";
-
-add_task(function* () {
- // Prepare a blank tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Fake a post-crash tab.
- ss.setTabState(tab, JSON.stringify(TAB_STATE));
- yield promiseTabRestored(tab);
-
- ok(gBrowser.tabs.length > 1, "we have more than one tab");
-
- let view = browser.contentDocument.getElementById("tabList").view;
- ok(view.isContainer(0), "first entry is the window");
- is(view.getCellProperties(1, { id: "title" }), "icon",
- "second entry is the tab and has a favicon");
-
- browser.messageManager.loadFrameScript(FRAME_SCRIPT, true);
-
- // Wait until the new window was restored.
- let win = yield waitForNewWindow();
- yield BrowserTestUtils.closeWindow(win);
-
- let [{tabs: [{entries: [{url}]}]}] = JSON.parse(ss.getClosedWindowData());
- is(url, CRASH_URL, "session was restored correctly");
- ss.forgetClosedWindow(0);
-});
-
-function waitForNewWindow() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observe(win, topic) {
- Services.obs.removeObserver(observe, topic);
- resolve(win);
- }, "browser-delayed-startup-finished", false);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_async_duplicate_tab.js b/browser/components/sessionstore/test/browser_async_duplicate_tab.js
deleted file mode 100644
index 8696a284f..000000000
--- a/browser/components/sessionstore/test/browser_async_duplicate_tab.js
+++ /dev/null
@@ -1,78 +0,0 @@
-"use strict";
-
-const URL = "data:text/html;charset=utf-8,<a href=%23>clickme</a>";
-
-add_task(function* test_duplicate() {
- // Create new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // Click the link to navigate, this will add second shistory entry.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("hashchange", function onHashChange() {
- removeEventListener("hashchange", onHashChange);
- resolve();
- });
-
- // Click the link.
- content.document.querySelector("a").click();
- });
- });
-
- // Duplicate the tab.
- let tab2 = ss.duplicateTab(window, tab);
-
- // Wait until the tab has fully restored.
- yield promiseTabRestored(tab2);
- yield TabStateFlusher.flush(tab2.linkedBrowser);
-
- // There should be two history entries now.
- let {entries} = JSON.parse(ss.getTabState(tab2));
- is(entries.length, 2, "there are two shistory entries");
-
- // Cleanup.
- yield promiseRemoveTab(tab2);
- yield promiseRemoveTab(tab);
-});
-
-add_task(function* test_duplicate_remove() {
- // Create new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // Click the link to navigate, this will add second shistory entry.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("hashchange", function onHashChange() {
- removeEventListener("hashchange", onHashChange);
- resolve();
- });
-
- // Click the link.
- content.document.querySelector("a").click();
- });
- });
-
- // Duplicate the tab.
- let tab2 = ss.duplicateTab(window, tab);
-
- // Before the duplication finished, remove the tab.
- yield Promise.all([promiseRemoveTab(tab), promiseTabRestored(tab2)]);
- yield TabStateFlusher.flush(tab2.linkedBrowser);
-
- // There should be two history entries now.
- let {entries} = JSON.parse(ss.getTabState(tab2));
- is(entries.length, 2, "there are two shistory entries");
-
- // Cleanup.
- yield promiseRemoveTab(tab2);
-});
diff --git a/browser/components/sessionstore/test/browser_async_flushes.js b/browser/components/sessionstore/test/browser_async_flushes.js
deleted file mode 100644
index a4cbbfbc7..000000000
--- a/browser/components/sessionstore/test/browser_async_flushes.js
+++ /dev/null
@@ -1,113 +0,0 @@
-"use strict";
-
-const URL = "data:text/html;charset=utf-8,<a href=%23>clickme</a>";
-
-add_task(function* test_flush() {
- // Create new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // There should be one history entry.
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is a single history entry");
-
- // Click the link to navigate, this will add second shistory entry.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("hashchange", function onHashChange() {
- removeEventListener("hashchange", onHashChange);
- resolve();
- });
-
- // Click the link.
- content.document.querySelector("a").click();
- });
- });
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // There should be two history entries now.
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there are two shistory entries");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_crash() {
- // Create new tab.
- let tab = gBrowser.addTab(URL);
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // There should be one history entry.
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is a single history entry");
-
- // Click the link to navigate.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("hashchange", function onHashChange() {
- removeEventListener("hashchange", onHashChange);
- resolve();
- });
-
- // Click the link.
- content.document.querySelector("a").click();
- });
- });
-
- // Crash the browser and flush. Both messages are async and will be sent to
- // the content process. The "crash" message makes it first so that we don't
- // get a chance to process the flush. The TabStateFlusher however should be
- // notified so that the flush still completes.
- let promise1 = BrowserTestUtils.crashBrowser(browser);
- let promise2 = TabStateFlusher.flush(browser);
- yield Promise.all([promise1, promise2]);
-
- // The pending update should be lost.
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 1, "still only one history entry");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_remove() {
- // Create new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to empty any queued update messages.
- yield TabStateFlusher.flush(browser);
-
- // There should be one history entry.
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is a single history entry");
-
- // Click the link to navigate.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("hashchange", function onHashChange() {
- removeEventListener("hashchange", onHashChange);
- resolve();
- });
-
- // Click the link.
- content.document.querySelector("a").click();
- });
- });
-
- // Request a flush and remove the tab. The flush should still complete.
- yield Promise.all([TabStateFlusher.flush(browser), promiseRemoveTab(tab)]);
-})
diff --git a/browser/components/sessionstore/test/browser_async_remove_tab.js b/browser/components/sessionstore/test/browser_async_remove_tab.js
deleted file mode 100644
index 20f3463d0..000000000
--- a/browser/components/sessionstore/test/browser_async_remove_tab.js
+++ /dev/null
@@ -1,242 +0,0 @@
-"use strict";
-
-function* createTabWithRandomValue(url) {
- let tab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Set a random value.
- let r = `rand-${Math.random()}`;
- ss.setTabValue(tab, "foobar", r);
-
- // Flush to ensure there are no scheduled messages.
- yield TabStateFlusher.flush(browser);
-
- return {tab, r};
-}
-
-function isValueInClosedData(rval) {
- return ss.getClosedTabData(window).includes(rval);
-}
-
-function restoreClosedTabWithValue(rval) {
- let closedTabData = JSON.parse(ss.getClosedTabData(window));
- let index = closedTabData.findIndex(function (data) {
- return (data.state.extData && data.state.extData.foobar) == rval;
- });
-
- if (index == -1) {
- throw new Error("no closed tab found for given rval");
- }
-
- return ss.undoCloseTab(window, index);
-}
-
-function promiseNewLocationAndHistoryEntryReplaced(browser, snippet) {
- return ContentTask.spawn(browser, snippet, function* (snippet) {
- let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation);
- let shistory = webNavigation.sessionHistory;
-
- // Evaluate the snippet that the changes the location.
- eval(snippet);
-
- return new Promise(resolve => {
- let listener = {
- OnHistoryReplaceEntry() {
- shistory.removeSHistoryListener(this);
- resolve();
- },
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsISHistoryListener,
- Ci.nsISupportsWeakReference
- ])
- };
-
- shistory.addSHistoryListener(listener);
-
- /* Keep the weak shistory listener alive. */
- addEventListener("unload", function () {
- try {
- shistory.removeSHistoryListener(listener);
- } catch (e) { /* Will most likely fail. */ }
- });
- });
- });
-}
-
-function promiseHistoryEntryReplacedNonRemote(browser) {
- let {listeners} = promiseHistoryEntryReplacedNonRemote;
-
- return new Promise(resolve => {
- let shistory = browser.webNavigation.sessionHistory;
-
- let listener = {
- OnHistoryReplaceEntry() {
- shistory.removeSHistoryListener(this);
- resolve();
- },
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsISHistoryListener,
- Ci.nsISupportsWeakReference
- ])
- };
-
- shistory.addSHistoryListener(listener);
- listeners.set(browser, listener);
- });
-}
-promiseHistoryEntryReplacedNonRemote.listeners = new WeakMap();
-
-add_task(function* dont_save_empty_tabs() {
- let {tab, r} = yield createTabWithRandomValue("about:blank");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // No tab state worth saving.
- ok(!isValueInClosedData(r), "closed tab not saved");
- yield promise;
-
- // Still no tab state worth saving.
- ok(!isValueInClosedData(r), "closed tab not saved");
-});
-
-add_task(function* save_worthy_tabs_remote() {
- let {tab, r} = yield createTabWithRandomValue("https://example.com/");
- ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // Tab state deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
- yield promise;
-
- // Tab state still deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-});
-
-add_task(function* save_worthy_tabs_nonremote() {
- let {tab, r} = yield createTabWithRandomValue("about:robots");
- ok(!tab.linkedBrowser.isRemoteBrowser, "browser is not remote");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // Tab state deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
- yield promise;
-
- // Tab state still deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-});
-
-add_task(function* save_worthy_tabs_remote_final() {
- let {tab, r} = yield createTabWithRandomValue("about:blank");
- let browser = tab.linkedBrowser;
- ok(browser.isRemoteBrowser, "browser is remote");
-
- // Replace about:blank with a new remote page.
- let snippet = 'webNavigation.loadURI("https://example.com/", null, null, null, null)';
- yield promiseNewLocationAndHistoryEntryReplaced(browser, snippet);
-
- // Remotness shouldn't have changed.
- ok(browser.isRemoteBrowser, "browser is still remote");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // No tab state worth saving (that we know about yet).
- ok(!isValueInClosedData(r), "closed tab not saved");
- yield promise;
-
- // Turns out there is a tab state worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-});
-
-add_task(function* save_worthy_tabs_nonremote_final() {
- let {tab, r} = yield createTabWithRandomValue("about:blank");
- let browser = tab.linkedBrowser;
- ok(browser.isRemoteBrowser, "browser is remote");
-
- // Replace about:blank with a non-remote entry.
- yield BrowserTestUtils.loadURI(browser, "about:robots");
- ok(!browser.isRemoteBrowser, "browser is not remote anymore");
-
- // Wait until the new entry replaces about:blank.
- yield promiseHistoryEntryReplacedNonRemote(browser);
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // No tab state worth saving (that we know about yet).
- ok(!isValueInClosedData(r), "closed tab not saved");
- yield promise;
-
- // Turns out there is a tab state worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-});
-
-add_task(function* dont_save_empty_tabs_final() {
- let {tab, r} = yield createTabWithRandomValue("https://example.com/");
- let browser = tab.linkedBrowser;
-
- // Replace the current page with an about:blank entry.
- let snippet = 'content.location.replace("about:blank")';
- yield promiseNewLocationAndHistoryEntryReplaced(browser, snippet);
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // Tab state deemed worth saving (yet).
- ok(isValueInClosedData(r), "closed tab saved");
- yield promise;
-
- // Turns out we don't want to save the tab state.
- ok(!isValueInClosedData(r), "closed tab not saved");
-});
-
-add_task(function* undo_worthy_tabs() {
- let {tab, r} = yield createTabWithRandomValue("https://example.com/");
- ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // Tab state deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-
- // Restore the closed tab before receiving its final message.
- tab = restoreClosedTabWithValue(r);
-
- // Wait for the final update message.
- yield promise;
-
- // Check we didn't add the tab back to the closed list.
- ok(!isValueInClosedData(r), "tab no longer closed");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
-
-add_task(function* forget_worthy_tabs_remote() {
- let {tab, r} = yield createTabWithRandomValue("https://example.com/");
- ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote");
-
- // Remove the tab before the update arrives.
- let promise = promiseRemoveTab(tab);
-
- // Tab state deemed worth saving.
- ok(isValueInClosedData(r), "closed tab saved");
-
- // Forget the closed tab.
- ss.forgetClosedTab(window, 0);
-
- // Wait for the final update message.
- yield promise;
-
- // Check we didn't add the tab back to the closed list.
- ok(!isValueInClosedData(r), "we forgot about the tab");
-});
diff --git a/browser/components/sessionstore/test/browser_async_window_flushing.js b/browser/components/sessionstore/test/browser_async_window_flushing.js
deleted file mode 100644
index 418c055c2..000000000
--- a/browser/components/sessionstore/test/browser_async_window_flushing.js
+++ /dev/null
@@ -1,178 +0,0 @@
-"use strict";
-
-const PAGE = "http://example.com/";
-
-/**
- * Tests that if we initially discard a window as not interesting
- * to save in the closed windows array, that we revisit that decision
- * after a window flush has completed.
- */
-add_task(function* test_add_interesting_window() {
- // We want to suppress all non-final updates from the browser tabs
- // so as to eliminate any racy-ness with this test.
- yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]);
-
- // Depending on previous tests, we might already have some closed
- // windows stored. We'll use its length to determine whether or not
- // the window was added or not.
- let initialClosedWindows = ss.getClosedWindowCount();
-
- // Make sure we can actually store another closed window
- yield pushPrefs(["browser.sessionstore.max_windows_undo",
- initialClosedWindows + 1]);
-
- // Create a new browser window. Since the default window will start
- // at about:blank, SessionStore should find this tab (and therefore the
- // whole window) uninteresting, and should not initially put it into
- // the closed windows array.
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
-
- let browser = newWin.gBrowser.selectedBrowser;
-
- // Send a message that will cause the content to change its location
- // to someplace more interesting. We've disabled auto updates from
- // the browser, so the parent won't know about this
- yield ContentTask.spawn(browser, PAGE, function*(PAGE) {
- content.location = PAGE;
- });
-
- yield promiseContentMessage(browser, "ss-test:OnHistoryReplaceEntry");
-
- // Clear out the userTypedValue so that the new window looks like
- // it's really not worth restoring.
- browser.userTypedValue = null;
-
- // Once the domWindowClosed Promise resolves, the window should
- // have closed, and SessionStore's onClose handler should have just
- // run.
- let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin);
-
- // Once this windowClosed Promise resolves, we should have finished
- // the flush and revisited our decision to put this window into
- // the closed windows array.
- let windowClosed = BrowserTestUtils.windowClosed(newWin);
-
- // Ok, let's close the window.
- newWin.close();
-
- yield domWindowClosed;
- // OnClose has just finished running.
- let currentClosedWindows = ss.getClosedWindowCount();
- is(currentClosedWindows, initialClosedWindows,
- "We should not have added the window to the closed windows array");
-
- yield windowClosed;
- // The window flush has finished
- currentClosedWindows = ss.getClosedWindowCount();
- is(currentClosedWindows,
- initialClosedWindows + 1,
- "We should have added the window to the closed windows array");
-});
-
-/**
- * Tests that if we initially store a closed window as interesting
- * to save in the closed windows array, that we revisit that decision
- * after a window flush has completed, and stop storing a window that
- * we've deemed no longer interesting.
- */
-add_task(function* test_remove_uninteresting_window() {
- // We want to suppress all non-final updates from the browser tabs
- // so as to eliminate any racy-ness with this test.
- yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]);
-
- // Depending on previous tests, we might already have some closed
- // windows stored. We'll use its length to determine whether or not
- // the window was added or not.
- let initialClosedWindows = ss.getClosedWindowCount();
-
- // Make sure we can actually store another closed window
- yield pushPrefs(["browser.sessionstore.max_windows_undo",
- initialClosedWindows + 1]);
-
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
-
- // Now browse the initial tab of that window to an interesting
- // site.
- let tab = newWin.gBrowser.selectedTab;
- let browser = tab.linkedBrowser;
- browser.loadURI(PAGE);
-
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
- yield TabStateFlusher.flush(browser);
-
- // Send a message that will cause the content to purge its
- // history entries and make itself seem uninteresting.
- yield ContentTask.spawn(browser, null, function*() {
- // Epic hackery to make this browser seem suddenly boring.
- Components.utils.import("resource://gre/modules/BrowserUtils.jsm");
- docShell.setCurrentURI(BrowserUtils.makeURI("about:blank"));
-
- let {sessionHistory} = docShell.QueryInterface(Ci.nsIWebNavigation);
- sessionHistory.PurgeHistory(sessionHistory.count);
- });
-
- // Once the domWindowClosed Promise resolves, the window should
- // have closed, and SessionStore's onClose handler should have just
- // run.
- let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin);
-
- // Once this windowClosed Promise resolves, we should have finished
- // the flush and revisited our decision to put this window into
- // the closed windows array.
- let windowClosed = BrowserTestUtils.windowClosed(newWin);
-
- // Ok, let's close the window.
- newWin.close();
-
- yield domWindowClosed;
- // OnClose has just finished running.
- let currentClosedWindows = ss.getClosedWindowCount();
- is(currentClosedWindows, initialClosedWindows + 1,
- "We should have added the window to the closed windows array");
-
- yield windowClosed;
- // The window flush has finished
- currentClosedWindows = ss.getClosedWindowCount();
- is(currentClosedWindows,
- initialClosedWindows,
- "We should have removed the window from the closed windows array");
-});
-
-/**
- * Tests that when we close a window, it is immediately removed from the
- * _windows array.
- */
-add_task(function* test_synchronously_remove_window_state() {
- // Depending on previous tests, we might already have some closed
- // windows stored. We'll use its length to determine whether or not
- // the window was added or not.
- let state = JSON.parse(ss.getBrowserState());
- ok(state, "Make sure we can get the state");
- let initialWindows = state.windows.length;
-
- // Open a new window and send the first tab somewhere
- // interesting.
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
- let browser = newWin.gBrowser.selectedBrowser;
- browser.loadURI(PAGE);
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
- yield TabStateFlusher.flush(browser);
-
- state = JSON.parse(ss.getBrowserState());
- is(state.windows.length, initialWindows + 1,
- "The new window to be in the state");
-
- // Now close the window, and make sure that the window was removed
- // from the windows list from the SessionState. We're specifically
- // testing the case where the window is _not_ removed in between
- // the close-initiated flush request and the flush response.
- let windowClosed = BrowserTestUtils.windowClosed(newWin);
- newWin.close();
-
- state = JSON.parse(ss.getBrowserState());
- is(state.windows.length, initialWindows,
- "The new window should have been removed from the state");
-
- // Wait for our window to go away
- yield windowClosed;
-});
diff --git a/browser/components/sessionstore/test/browser_attributes.js b/browser/components/sessionstore/test/browser_attributes.js
deleted file mode 100644
index 40c7b4e02..000000000
--- a/browser/components/sessionstore/test/browser_attributes.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This test makes sure that we correctly preserve tab attributes when storing
- * and restoring tabs. It also ensures that we skip special attributes like
- * 'image', 'muted' and 'pending' that need to be handled differently or internally.
- */
-
-const PREF = "browser.sessionstore.restore_on_demand";
-
-add_task(function* test() {
- Services.prefs.setBoolPref(PREF, true)
- registerCleanupFunction(() => Services.prefs.clearUserPref(PREF));
-
- // Add a new tab with a nice icon.
- let tab = gBrowser.addTab("about:robots");
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // Check that the tab has 'image' and 'iconLoadingPrincipal' attributes.
- ok(tab.hasAttribute("image"), "tab.image exists");
- ok(tab.hasAttribute("iconLoadingPrincipal"), "tab.iconLoadingPrincipal exists");
-
- tab.toggleMuteAudio();
- // Check that the tab has a 'muted' attribute.
- ok(tab.hasAttribute("muted"), "tab.muted exists");
-
- // Make sure we do not persist 'image' or 'muted' attributes.
- ss.persistTabAttribute("image");
- ss.persistTabAttribute("muted");
- ss.persistTabAttribute("iconLoadingPrincipal");
- let {attributes} = JSON.parse(ss.getTabState(tab));
- ok(!("image" in attributes), "'image' attribute not saved");
- ok(!("iconLoadingPrincipal" in attributes), "'iconLoadingPrincipal' attribute not saved");
- ok(!("muted" in attributes), "'muted' attribute not saved");
- ok(!("custom" in attributes), "'custom' attribute not saved");
-
- // Test persisting a custom attribute.
- tab.setAttribute("custom", "foobar");
- ss.persistTabAttribute("custom");
-
- ({attributes} = JSON.parse(ss.getTabState(tab)));
- is(attributes.custom, "foobar", "'custom' attribute is correct");
-
- // Make sure we're backwards compatible and restore old 'image' attributes.
- let state = {
- entries: [{url: "about:mozilla"}],
- attributes: {custom: "foobaz"},
- image: gBrowser.getIcon(tab)
- };
-
- // Prepare a pending tab waiting to be restored.
- let promise = promiseTabRestoring(tab);
- ss.setTabState(tab, JSON.stringify(state));
- yield promise;
-
- ok(tab.hasAttribute("pending"), "tab is pending");
- is(gBrowser.getIcon(tab), state.image, "tab has correct icon");
- ok(!state.attributes.image, "'image' attribute not saved");
-
- // Let the pending tab load.
- gBrowser.selectedTab = tab;
- yield promiseTabRestored(tab);
-
- // Ensure no 'image' or 'pending' attributes are stored.
- ({attributes} = JSON.parse(ss.getTabState(tab)));
- ok(!("image" in attributes), "'image' attribute not saved");
- ok(!("pending" in attributes), "'pending' attribute not saved");
- is(attributes.custom, "foobaz", "'custom' attribute is correct");
-
- // Clean up.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_background_tab_crash.js b/browser/components/sessionstore/test/browser_background_tab_crash.js
deleted file mode 100644
index e804b177e..000000000
--- a/browser/components/sessionstore/test/browser_background_tab_crash.js
+++ /dev/null
@@ -1,221 +0,0 @@
-"use strict";
-
-/**
- * These tests the behaviour of the browser when background tabs crash,
- * while the foreground tab remains.
- *
- * The current behavioural rule is this: if only background tabs crash,
- * then only the first tab shown of that group should show the tab crash
- * page, and subsequent ones should restore on demand.
- */
-
-/**
- * Makes the current browser tab non-remote, and then sets up two remote
- * background tabs, ensuring that both belong to the same content process.
- * Callers should pass in a testing function that will execute (and possibly
- * yield Promises) taking the created background tabs as arguments. Once
- * the testing function completes, this function will take care of closing
- * the opened tabs.
- *
- * @param testFn (function)
- * A Promise-generating function that will be called once the tabs
- * are opened and ready.
- * @return Promise
- * Resolves once the testing function completes and the opened tabs
- * have been completely closed.
- */
-function* setupBackgroundTabs(testFn) {
- const REMOTE_PAGE = "http://www.example.com";
- const NON_REMOTE_PAGE = "about:robots";
-
- // Browse the initial tab to a non-remote page, which we'll have in the
- // foreground.
- let initialTab = gBrowser.selectedTab;
- let initialBrowser = initialTab.linkedBrowser;
- initialBrowser.loadURI(NON_REMOTE_PAGE);
- yield BrowserTestUtils.browserLoaded(initialBrowser);
-
- // Open some tabs that should be running in the content process.
- let tab1 =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, REMOTE_PAGE);
- let remoteBrowser1 = tab1.linkedBrowser;
- yield TabStateFlusher.flush(remoteBrowser1);
-
- let tab2 =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, REMOTE_PAGE);
- let remoteBrowser2 = tab2.linkedBrowser;
- yield TabStateFlusher.flush(remoteBrowser2);
-
- // Quick sanity check - the two browsers should be remote and share the
- // same childID, or else this test is not going to work.
- Assert.ok(remoteBrowser1.isRemoteBrowser,
- "Browser should be remote in order to crash.");
- Assert.ok(remoteBrowser2.isRemoteBrowser,
- "Browser should be remote in order to crash.");
- Assert.equal(remoteBrowser1.frameLoader.childID,
- remoteBrowser2.frameLoader.childID,
- "Both remote browsers should share the same content process.");
-
- // Now switch back to the non-remote browser...
- yield BrowserTestUtils.switchTab(gBrowser, initialTab);
-
- yield testFn([tab1, tab2]);
-
- yield BrowserTestUtils.removeTab(tab1);
- yield BrowserTestUtils.removeTab(tab2);
-}
-
-/**
- * Takes some set of background tabs that are assumed to all belong to
- * the same content process, and crashes them.
- *
- * @param tabs (Array(<xul:tab>))
- * The tabs to crash.
- * @return Promise
- * Resolves once the tabs have crashed and entered the pending
- * background state.
- */
-function* crashBackgroundTabs(tabs) {
- Assert.ok(tabs.length > 0, "Need to crash at least one tab.");
- for (let tab of tabs) {
- Assert.ok(tab.linkedBrowser.isRemoteBrowser, "tab is remote");
- }
-
- let remotenessChangePromises = tabs.map((t) => {
- return BrowserTestUtils.waitForEvent(t, "TabRemotenessChange");
- });
-
- let tabsRevived = tabs.map((t) => {
- return promiseTabRestoring(t);
- });
-
- yield BrowserTestUtils.crashBrowser(tabs[0].linkedBrowser, false);
- yield Promise.all(remotenessChangePromises);
- yield Promise.all(tabsRevived);
-
- // Both background tabs should now be in the pending restore
- // state.
- for (let tab of tabs) {
- Assert.ok(!tab.linkedBrowser.isRemoteBrowser, "tab is not remote");
- Assert.ok(!tab.linkedBrowser.hasAttribute("crashed"), "tab is not crashed");
- Assert.ok(tab.linkedBrowser.hasAttribute("pending"), "tab is pending");
- }
-}
-
-add_task(function* setup() {
- // We'll simplify by making sure we only ever one content process for this
- // test.
- yield SpecialPowers.pushPrefEnv({ set: [[ "dom.ipc.processCount", 1 ]] });
-
- // On debug builds, crashing tabs results in much thinking, which
- // slows down the test and results in intermittent test timeouts,
- // so we'll pump up the expected timeout for this test.
- requestLongerTimeout(5);
-});
-
-/**
- * Tests that if a content process crashes taking down only
- * background tabs, then the first of those tabs that the user
- * selects will show the tab crash page, but the rest will restore
- * on demand.
- */
-add_task(function* test_background_crash_simple() {
- yield setupBackgroundTabs(function*([tab1, tab2]) {
- // Let's crash one of those background tabs now...
- yield crashBackgroundTabs([tab1, tab2]);
-
- // Selecting the first tab should now send it to the tab crashed page.
- let tabCrashedPagePromise =
- BrowserTestUtils.waitForContentEvent(tab1.linkedBrowser,
- "AboutTabCrashedReady",
- false, null, true);
- yield BrowserTestUtils.switchTab(gBrowser, tab1);
- yield tabCrashedPagePromise;
-
- // Selecting the second tab should restore it.
- let tabRestored = promiseTabRestored(tab2);
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- yield tabRestored;
- });
-});
-
-/**
- * Tests that if a content process crashes taking down only
- * background tabs, and the user is configured to send backlogged
- * crash reports automatically, that the tab crashed page is not
- * shown.
- */
-add_task(function* test_background_crash_autosubmit_backlogged() {
- yield SpecialPowers.pushPrefEnv({
- set: [["browser.crashReports.unsubmittedCheck.autoSubmit2", true]],
- });
-
- yield setupBackgroundTabs(function*([tab1, tab2]) {
- // Let's crash one of those background tabs now...
- yield crashBackgroundTabs([tab1, tab2]);
-
- // Selecting the first tab should restore it.
- let tabRestored = promiseTabRestored(tab1);
- yield BrowserTestUtils.switchTab(gBrowser, tab1);
- yield tabRestored;
-
- // Selecting the second tab should restore it.
- tabRestored = promiseTabRestored(tab2);
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- yield tabRestored;
- });
-
- yield SpecialPowers.popPrefEnv();
-});
-
-/**
- * Tests that if there are two background tab crashes in a row, that
- * the two sets of background crashes don't interfere with one another.
- *
- * Specifically, if we start with two background tabs (1, 2) which crash,
- * and we visit 1, 1 should go to the tab crashed page. If we then have
- * two new background tabs (3, 4) crash, visiting 2 should still restore.
- * Visiting 4 should show us the tab crashed page, and then visiting 3
- * should restore.
- */
-add_task(function* test_background_crash_multiple() {
- let initialTab = gBrowser.selectedTab;
-
- yield setupBackgroundTabs(function*([tab1, tab2]) {
- // Let's crash one of those background tabs now...
- yield crashBackgroundTabs([tab1, tab2]);
-
- // Selecting the first tab should now send it to the tab crashed page.
- let tabCrashedPagePromise =
- BrowserTestUtils.waitForContentEvent(tab1.linkedBrowser,
- "AboutTabCrashedReady",
- false, null, true);
- yield BrowserTestUtils.switchTab(gBrowser, tab1);
- yield tabCrashedPagePromise;
-
- // Now switch back to the original non-remote tab...
- yield BrowserTestUtils.switchTab(gBrowser, initialTab);
-
- yield setupBackgroundTabs(function*([tab3, tab4]) {
- yield crashBackgroundTabs([tab3, tab4]);
-
- // Selecting the second tab should restore it.
- let tabRestored = promiseTabRestored(tab2);
- yield BrowserTestUtils.switchTab(gBrowser, tab2);
- yield tabRestored;
-
- // Selecting the fourth tab should now send it to the tab crashed page.
- let tabCrashedPagePromise =
- BrowserTestUtils.waitForContentEvent(tab4.linkedBrowser,
- "AboutTabCrashedReady",
- false, null, true);
- yield BrowserTestUtils.switchTab(gBrowser, tab4);
- yield tabCrashedPagePromise;
-
- // Selecting the third tab should restore it.
- tabRestored = promiseTabRestored(tab3);
- yield BrowserTestUtils.switchTab(gBrowser, tab3);
- yield tabRestored;
- });
- });
-});
diff --git a/browser/components/sessionstore/test/browser_backup_recovery.js b/browser/components/sessionstore/test/browser_backup_recovery.js
deleted file mode 100644
index 81f678856..000000000
--- a/browser/components/sessionstore/test/browser_backup_recovery.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This tests are for a sessionstore.js atomic backup.
-// Each test will wait for a write to the Session Store
-// before executing.
-
-var OS = Cu.import("resource://gre/modules/osfile.jsm", {}).OS;
-var {File, Constants, Path} = OS;
-
-const PREF_SS_INTERVAL = "browser.sessionstore.interval";
-const Paths = SessionFile.Paths;
-
-// A text decoder.
-var gDecoder = new TextDecoder();
-// Global variables that contain sessionstore.js and sessionstore.bak data for
-// comparison between tests.
-var gSSData;
-var gSSBakData;
-
-function promiseRead(path) {
- return File.read(path, {encoding: "utf-8"});
-}
-
-add_task(function* init() {
- // Make sure that we are not racing with SessionSaver's time based
- // saves.
- Services.prefs.setIntPref(PREF_SS_INTERVAL, 10000000);
- registerCleanupFunction(() => Services.prefs.clearUserPref(PREF_SS_INTERVAL));
-});
-
-add_task(function* test_creation() {
- // Create dummy sessionstore backups
- let OLD_BACKUP = Path.join(Constants.Path.profileDir, "sessionstore.bak");
- let OLD_UPGRADE_BACKUP = Path.join(Constants.Path.profileDir, "sessionstore.bak-0000000");
-
- yield File.writeAtomic(OLD_BACKUP, "sessionstore.bak");
- yield File.writeAtomic(OLD_UPGRADE_BACKUP, "sessionstore upgrade backup");
-
- yield SessionFile.wipe();
- yield SessionFile.read(); // Reinitializes SessionFile
-
- // Ensure none of the sessionstore files and backups exists
- for (let k of Paths.loadOrder) {
- ok(!(yield File.exists(Paths[k])), "After wipe " + k + " sessionstore file doesn't exist");
- }
- ok(!(yield File.exists(OLD_BACKUP)), "After wipe, old backup doesn't exist");
- ok(!(yield File.exists(OLD_UPGRADE_BACKUP)), "After wipe, old upgrade backup doesn't exist");
-
- // Open a new tab, save session, ensure that the correct files exist.
- let URL_BASE = "http://example.com/?atomic_backup_test_creation=" + Math.random();
- let URL = URL_BASE + "?first_write";
- let tab = gBrowser.addTab(URL);
-
- info("Testing situation after a single write");
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- yield SessionSaver.run();
-
- ok((yield File.exists(Paths.recovery)), "After write, recovery sessionstore file exists again");
- ok(!(yield File.exists(Paths.recoveryBackup)), "After write, recoveryBackup sessionstore doesn't exist");
- ok((yield promiseRead(Paths.recovery)).indexOf(URL) != -1, "Recovery sessionstore file contains the required tab");
- ok(!(yield File.exists(Paths.clean)), "After first write, clean shutdown sessionstore doesn't exist, since we haven't shutdown yet");
-
- // Open a second tab, save session, ensure that the correct files exist.
- info("Testing situation after a second write");
- let URL2 = URL_BASE + "?second_write";
- tab.linkedBrowser.loadURI(URL2);
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- yield SessionSaver.run();
-
- ok((yield File.exists(Paths.recovery)), "After second write, recovery sessionstore file still exists");
- ok((yield promiseRead(Paths.recovery)).indexOf(URL2) != -1, "Recovery sessionstore file contains the latest url");
- ok((yield File.exists(Paths.recoveryBackup)), "After write, recoveryBackup sessionstore now exists");
- let backup = yield promiseRead(Paths.recoveryBackup);
- ok(backup.indexOf(URL2) == -1, "Recovery backup doesn't contain the latest url");
- ok(backup.indexOf(URL) != -1, "Recovery backup contains the original url");
- ok(!(yield File.exists(Paths.clean)), "After first write, clean shutdown sessinstore doesn't exist, since we haven't shutdown yet");
-
- info("Reinitialize, ensure that we haven't leaked sensitive files");
- yield SessionFile.read(); // Reinitializes SessionFile
- yield SessionSaver.run();
- ok(!(yield File.exists(Paths.clean)), "After second write, clean shutdown sessonstore doesn't exist, since we haven't shutdown yet");
- ok(!(yield File.exists(Paths.upgradeBackup)), "After second write, clean shutdwn sessionstore doesn't exist, since we haven't shutdown yet");
- ok(!(yield File.exists(Paths.nextUpgradeBackup)), "After second write, clean sutdown sessionstore doesn't exist, since we haven't shutdown yet");
-
- gBrowser.removeTab(tab);
- yield SessionFile.wipe();
-});
-
-var promiseSource = Task.async(function*(name) {
- let URL = "http://example.com/?atomic_backup_test_recovery=" + Math.random() + "&name=" + name;
- let tab = gBrowser.addTab(URL);
-
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- yield SessionSaver.run();
- gBrowser.removeTab(tab);
-
- let SOURCE = yield promiseRead(Paths.recovery);
- yield SessionFile.wipe();
- return SOURCE;
-});
-
-add_task(function* test_recovery() {
- // Remove all files.
- yield SessionFile.wipe();
- info("Attempting to recover from the recovery file");
-
- // Create Paths.recovery, ensure that we can recover from it.
- let SOURCE = yield promiseSource("Paths.recovery");
- yield File.makeDir(Paths.backups);
- yield File.writeAtomic(Paths.recovery, SOURCE);
- is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file");
- yield SessionFile.wipe();
-
- info("Corrupting recovery file, attempting to recover from recovery backup");
- SOURCE = yield promiseSource("Paths.recoveryBackup");
- yield File.makeDir(Paths.backups);
- yield File.writeAtomic(Paths.recoveryBackup, SOURCE);
- yield File.writeAtomic(Paths.recovery, "<Invalid JSON>");
- is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file");
- yield SessionFile.wipe();
-});
-
-add_task(function* test_recovery_inaccessible() {
- // Can't do chmod() on non-UNIX platforms, we need that for this test.
- if (AppConstants.platform != "macosx" && AppConstants.platform != "linux") {
- return;
- }
-
- info("Making recovery file inaccessible, attempting to recover from recovery backup");
- let SOURCE_RECOVERY = yield promiseSource("Paths.recovery");
- let SOURCE = yield promiseSource("Paths.recoveryBackup");
- yield File.makeDir(Paths.backups);
- yield File.writeAtomic(Paths.recoveryBackup, SOURCE);
-
- // Write a valid recovery file but make it inaccessible.
- yield File.writeAtomic(Paths.recovery, SOURCE_RECOVERY);
- yield File.setPermissions(Paths.recovery, { unixMode: 0 });
-
- is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file");
- yield File.setPermissions(Paths.recovery, { unixMode: 0o644 });
-});
-
-add_task(function* test_clean() {
- yield SessionFile.wipe();
- let SOURCE = yield promiseSource("Paths.clean");
- yield File.writeAtomic(Paths.clean, SOURCE);
- yield SessionFile.read();
- yield SessionSaver.run();
- is((yield promiseRead(Paths.cleanBackup)), SOURCE, "After first read/write, clean shutdown file has been moved to cleanBackup");
-});
-
-
-/**
- * Tests loading of sessionstore when format version is known.
- */
-add_task(function* test_version() {
- info("Preparing sessionstore");
- let SOURCE = yield promiseSource("Paths.clean");
-
- // Check there's a format version number
- is(JSON.parse(SOURCE).version[0], "sessionrestore", "Found sessionstore format version");
-
- // Create Paths.clean file
- yield File.makeDir(Paths.backups);
- yield File.writeAtomic(Paths.clean, SOURCE);
-
- info("Attempting to recover from the clean file");
- // Ensure that we can recover from Paths.recovery
- is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the clean file");
-});
-
-/**
- * Tests fallback to previous backups if format version is unknown.
- */
-add_task(function* test_version_fallback() {
- info("Preparing data, making sure that it has a version number");
- let SOURCE = yield promiseSource("Paths.clean");
- let BACKUP_SOURCE = yield promiseSource("Paths.cleanBackup");
-
- is(JSON.parse(SOURCE).version[0], "sessionrestore", "Found sessionstore format version");
- is(JSON.parse(BACKUP_SOURCE).version[0], "sessionrestore", "Found backup sessionstore format version");
-
- yield File.makeDir(Paths.backups);
-
- info("Modifying format version number to something incorrect, to make sure that we disregard the file.");
- let parsedSource = JSON.parse(SOURCE);
- parsedSource.version[0] = "bookmarks";
- yield File.writeAtomic(Paths.clean, JSON.stringify(parsedSource));
- yield File.writeAtomic(Paths.cleanBackup, BACKUP_SOURCE);
- is((yield SessionFile.read()).source, BACKUP_SOURCE, "Recovered the correct source from the backup recovery file");
-
- info("Modifying format version number to a future version, to make sure that we disregard the file.");
- parsedSource = JSON.parse(SOURCE);
- parsedSource.version[1] = Number.MAX_SAFE_INTEGER;
- yield File.writeAtomic(Paths.clean, JSON.stringify(parsedSource));
- yield File.writeAtomic(Paths.cleanBackup, BACKUP_SOURCE);
- is((yield SessionFile.read()).source, BACKUP_SOURCE, "Recovered the correct source from the backup recovery file");
-});
-
-add_task(function* cleanup() {
- yield SessionFile.wipe();
-});
diff --git a/browser/components/sessionstore/test/browser_broadcast.js b/browser/components/sessionstore/test/browser_broadcast.js
deleted file mode 100644
index 95984d6d0..000000000
--- a/browser/components/sessionstore/test/browser_broadcast.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const INITIAL_VALUE = "browser_broadcast.js-initial-value-" + Date.now();
-
-/**
- * This test ensures we won't lose tab data queued in the content script when
- * closing a tab.
- */
-add_task(function flush_on_tabclose() {
- let tab = yield createTabWithStorageData(["http://example.com"]);
- let browser = tab.linkedBrowser;
-
- yield modifySessionStorage(browser, {test: "on-tab-close"});
- yield promiseRemoveTab(tab);
-
- let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://example.com"].test, "on-tab-close",
- "sessionStorage data has been flushed on TabClose");
-});
-
-/**
- * This test ensures we won't lose tab data queued in the content script when
- * duplicating a tab.
- */
-add_task(function flush_on_duplicate() {
- let tab = yield createTabWithStorageData(["http://example.com"]);
- let browser = tab.linkedBrowser;
-
- yield modifySessionStorage(browser, {test: "on-duplicate"});
- let tab2 = ss.duplicateTab(window, tab);
- yield promiseTabRestored(tab2);
-
- yield promiseRemoveTab(tab2);
- let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://example.com"].test, "on-duplicate",
- "sessionStorage data has been flushed when duplicating tabs");
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * This test ensures we won't lose tab data queued in the content script when
- * a window is closed.
- */
-add_task(function flush_on_windowclose() {
- let win = yield promiseNewWindow();
- let tab = yield createTabWithStorageData(["http://example.com"], win);
- let browser = tab.linkedBrowser;
-
- yield modifySessionStorage(browser, {test: "on-window-close"});
- yield BrowserTestUtils.closeWindow(win);
-
- let [{tabs: [_, {storage}]}] = JSON.parse(ss.getClosedWindowData());
- is(storage["http://example.com"].test, "on-window-close",
- "sessionStorage data has been flushed when closing a window");
-});
-
-/**
- * This test ensures that stale tab data is ignored when reusing a tab
- * (via e.g. setTabState) and does not overwrite the new data.
- */
-add_task(function flush_on_settabstate() {
- let tab = yield createTabWithStorageData(["http://example.com"]);
- let browser = tab.linkedBrowser;
-
- // Flush to make sure our tab state is up-to-date.
- yield TabStateFlusher.flush(browser);
-
- let state = ss.getTabState(tab);
- yield modifySessionStorage(browser, {test: "on-set-tab-state"});
-
- // Flush all data contained in the content script but send it using
- // asynchronous messages.
- TabStateFlusher.flush(browser);
-
- yield promiseTabState(tab, state);
-
- let {storage} = JSON.parse(ss.getTabState(tab));
- is(storage["http://example.com"].test, INITIAL_VALUE,
- "sessionStorage data has not been overwritten");
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * This test ensures that we won't lose tab data that has been sent
- * asynchronously just before closing a tab. Flushing must re-send all data
- * that hasn't been received by chrome, yet.
- */
-add_task(function flush_on_tabclose_racy() {
- let tab = yield createTabWithStorageData(["http://example.com"]);
- let browser = tab.linkedBrowser;
-
- // Flush to make sure we start with an empty queue.
- yield TabStateFlusher.flush(browser);
-
- yield modifySessionStorage(browser, {test: "on-tab-close-racy"});
-
- // Flush all data contained in the content script but send it using
- // asynchronous messages.
- TabStateFlusher.flush(browser);
- yield promiseRemoveTab(tab);
-
- let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://example.com"].test, "on-tab-close-racy",
- "sessionStorage data has been merged correctly to prevent data loss");
-});
-
-function promiseNewWindow() {
- let deferred = Promise.defer();
- whenNewWindowLoaded({private: false}, deferred.resolve);
- return deferred.promise;
-}
-
-function createTabWithStorageData(urls, win = window) {
- return Task.spawn(function task() {
- let tab = win.gBrowser.addTab();
- let browser = tab.linkedBrowser;
-
- for (let url of urls) {
- browser.loadURI(url);
- yield promiseBrowserLoaded(browser);
- yield modifySessionStorage(browser, {test: INITIAL_VALUE});
- }
-
- throw new Task.Result(tab);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_capabilities.js b/browser/components/sessionstore/test/browser_capabilities.js
deleted file mode 100644
index 456e41882..000000000
--- a/browser/components/sessionstore/test/browser_capabilities.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * These tests ensures that disabling features by flipping nsIDocShell.allow*
- * properties are (re)stored as disabled. Disallowed features must be
- * re-enabled when the tab is re-used by another tab restoration.
- */
-add_task(function docshell_capabilities() {
- let tab = yield createTab();
- let browser = tab.linkedBrowser;
- let docShell = browser.docShell;
-
- // Get the list of capabilities for docShells.
- let flags = Object.keys(docShell).filter(k => k.startsWith("allow"));
-
- // Check that everything is allowed by default for new tabs.
- let state = JSON.parse(ss.getTabState(tab));
- ok(!("disallow" in state), "everything allowed by default");
- ok(flags.every(f => docShell[f]), "all flags set to true");
-
- // Flip a couple of allow* flags.
- docShell.allowImages = false;
- docShell.allowMetaRedirects = false;
-
- // Now reload the document to ensure that these capabilities
- // are taken into account.
- browser.reload();
- yield promiseBrowserLoaded(browser);
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
-
- // Check that we correctly save disallowed features.
- let disallowedState = JSON.parse(ss.getTabState(tab));
- let disallow = new Set(disallowedState.disallow.split(","));
- ok(disallow.has("Images"), "images not allowed");
- ok(disallow.has("MetaRedirects"), "meta redirects not allowed");
- is(disallow.size, 2, "two capabilities disallowed");
-
- // Reuse the tab to restore a new, clean state into it.
- yield promiseTabState(tab, {entries: [{url: "about:robots"}]});
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
-
- // After restoring disallowed features must be available again.
- state = JSON.parse(ss.getTabState(tab));
- ok(!("disallow" in state), "everything allowed again");
- ok(flags.every(f => docShell[f]), "all flags set to true");
-
- // Restore the state with disallowed features.
- yield promiseTabState(tab, disallowedState);
-
- // Check that docShell flags are set.
- ok(!docShell.allowImages, "images not allowed");
- ok(!docShell.allowMetaRedirects, "meta redirects not allowed");
-
- // Check that we correctly restored features as disabled.
- state = JSON.parse(ss.getTabState(tab));
- disallow = new Set(state.disallow.split(","));
- ok(disallow.has("Images"), "images not allowed anymore");
- ok(disallow.has("MetaRedirects"), "meta redirects not allowed anymore");
- is(disallow.size, 2, "two capabilities disallowed");
-
- // Clean up after ourselves.
- gBrowser.removeTab(tab);
-});
-
-function createTab() {
- let tab = gBrowser.addTab("about:mozilla");
- let browser = tab.linkedBrowser;
- return promiseBrowserLoaded(browser).then(() => tab);
-}
diff --git a/browser/components/sessionstore/test/browser_cleaner.js b/browser/components/sessionstore/test/browser_cleaner.js
deleted file mode 100644
index 921d7d3e4..000000000
--- a/browser/components/sessionstore/test/browser_cleaner.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-/*
- * This test ensures that Session Restore eventually forgets about
- * tabs and windows that have been closed a long time ago.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-
-const LONG_TIME_AGO = 1;
-
-const URL_TAB1 = "http://example.com/browser_cleaner.js?newtab1=" + Math.random();
-const URL_TAB2 = "http://example.com/browser_cleaner.js?newtab2=" + Math.random();
-const URL_NEWWIN = "http://example.com/browser_cleaner.js?newwin=" + Math.random();
-
-function isRecent(stamp) {
- is(typeof stamp, "number", "This is a timestamp");
- return Date.now() - stamp <= 60000;
-}
-
-function promiseCleanup () {
- info("Cleaning up browser");
-
- return promiseBrowserState(getClosedState());
-};
-
-function getClosedState() {
- return Cu.cloneInto(CLOSED_STATE, {});
-}
-
-var CLOSED_STATE;
-
-add_task(function* init() {
- forgetClosedWindows();
- while (ss.getClosedTabCount(window) > 0) {
- ss.forgetClosedTab(window, 0);
- }
-});
-
-add_task(function* test_open_and_close() {
- let newTab1 = gBrowser.addTab(URL_TAB1);
- yield promiseBrowserLoaded(newTab1.linkedBrowser);
-
- let newTab2 = gBrowser.addTab(URL_TAB2);
- yield promiseBrowserLoaded(newTab2.linkedBrowser);
-
- let newWin = yield promiseNewWindowLoaded();
- let tab = newWin.gBrowser.addTab(URL_NEWWIN);
-
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- yield TabStateFlusher.flushWindow(window);
- yield TabStateFlusher.flushWindow(newWin);
-
- info("1. Making sure that before closing, we don't have closedAt");
- // For the moment, no "closedAt"
- let state = JSON.parse(ss.getBrowserState());
- is(state.windows[0].closedAt || false, false, "1. Main window doesn't have closedAt");
- is(state.windows[1].closedAt || false, false, "1. Second window doesn't have closedAt");
- is(state.windows[0].tabs[0].closedAt || false, false, "1. First tab doesn't have closedAt");
- is(state.windows[0].tabs[1].closedAt || false, false, "1. Second tab doesn't have closedAt");
-
- info("2. Making sure that after closing, we have closedAt");
-
- // Now close stuff, this should add closeAt
- yield BrowserTestUtils.closeWindow(newWin);
- yield promiseRemoveTab(newTab1);
- yield promiseRemoveTab(newTab2);
-
- state = CLOSED_STATE = JSON.parse(ss.getBrowserState());
-
- is(state.windows[0].closedAt || false, false, "2. Main window doesn't have closedAt");
- ok(isRecent(state._closedWindows[0].closedAt), "2. Second window was closed recently");
- ok(isRecent(state.windows[0]._closedTabs[0].closedAt), "2. First tab was closed recently");
- ok(isRecent(state.windows[0]._closedTabs[1].closedAt), "2. Second tab was closed recently");
-});
-
-
-add_task(function* test_restore() {
- info("3. Making sure that after restoring, we don't have closedAt");
- yield promiseBrowserState(CLOSED_STATE);
-
- let newWin = ss.undoCloseWindow(0);
- yield promiseDelayedStartupFinished(newWin);
-
- let newTab2 = ss.undoCloseTab(window, 0);
- yield promiseTabRestored(newTab2);
-
- let newTab1 = ss.undoCloseTab(window, 0);
- yield promiseTabRestored(newTab1);
-
- let state = JSON.parse(ss.getBrowserState());
-
- is(state.windows[0].closedAt || false, false, "3. Main window doesn't have closedAt");
- is(state.windows[1].closedAt || false, false, "3. Second window doesn't have closedAt");
- is(state.windows[0].tabs[0].closedAt || false, false, "3. First tab doesn't have closedAt");
- is(state.windows[0].tabs[1].closedAt || false, false, "3. Second tab doesn't have closedAt");
-
- yield BrowserTestUtils.closeWindow(newWin);
- gBrowser.removeTab(newTab1);
- gBrowser.removeTab(newTab2);
-});
-
-
-add_task(function* test_old_data() {
- info("4. Removing closedAt from the sessionstore, making sure that it is added upon idle-daily");
-
- let state = getClosedState();
- delete state._closedWindows[0].closedAt;
- delete state.windows[0]._closedTabs[0].closedAt;
- delete state.windows[0]._closedTabs[1].closedAt;
- yield promiseBrowserState(state);
-
- info("Sending idle-daily");
- Services.obs.notifyObservers(null, "idle-daily", "");
- info("Sent idle-daily");
-
- state = JSON.parse(ss.getBrowserState());
- is(state.windows[0].closedAt || false, false, "4. Main window doesn't have closedAt");
- ok(isRecent(state._closedWindows[0].closedAt), "4. Second window was closed recently");
- ok(isRecent(state.windows[0]._closedTabs[0].closedAt), "4. First tab was closed recently");
- ok(isRecent(state.windows[0]._closedTabs[1].closedAt), "4. Second tab was closed recently");
- yield promiseCleanup();
-});
-
-
-add_task(function* test_cleanup() {
-
- info("5. Altering closedAt to an old date, making sure that stuff gets collected, eventually");
- yield promiseCleanup();
-
- let state = getClosedState();
- state._closedWindows[0].closedAt = LONG_TIME_AGO;
- state.windows[0]._closedTabs[0].closedAt = LONG_TIME_AGO;
- state.windows[0]._closedTabs[1].closedAt = Date.now();
- let url = state.windows[0]._closedTabs[1].state.entries[0].url;
-
- yield promiseBrowserState(state);
-
- info("Sending idle-daily");
- Services.obs.notifyObservers(null, "idle-daily", "");
- info("Sent idle-daily");
-
- state = JSON.parse(ss.getBrowserState());
- is(state._closedWindows[0], undefined, "5. Second window was forgotten");
-
- is(state.windows[0]._closedTabs.length, 1, "5. Only one closed tab left");
- is(state.windows[0]._closedTabs[0].state.entries[0].url, url, "5. The second tab is still here");
- yield promiseCleanup();
-});
-
diff --git a/browser/components/sessionstore/test/browser_cookies.js b/browser/components/sessionstore/test/browser_cookies.js
deleted file mode 100644
index cc5b41e4b..000000000
--- a/browser/components/sessionstore/test/browser_cookies.js
+++ /dev/null
@@ -1,173 +0,0 @@
-"use strict";
-
-const PATH = "/browser/browser/components/sessionstore/test/";
-
-/**
- * Remove all cookies to start off a clean slate.
- */
-add_task(function* test_setup() {
- requestLongerTimeout(2);
- Services.cookies.removeAll();
-});
-
-/**
- * Test multiple scenarios with different Set-Cookie header domain= params.
- */
-add_task(function* test_run() {
- // Set-Cookie: foobar=random()
- // The domain of the cookie should be the request domain (www.example.com).
- // We should collect data only for the request domain, no parent or subdomains.
- yield testCookieCollection({
- host: "http://www.example.com",
- cookieHost: "www.example.com",
- cookieURIs: ["http://www.example.com" + PATH],
- noCookieURIs: ["http://example.com/" + PATH]
- });
-
- // Set-Cookie: foobar=random()
- // The domain of the cookie should be the request domain (example.com).
- // We should collect data only for the request domain, no parent or subdomains.
- yield testCookieCollection({
- host: "http://example.com",
- cookieHost: "example.com",
- cookieURIs: ["http://example.com" + PATH],
- noCookieURIs: ["http://www.example.com/" + PATH]
- });
-
- // Set-Cookie: foobar=random(); Domain=example.com
- // The domain of the cookie should be the given one (.example.com).
- // We should collect data for the given domain and its subdomains.
- yield testCookieCollection({
- host: "http://example.com",
- domain: "example.com",
- cookieHost: ".example.com",
- cookieURIs: ["http://example.com" + PATH, "http://www.example.com/" + PATH],
- noCookieURIs: ["about:robots"]
- });
-
- // Set-Cookie: foobar=random(); Domain=.example.com
- // The domain of the cookie should be the given one (.example.com).
- // We should collect data for the given domain and its subdomains.
- yield testCookieCollection({
- host: "http://example.com",
- domain: ".example.com",
- cookieHost: ".example.com",
- cookieURIs: ["http://example.com" + PATH, "http://www.example.com/" + PATH],
- noCookieURIs: ["about:robots"]
- });
-
- // Set-Cookie: foobar=random(); Domain=www.example.com
- // The domain of the cookie should be the given one (.www.example.com).
- // We should collect data for the given domain and its subdomains.
- yield testCookieCollection({
- host: "http://www.example.com",
- domain: "www.example.com",
- cookieHost: ".www.example.com",
- cookieURIs: ["http://www.example.com/" + PATH],
- noCookieURIs: ["http://example.com"]
- });
-
- // Set-Cookie: foobar=random(); Domain=.www.example.com
- // The domain of the cookie should be the given one (.www.example.com).
- // We should collect data for the given domain and its subdomains.
- yield testCookieCollection({
- host: "http://www.example.com",
- domain: ".www.example.com",
- cookieHost: ".www.example.com",
- cookieURIs: ["http://www.example.com/" + PATH],
- noCookieURIs: ["http://example.com"]
- });
-});
-
-/**
- * Generic test function to check sessionstore's cookie collection module with
- * different cookie domains given in the Set-Cookie header. See above for some
- * usage examples.
- */
-var testCookieCollection = Task.async(function (params) {
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
-
- let urlParams = new URLSearchParams();
- let value = Math.random();
- urlParams.append("value", value);
-
- if (params.domain) {
- urlParams.append("domain", params.domain);
- }
-
- // Construct request URI.
- let uri = `${params.host}${PATH}browser_cookies.sjs?${urlParams}`;
-
- // Wait for the browser to load and the cookie to be set.
- // These two events can probably happen in no particular order,
- // so let's wait for them in parallel.
- yield Promise.all([
- waitForNewCookie(),
- replaceCurrentURI(browser, uri)
- ]);
-
- // Check all URIs for which the cookie should be collected.
- for (let uri of params.cookieURIs || []) {
- yield replaceCurrentURI(browser, uri);
-
- // Check the cookie.
- let cookie = getCookie();
- is(cookie.host, params.cookieHost, "cookie host is correct");
- is(cookie.path, PATH, "cookie path is correct");
- is(cookie.name, "foobar", "cookie name is correct");
- is(cookie.value, value, "cookie value is correct");
- }
-
- // Check all URIs for which the cookie should NOT be collected.
- for (let uri of params.noCookieURIs || []) {
- yield replaceCurrentURI(browser, uri);
-
- // Cookie should be ignored.
- ok(!getCookie(), "no cookie collected");
- }
-
- // Clean up.
- gBrowser.removeTab(tab);
- Services.cookies.removeAll();
-});
-
-/**
- * Replace the current URI of the given browser by loading a new URI. The
- * browser's session history will be completely replaced. This function ensures
- * that the parent process has the lastest shistory data before resolving.
- */
-var replaceCurrentURI = Task.async(function* (browser, uri) {
- // Replace the tab's current URI with the parent domain.
- let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY;
- browser.loadURIWithFlags(uri, flags);
- yield promiseBrowserLoaded(browser);
-
- // Ensure the tab's session history is up-to-date.
- yield TabStateFlusher.flush(browser);
-});
-
-/**
- * Waits for a new "*example.com" cookie to be added.
- */
-function waitForNewCookie() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(subj, topic, data) {
- let cookie = subj.QueryInterface(Ci.nsICookie2);
- if (data == "added" && cookie.host.endsWith("example.com")) {
- Services.obs.removeObserver(observer, topic);
- resolve();
- }
- }, "cookie-changed", false);
- });
-}
-
-/**
- * Retrieves the first cookie in the first window from the current sessionstore
- * state.
- */
-function getCookie() {
- let state = JSON.parse(ss.getWindowState(window));
- let cookies = state.windows[0].cookies || [];
- return cookies[0] || null;
-}
diff --git a/browser/components/sessionstore/test/browser_cookies.sjs b/browser/components/sessionstore/test/browser_cookies.sjs
deleted file mode 100644
index bffbd66d9..000000000
--- a/browser/components/sessionstore/test/browser_cookies.sjs
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Components.utils.importGlobalProperties(["URLSearchParams"]);
-
-function handleRequest(req, resp) {
- resp.setStatusLine(req.httpVersion, 200);
-
- let params = new URLSearchParams(req.queryString);
- let value = params.get("value");
-
- let domain = "";
- if (params.has("domain")) {
- domain = `; Domain=${params.get("domain")}`;
- }
-
- resp.setHeader("Set-Cookie", `foobar=${value}${domain}`);
- resp.write("<meta charset=utf-8>hi");
-}
diff --git a/browser/components/sessionstore/test/browser_crashedTabs.js b/browser/components/sessionstore/test/browser_crashedTabs.js
deleted file mode 100644
index 5841d536a..000000000
--- a/browser/components/sessionstore/test/browser_crashedTabs.js
+++ /dev/null
@@ -1,462 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-requestLongerTimeout(10);
-
-const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page.";
-
-// Turn off tab animations for testing and use a single content process
-// for these tests since we want to test tabs within the crashing process here.
-add_task(function* test_initialize() {
- yield SpecialPowers.pushPrefEnv({
- set: [
- [ "dom.ipc.processCount", 1 ],
- [ "browser.tabs.animate", false]
- ] });
-});
-
-// Allow tabs to restore on demand so we can test pending states
-Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
-
-function clickButton(browser, id) {
- info("Clicking " + id);
-
- let frame_script = (id) => {
- let button = content.document.getElementById(id);
- button.click();
- };
-
- let mm = browser.messageManager;
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")('" + id + "');", false);
-}
-
-/**
- * Checks the documentURI of the root document of a remote browser
- * to see if it equals URI. Returns a Promise that resolves if
- * there is a match, and rejects with an error message if they
- * do not match.
- *
- * @param browser
- * The remote <xul:browser> to check the root document URI in.
- * @param URI
- * A string to match the root document URI against.
- * @return Promise
- */
-function promiseContentDocumentURIEquals(browser, URI) {
- return new Promise((resolve, reject) => {
- let frame_script = () => {
- sendAsyncMessage("test:documenturi", {
- uri: content.document.documentURI,
- });
- };
-
- let mm = browser.messageManager;
- mm.addMessageListener("test:documenturi", function onMessage(message) {
- mm.removeMessageListener("test:documenturi", onMessage);
- let contentURI = message.data.uri;
- if (contentURI == URI) {
- resolve();
- } else {
- reject(`Content has URI ${contentURI} which does not match ${URI}`);
- }
- });
-
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", false);
- });
-}
-
-/**
- * Checks the window.history.length of the root window of a remote
- * browser to see if it equals length. Returns a Promise that resolves
- * if there is a match, and rejects with an error message if they
- * do not match.
- *
- * @param browser
- * The remote <xul:browser> to check the root window.history.length
- * @param length
- * The expected history length
- * @return Promise
- */
-function promiseHistoryLength(browser, length) {
- return new Promise((resolve, reject) => {
- let frame_script = () => {
- sendAsyncMessage("test:historylength", {
- length: content.history.length,
- });
- };
-
- let mm = browser.messageManager;
- mm.addMessageListener("test:historylength", function onMessage(message) {
- mm.removeMessageListener("test:historylength", onMessage);
- let contentLength = message.data.length;
- if (contentLength == length) {
- resolve();
- } else {
- reject(`Content has window.history.length ${contentLength} which does ` +
- `not equal expected ${length}`);
- }
- });
-
- mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", false);
- });
-}
-
-/**
- * Returns a Promise that resolves when a browser has fired the
- * AboutTabCrashedReady event.
- *
- * @param browser
- * The remote <xul:browser> that will fire the event.
- * @return Promise
- */
-function promiseTabCrashedReady(browser) {
- return new Promise((resolve) => {
- browser.addEventListener("AboutTabCrashedReady", function ready(e) {
- browser.removeEventListener("AboutTabCrashedReady", ready, false, true);
- resolve();
- }, false, true);
- });
-}
-
-/**
- * Checks that if a tab crashes, that information about the tab crashed
- * page does not get added to the tab history.
- */
-add_task(function test_crash_page_not_in_history() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- // Check the tab state and make sure the tab crashed page isn't
- // mentioned.
- let {entries} = JSON.parse(ss.getTabState(newTab));
- is(entries.length, 1, "Should have a single history entry");
- is(entries[0].url, PAGE_1,
- "Single entry should be the page we visited before crashing");
-
- gBrowser.removeTab(newTab);
-});
-
-/**
- * Checks that if a tab crashes, that when we browse away from that page
- * to a non-blacklisted site (so the browser becomes remote again), that
- * we record history for that new visit.
- */
-add_task(function test_revived_history_from_remote() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- // Browse to a new site that will cause the browser to
- // become remote again.
- browser.loadURI(PAGE_2);
- yield promiseTabRestored(newTab);
- ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore.");
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield TabStateFlusher.flush(browser);
-
- // Check the tab state and make sure the tab crashed page isn't
- // mentioned.
- let {entries} = JSON.parse(ss.getTabState(newTab));
- is(entries.length, 2, "Should have two history entries");
- is(entries[0].url, PAGE_1,
- "First entry should be the page we visited before crashing");
- is(entries[1].url, PAGE_2,
- "Second entry should be the page we visited after crashing");
-
- gBrowser.removeTab(newTab);
-});
-
-/**
- * Checks that if a tab crashes, that when we browse away from that page
- * to a blacklisted site (so the browser stays non-remote), that
- * we record history for that new visit.
- */
-add_task(function test_revived_history_from_non_remote() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- // Browse to a new site that will not cause the browser to
- // become remote again.
- browser.loadURI("about:mozilla");
- yield promiseBrowserLoaded(browser);
- ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore.");
- ok(!browser.isRemoteBrowser, "Should not be a remote browser");
- yield TabStateFlusher.flush(browser);
-
- // Check the tab state and make sure the tab crashed page isn't
- // mentioned.
- let {entries} = JSON.parse(ss.getTabState(newTab));
- is(entries.length, 2, "Should have two history entries");
- is(entries[0].url, PAGE_1,
- "First entry should be the page we visited before crashing");
- is(entries[1].url, "about:mozilla",
- "Second entry should be the page we visited after crashing");
-
- gBrowser.removeTab(newTab);
-});
-
-/**
- * Checks that we can revive a crashed tab back to the page that
- * it was on when it crashed.
- */
-add_task(function test_revive_tab_from_session_store() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- let newTab2 = gBrowser.addTab();
- let browser2 = newTab2.linkedBrowser;
- ok(browser2.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser2);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_2);
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
- // Background tabs should not be crashed, but should be in the "to be restored"
- // state.
- ok(!newTab2.hasAttribute("crashed"), "Second tab should not be crashed.");
- ok(newTab2.hasAttribute("pending"), "Second tab should be pending.");
-
- // Use SessionStore to revive the first tab
- clickButton(browser, "restoreTab");
- yield promiseTabRestored(newTab);
- ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore.");
- ok(newTab2.hasAttribute("pending"), "Second tab should still be pending.");
-
- // We can't just check browser.currentURI.spec, because from
- // the outside, a crashed tab has the same URI as the page
- // it crashed on (much like an about:neterror page). Instead,
- // we have to use the documentURI on the content.
- yield promiseContentDocumentURIEquals(browser, PAGE_2);
-
- // We should also have two entries in the browser history.
- yield promiseHistoryLength(browser, 2);
-
- gBrowser.removeTab(newTab);
- gBrowser.removeTab(newTab2);
-});
-
-/**
- * Checks that we can revive multiple crashed tabs back to the pages
- * that they were on when they crashed.
- */
-add_task(function test_revive_all_tabs_from_session_store() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- // In order to see a second about:tabcrashed page, we'll need
- // a second window, since only selected tabs will show
- // about:tabcrashed.
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
- let newTab2 = win2.gBrowser.addTab(PAGE_1);
- win2.gBrowser.selectedTab = newTab2;
- let browser2 = newTab2.linkedBrowser;
- ok(browser2.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser2);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_2);
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
- yield TabStateFlusher.flush(browser2);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
- // Both tabs should now be crashed.
- is(newTab.getAttribute("crashed"), "true", "First tab should be crashed");
- is(newTab2.getAttribute("crashed"), "true", "Second window tab should be crashed");
-
- // Use SessionStore to revive all the tabs
- clickButton(browser, "restoreAll");
- yield promiseTabRestored(newTab);
- ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore.");
- ok(!newTab.hasAttribute("pending"), "Tab shouldn't be pending.");
- ok(!newTab2.hasAttribute("crashed"), "Second tab shouldn't be marked as crashed anymore.");
- ok(!newTab2.hasAttribute("pending"), "Second tab shouldn't be pending.");
-
- // We can't just check browser.currentURI.spec, because from
- // the outside, a crashed tab has the same URI as the page
- // it crashed on (much like an about:neterror page). Instead,
- // we have to use the documentURI on the content.
- yield promiseContentDocumentURIEquals(browser, PAGE_2);
- yield promiseContentDocumentURIEquals(browser2, PAGE_1);
-
- // We should also have two entries in the browser history.
- yield promiseHistoryLength(browser, 2);
-
- yield BrowserTestUtils.closeWindow(win2);
- gBrowser.removeTab(newTab);
-});
-
-/**
- * Checks that about:tabcrashed can close the current tab
- */
-add_task(function test_close_tab_after_crash() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- let promise = promiseEvent(gBrowser.tabContainer, "TabClose");
-
- // Click the close tab button
- clickButton(browser, "closeTab");
- yield promise;
-
- is(gBrowser.tabs.length, 1, "Should have closed the tab");
-});
-
-
-/**
- * Checks that "restore all" button is only shown if more than one tab
- * is showing about:tabcrashed
- */
-add_task(function* test_hide_restore_all_button() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- let doc = browser.contentDocument;
- let restoreAllButton = doc.getElementById("restoreAll");
- let restoreOneButton = doc.getElementById("restoreTab");
-
- let restoreAllStyles = window.getComputedStyle(restoreAllButton);
- is(restoreAllStyles.display, "none", "Restore All button should be hidden");
- ok(restoreOneButton.classList.contains("primary"), "Restore Tab button should have the primary class");
-
- let newTab2 = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
-
- browser.loadURI(PAGE_2);
- yield promiseBrowserLoaded(browser);
-
- // Load up a second window so we can get another tab to show
- // about:tabcrashed
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
- let newTab3 = win2.gBrowser.addTab(PAGE_2);
- win2.gBrowser.selectedTab = newTab3;
- let otherWinBrowser = newTab3.linkedBrowser;
- yield promiseBrowserLoaded(otherWinBrowser);
- // We'll need to make sure the second tab's browser has finished
- // sending its AboutTabCrashedReady event before we know for
- // sure whether or not we're showing the right Restore buttons.
- let otherBrowserReady = promiseTabCrashedReady(otherWinBrowser);
-
- // Crash the first tab.
- yield BrowserTestUtils.crashBrowser(browser);
- yield otherBrowserReady;
-
- doc = browser.contentDocument;
- restoreAllButton = doc.getElementById("restoreAll");
- restoreOneButton = doc.getElementById("restoreTab");
-
- restoreAllStyles = window.getComputedStyle(restoreAllButton);
- isnot(restoreAllStyles.display, "none", "Restore All button should not be hidden");
- ok(!(restoreOneButton.classList.contains("primary")), "Restore Tab button should not have the primary class");
-
- yield BrowserTestUtils.closeWindow(win2);
- gBrowser.removeTab(newTab);
- gBrowser.removeTab(newTab2);
-});
-
-add_task(function* test_aboutcrashedtabzoom() {
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
- ok(browser.isRemoteBrowser, "Should be a remote browser");
- yield promiseBrowserLoaded(browser);
-
- browser.loadURI(PAGE_1);
- yield promiseBrowserLoaded(browser);
-
- FullZoom.enlarge();
- let zoomLevel = ZoomManager.getZoomForBrowser(browser);
- ok(zoomLevel !== 1, "should have enlarged");
-
- yield TabStateFlusher.flush(browser);
-
- // Crash the tab
- yield BrowserTestUtils.crashBrowser(browser);
-
- ok(ZoomManager.getZoomForBrowser(browser) === 1, "zoom should have reset on crash");
-
- clickButton(browser, "restoreTab");
- yield promiseTabRestored(newTab);
-
- ok(ZoomManager.getZoomForBrowser(browser) === zoomLevel, "zoom should have gone back to enlarged");
- FullZoom.reset();
-
- gBrowser.removeTab(newTab);
-});
diff --git a/browser/components/sessionstore/test/browser_dying_cache.js b/browser/components/sessionstore/test/browser_dying_cache.js
deleted file mode 100644
index c573aa5d4..000000000
--- a/browser/components/sessionstore/test/browser_dying_cache.js
+++ /dev/null
@@ -1,66 +0,0 @@
-"use strict";
-
-/**
- * This test ensures that after closing a window we keep its state data around
- * as long as something keeps a reference to it. It should only be possible to
- * read data after closing - writing should fail.
- */
-
-add_task(function* test() {
- // Open a new window.
- let win = yield promiseNewWindowLoaded();
-
- // Load some URL in the current tab.
- let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY;
- win.gBrowser.selectedBrowser.loadURIWithFlags("about:robots", flags);
- yield promiseBrowserLoaded(win.gBrowser.selectedBrowser);
-
- // Open a second tab and close the first one.
- let tab = win.gBrowser.addTab("about:mozilla");
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- yield promiseRemoveTab(win.gBrowser.tabs[0]);
-
- // Make sure our window is still tracked by sessionstore
- // and the window state is as expected.
- ok("__SSi" in win, "window is being tracked by sessionstore");
- ss.setWindowValue(win, "foo", "bar");
- checkWindowState(win);
-
- let state = ss.getWindowState(win);
- let closedTabData = ss.getClosedTabData(win);
-
- // Close our window.
- yield BrowserTestUtils.closeWindow(win);
-
- // SessionStore should no longer track our window
- // but it should still report the same state.
- ok(!("__SSi" in win), "sessionstore does no longer track our window");
- checkWindowState(win);
-
- // Make sure we're not allowed to modify state data.
- Assert.throws(() => ss.setWindowState(win, {}),
- "we're not allowed to modify state data anymore");
- Assert.throws(() => ss.setWindowValue(win, "foo", "baz"),
- "we're not allowed to modify state data anymore");
-});
-
-function checkWindowState(window) {
- let {windows: [{tabs}]} = JSON.parse(ss.getWindowState(window));
- is(tabs.length, 1, "the window has a single tab");
- is(tabs[0].entries[0].url, "about:mozilla", "the tab is about:mozilla");
-
- is(ss.getClosedTabCount(window), 1, "the window has one closed tab");
- let [{state: {entries: [{url}]}}] = JSON.parse(ss.getClosedTabData(window));
- is(url, "about:robots", "the closed tab is about:robots");
-
- is(ss.getWindowValue(window, "foo"), "bar", "correct extData value");
-}
-
-function shouldThrow(f) {
- try {
- f();
- } catch (e) {
- return true;
- }
-}
diff --git a/browser/components/sessionstore/test/browser_dynamic_frames.js b/browser/components/sessionstore/test/browser_dynamic_frames.js
deleted file mode 100644
index e4355fee3..000000000
--- a/browser/components/sessionstore/test/browser_dynamic_frames.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Ensure that static frames of framesets are serialized but dynamically
- * inserted iframes are ignored.
- */
-add_task(function () {
- // This URL has the following frames:
- // + data:text/html,A (static)
- // + data:text/html,B (static)
- // + data:text/html,C (dynamic iframe)
- const URL = "data:text/html;charset=utf-8," +
- "<frameset cols=50%25,50%25><frame src='data:text/html,A'>" +
- "<frame src='data:text/html,B'></frameset>" +
- "<script>var i=document.createElement('iframe');" +
- "i.setAttribute('src', 'data:text/html,C');" +
- "document.body.appendChild(i);</script>";
-
- // Add a new tab with two "static" and one "dynamic" frame.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
-
- // Check URLs.
- ok(entries[0].url.startsWith("data:text/html"), "correct root url");
- is(entries[0].children[0].url, "data:text/html,A", "correct url for 1st frame");
- is(entries[0].children[1].url, "data:text/html,B", "correct url for 2nd frame");
-
- // Check the number of children.
- is(entries.length, 1, "there is one root entry ...");
- is(entries[0].children.length, 2, "... with two child entries");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that iframes created by the network parser are serialized but
- * dynamically inserted iframes are ignored. Navigating a subframe should
- * create a second root entry that doesn't contain any dynamic children either.
- */
-add_task(function () {
- // This URL has the following frames:
- // + data:text/html,A (static)
- // + data:text/html,C (dynamic iframe)
- const URL = "data:text/html;charset=utf-8," +
- "<iframe name=t src='data:text/html,A'></iframe>" +
- "<a id=lnk href='data:text/html,B' target=t>clickme</a>" +
- "<script>var i=document.createElement('iframe');" +
- "i.setAttribute('src', 'data:text/html,C');" +
- "document.body.appendChild(i);</script>";
-
- // Add a new tab with one "static" and one "dynamic" frame.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
-
- // Check URLs.
- ok(entries[0].url.startsWith("data:text/html"), "correct root url");
- ok(!entries[0].children, "no children collected");
-
- // Navigate the subframe.
- browser.messageManager.sendAsyncMessage("ss-test:click", {id: "lnk"});
- yield promiseBrowserLoaded(browser, false /* don't ignore subframes */);
-
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
-
- // Check URLs.
- ok(entries[0].url.startsWith("data:text/html"), "correct 1st root url");
- ok(entries[1].url.startsWith("data:text/html"), "correct 2nd root url");
- ok(!entries.children, "no children collected");
- ok(!entries[0].children, "no children collected");
- ok(!entries[1].children, "no children collected");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_forget_async_closings.js b/browser/components/sessionstore/test/browser_forget_async_closings.js
deleted file mode 100644
index c130ec5ad..000000000
--- a/browser/components/sessionstore/test/browser_forget_async_closings.js
+++ /dev/null
@@ -1,144 +0,0 @@
-"use strict";
-
-const PAGE = "http://example.com/";
-
-/**
- * Creates a tab in the current window worth storing in the
- * closedTabs array, and then closes it. Runs a synchronous
- * forgetFn passed in that should cause us to forget the tab,
- * and then ensures that after the tab has sent its final
- * update message that we didn't accidentally store it in
- * the closedTabs array.
- *
- * @param forgetFn (function)
- * A synchronous function that should cause the tab
- * to be forgotten.
- * @returns Promise
- */
-let forgetTabHelper = Task.async(function*(forgetFn) {
- // We want to suppress all non-final updates from the browser tabs
- // so as to eliminate any racy-ness with this test.
- yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]);
-
- // Forget any previous closed tabs from other tests that may have
- // run in the same session.
- Services.obs.notifyObservers(null, "browser:purge-session-history", 0);
-
- is(ss.getClosedTabCount(window), 0,
- "We should have 0 closed tabs being stored.");
-
- // Create a tab worth remembering.
- let tab = gBrowser.addTab(PAGE);
- let browser = tab.linkedBrowser;
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
- yield TabStateFlusher.flush(browser);
-
- // Now close the tab, and immediately choose to forget it.
- let promise = BrowserTestUtils.removeTab(tab);
-
- // At this point, the tab will have closed, but the final update
- // to SessionStore hasn't come up yet. Now do the operation that
- // should cause us to forget the tab.
- forgetFn();
-
- is(ss.getClosedTabCount(window), 0, "Should have forgotten the closed tab");
-
- // Now wait for the final update to come up.
- yield promise;
-
- is(ss.getClosedTabCount(window), 0,
- "Should not have stored the forgotten closed tab");
-});
-
-/**
- * Creates a new window worth storing in the closeWIndows array,
- * and then closes it. Runs a synchronous forgetFn passed in that
- * should cause us to forget the window, and then ensures that after
- * the window has sent its final update message that we didn't
- * accidentally store it in the closedWindows array.
- *
- * @param forgetFn (function)
- * A synchronous function that should cause the window
- * to be forgotten.
- * @returns Promise
- */
-let forgetWinHelper = Task.async(function*(forgetFn) {
- // We want to suppress all non-final updates from the browser tabs
- // so as to eliminate any racy-ness with this test.
- yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]);
-
- // Forget any previous closed windows from other tests that may have
- // run in the same session.
- Services.obs.notifyObservers(null, "browser:purge-session-history", 0);
-
- is(ss.getClosedWindowCount(), 0, "We should have 0 closed windows being stored.");
-
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
-
- // Create a tab worth remembering.
- let tab = newWin.gBrowser.selectedTab;
- let browser = tab.linkedBrowser;
- browser.loadURI(PAGE);
- yield BrowserTestUtils.browserLoaded(browser, false, PAGE);
- yield TabStateFlusher.flush(browser);
-
- // Now close the window and immediately choose to forget it.
- let windowClosed = BrowserTestUtils.windowClosed(newWin);
- let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin);
-
- newWin.close();
- yield domWindowClosed;
-
- // At this point, the window will have closed and the onClose handler
- // has run, but the final update to SessionStore hasn't come up yet.
- // Now do the oepration that should cause us to forget the window.
- forgetFn();
-
- is(ss.getClosedWindowCount(), 0, "Should have forgotten the closed window");
-
- // Now wait for the final update to come up.
- yield windowClosed;
-
- is(ss.getClosedWindowCount(), 0, "Should not have stored the closed window");
-});
-
-/**
- * Tests that if we choose to forget a tab while waiting for its
- * final flush to complete, we don't accidentally store it.
- */
-add_task(function* test_forget_closed_tab() {
- yield forgetTabHelper(() => {
- ss.forgetClosedTab(window, 0);
- });
-});
-
-/**
- * Tests that if we choose to forget a tab while waiting for its
- * final flush to complete, we don't accidentally store it.
- */
-add_task(function* test_forget_closed_window() {
- yield forgetWinHelper(() => {
- ss.forgetClosedWindow(0);
- });
-});
-
-/**
- * Tests that if we choose to purge history while waiting for a
- * final flush of a tab to complete, we don't accidentally store it.
- */
-add_task(function* test_forget_purged_tab() {
- yield forgetTabHelper(() => {
- Services.obs.notifyObservers(null, "browser:purge-session-history", 0);
- });
-});
-
-/**
- * Tests that if we choose to purge history while waiting for a
- * final flush of a window to complete, we don't accidentally
- * store it.
- */
-add_task(function* test_forget_purged_window() {
- yield forgetWinHelper(() => {
- Services.obs.notifyObservers(null, "browser:purge-session-history", 0);
- });
-});
diff --git a/browser/components/sessionstore/test/browser_form_restore_events.js b/browser/components/sessionstore/test/browser_form_restore_events.js
deleted file mode 100644
index 3fc2e0fd4..000000000
--- a/browser/components/sessionstore/test/browser_form_restore_events.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_form_restore_events_sample.html";
-
-/**
- * Originally a test for Bug 476161, but then expanded to include all input
- * types in bug 640136.
- */
-add_task(function () {
- // Load a page with some form elements.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // text fields
- yield setInputValue(browser, {id: "modify01", value: Math.random()});
- yield setInputValue(browser, {id: "modify02", value: Date.now()});
-
- // textareas
- yield setInputValue(browser, {id: "modify03", value: Math.random()});
- yield setInputValue(browser, {id: "modify04", value: Date.now()});
-
- // file
- let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
- yield setInputValue(browser, {id: "modify05", value: file.path});
-
- // select
- yield setSelectedIndex(browser, {id: "modify06", index: 1});
- yield setMultipleSelected(browser, {id: "modify07", indices: [0,1,2]});
-
- // checkbox
- yield setInputChecked(browser, {id: "modify08", checked: true});
- yield setInputChecked(browser, {id: "modify09", checked: false});
-
- // radio
- yield setInputChecked(browser, {id: "modify10", checked: true});
- yield setInputChecked(browser, {id: "modify11", checked: true});
-
- // Duplicate the tab and check that restoring form data yields the expected
- // input and change events for modified form fields.
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- let inputFired = yield getTextContent(browser2, {id: "inputFired"});
- inputFired = inputFired.trim().split().sort().join(" ");
-
- let changeFired = yield getTextContent(browser2, {id: "changeFired"});
- changeFired = changeFired.trim().split().sort().join(" ");
-
- is(inputFired, "modify01 modify02 modify03 modify04 modify05",
- "input events were only dispatched for modified input, textarea fields");
-
- is(changeFired, "modify06 modify07 modify08 modify09 modify11",
- "change events were only dispatched for modified select, checkbox, radio fields");
-
- // Cleanup.
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_form_restore_events_sample.html b/browser/components/sessionstore/test/browser_form_restore_events_sample.html
deleted file mode 100644
index 1d46d4040..000000000
--- a/browser/components/sessionstore/test/browser_form_restore_events_sample.html
+++ /dev/null
@@ -1,99 +0,0 @@
-<!DOCTYPE html>
-<meta charset="utf-8">
-<title>Test for form restore events (originally bug 476161)</title>
-
-<script>
-
-document.addEventListener("input", function(aEvent) {
- var inputEl = aEvent.originalTarget;
- var changedEl = document.getElementById("inputFired");
- changedEl.textContent += " " + inputEl.id;
-}, false);
-
-document.addEventListener("change", function(aEvent) {
- var inputEl = aEvent.originalTarget;
- var changedEl = document.getElementById("changeFired");
- changedEl.textContent += " " + inputEl.id;
-}, false);
-
-</script>
-
-<!-- input events -->
-<h3>Text fields with changed text</h3>
-<input type="text" id="modify1">
-<input type="text" id="modify2" value="preset value">
-<input type="text" id="modify01">
-<input type="text" id="modify02" value="preset value">
-
-<h3>Text fields with unchanged text</h3>
-<input type="text" id="unchanged1">
-<input type="text" id="unchanged2" value="preset value">
-<input type="text" id="unchanged01">
-<input type="text" id="unchanged02" value="preset value">
-
-<h3>Textarea with changed text</h3>
-<textarea id="modify03"></textarea>
-<textarea id="modify04">preset value</textarea>
-
-<h3>Textarea with unchanged text</h3>
-<textarea id="unchanged03"></textarea>
-<textarea id="unchanged04">preset value</textarea>
-
-<h3>file field with changed value</h3>
-<input type="file" id="modify05">
-
-<h3>file field with unchanged value</h3>
-<input type="file" id="unchanged05">
-
-<!-- change events -->
-
-<h3>Select menu with changed selection</h3>
-<select id="modify06">
- <option value="one">one</option>
- <option value="two">two</option>
- <option value="three">three</option>
-</select>
-
-<h3>Select menu with unchanged selection (change event still fires)</h3>
-<select id="unchanged06">
- <option value="one">one</option>
- <option value="two" selected>two</option>
- <option value="three">three</option>
-</select>
-
-<h3>Multiple Select menu with changed selection</h3>
-<select id="modify07" multiple>
- <option value="one">one</option>
- <option value="two" selected>two</option>
- <option value="three">three</option>
-</select>
-
-<h3>Select menu with unchanged selection</h3>
-<select id="unchanged07" multiple>
- <option value="one">one</option>
- <option value="two" selected>two</option>
- <option value="three" selected>three</option>
-</select>
-
-<h3>checkbox with changed value</h3>
-<input type="checkbox" id="modify08">
-<input type="checkbox" id="modify09" checked>
-
-<h3>checkbox with unchanged value</h3>
-<input type="checkbox" id="unchanged08">
-<input type="checkbox" id="unchanged09" checked>
-
-<h3>radio with changed value</h3>
-<input type="radio" id="modify10" name="group">Radio 1</input>
-<input type="radio" id="modify11" name="group">Radio 2</input>
-<input type="radio" id="modify12" name="group" checked>Radio 3</input>
-
-<h3>radio with unchanged value</h3>
-<input type="radio" id="unchanged10" name="group2">Radio 4</input>
-<input type="radio" id="unchanged11" name="group2">Radio 5</input>
-<input type="radio" id="unchanged12" name="group2" checked>Radio 6</input>
-
-<h3>Changed field IDs</h3>
-<div id="changed"></div>
-<div id="inputFired"></div>
-<div id="changeFired"></div>
diff --git a/browser/components/sessionstore/test/browser_formdata.js b/browser/components/sessionstore/test/browser_formdata.js
deleted file mode 100644
index ce1272888..000000000
--- a/browser/components/sessionstore/test/browser_formdata.js
+++ /dev/null
@@ -1,194 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-/**
- * This test ensures that form data collection respects the privacy level as
- * set by the user.
- */
-add_task(function test_formdata() {
- const URL = "http://mochi.test:8888/browser/browser/components/" +
- "sessionstore/test/browser_formdata_sample.html";
-
- const OUTER_VALUE = "browser_formdata_" + Math.random();
- const INNER_VALUE = "browser_formdata_" + Math.random();
-
- // Creates a tab, loads a page with some form fields,
- // modifies their values and closes the tab.
- function createAndRemoveTab() {
- return Task.spawn(function () {
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Modify form data.
- yield setInputValue(browser, {id: "txt", value: OUTER_VALUE});
- yield setInputValue(browser, {id: "txt", value: INNER_VALUE, frame: 0});
-
- // Remove the tab.
- yield promiseRemoveTab(tab);
- });
- }
-
- yield createAndRemoveTab();
- let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window));
- is(formdata.id.txt, OUTER_VALUE, "outer value is correct");
- is(formdata.children[0].id.txt, INNER_VALUE, "inner value is correct");
-
- // Disable saving data for encrypted sites.
- Services.prefs.setIntPref("browser.sessionstore.privacy_level", 1);
-
- yield createAndRemoveTab();
- [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window));
- is(formdata.id.txt, OUTER_VALUE, "outer value is correct");
- ok(!formdata.children, "inner value was *not* stored");
-
- // Disable saving data for any site.
- Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2);
-
- yield createAndRemoveTab();
- [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window));
- ok(!formdata, "form data has *not* been stored");
-
- // Restore the default privacy level.
- Services.prefs.clearUserPref("browser.sessionstore.privacy_level");
-});
-
-/**
- * This test ensures that a malicious website can't trick us into restoring
- * form data into a wrong website and that we always check the stored URL
- * before doing so.
- */
-add_task(function test_url_check() {
- const URL = "data:text/html;charset=utf-8,<input%20id=input>";
- const VALUE = "value-" + Math.random();
-
- // Create a tab with an iframe containing an input field.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Restore a tab state with a given form data url.
- function restoreStateWithURL(url) {
- let state = {entries: [{url: URL}], formdata: {id: {input: VALUE}}};
-
- if (url) {
- state.formdata.url = url;
- }
-
- return promiseTabState(tab, state).then(() => getInputValue(browser, "input"));
- }
-
- // Check that the form value is restored with the correct URL.
- is((yield restoreStateWithURL(URL)), VALUE, "form data restored");
-
- // Check that the form value is *not* restored with the wrong URL.
- is((yield restoreStateWithURL(URL + "?")), "", "form data not restored");
- is((yield restoreStateWithURL()), "", "form data not restored");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * This test ensures that collecting form data works as expected when having
- * nested frame sets.
- */
-add_task(function test_nested() {
- const URL = "data:text/html;charset=utf-8," +
- "<iframe src='data:text/html;charset=utf-8," +
- "<input autofocus=true>'/>";
-
- const FORM_DATA = {
- children: [{
- xpath: {"/xhtml:html/xhtml:body/xhtml:input": "M"},
- url: "data:text/html;charset=utf-8,<input%20autofocus=true>"
- }]
- };
-
- // Create a tab with an iframe containing an input field.
- let tab = gBrowser.selectedTab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Modify the input field's value.
- yield sendMessage(browser, "ss-test:sendKeyEvent", {key: "m", frame: 0});
-
- // Remove the tab and check that we stored form data correctly.
- yield promiseRemoveTab(tab);
- let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window));
- is(JSON.stringify(formdata), JSON.stringify(FORM_DATA),
- "formdata for iframe stored correctly");
-
- // Restore the closed tab.
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that the input field has the right value.
- yield TabStateFlusher.flush(browser);
- ({formdata} = JSON.parse(ss.getTabState(tab)));
- is(JSON.stringify(formdata), JSON.stringify(FORM_DATA),
- "formdata for iframe restored correctly");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * This test ensures that collecting form data for documents with
- * designMode=on works as expected.
- */
-add_task(function test_design_mode() {
- const URL = "data:text/html;charset=utf-8,<h1>mozilla</h1>" +
- "<script>document.designMode='on'</script>";
-
- // Load a tab with an editable document.
- let tab = gBrowser.selectedTab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Modify the document content.
- yield sendMessage(browser, "ss-test:sendKeyEvent", {key: "m"});
-
- // Close and restore the tab.
- yield promiseRemoveTab(tab);
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that the innerHTML value was restored.
- let html = yield getInnerHTML(browser);
- let expected = "<h1>Mmozilla</h1><script>document.designMode='on'</script>";
- is(html, expected, "editable document has been restored correctly");
-
- // Close and restore the tab.
- yield promiseRemoveTab(tab);
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that the innerHTML value was restored.
- html = yield getInnerHTML(browser);
- expected = "<h1>Mmozilla</h1><script>document.designMode='on'</script>";
- is(html, expected, "editable document has been restored correctly");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-function getInputValue(browser, id) {
- return sendMessage(browser, "ss-test:getInputValue", {id: id});
-}
-
-function setInputValue(browser, data) {
- return sendMessage(browser, "ss-test:setInputValue", data);
-}
-
-function getInnerHTML(browser) {
- return sendMessage(browser, "ss-test:getInnerHTML", {selector: "body"});
-}
diff --git a/browser/components/sessionstore/test/browser_formdata_cc.js b/browser/components/sessionstore/test/browser_formdata_cc.js
deleted file mode 100644
index 6e27ca970..000000000
--- a/browser/components/sessionstore/test/browser_formdata_cc.js
+++ /dev/null
@@ -1,79 +0,0 @@
-"use strict";
-
-const URL = "http://mochi.test:8888/browser/browser/components/" +
- "sessionstore/test/browser_formdata_sample.html";
-
-requestLongerTimeout(3);
-
-/**
- * This test ensures that credit card numbers in form data will not be
- * collected, while numbers that don't look like credit card numbers will
- * still be collected.
- */
-add_task(function* () {
- const validCCNumbers = [
- // 15 digits
- "930771457288760", "474915027480942",
- "924894781317325", "714816113937185",
- "790466087343106", "474320195408363",
- "219211148122351", "633038472250799",
- "354236732906484", "095347810189325",
- // 16 digits
- "3091269135815020", "5471839082338112",
- "0580828863575793", "5015290610002932",
- "9465714503078607", "4302068493801686",
- "2721398408985465", "6160334316984331",
- "8643619970075142", "0218246069710785"
- ];
-
- const invalidCCNumbers = [
- // 15 digits
- "526931005800649", "724952425140686",
- "379761391174135", "030551436468583",
- "947377014076746", "254848023655752",
- "226871580283345", "708025346034339",
- "917585839076788", "918632588027666",
- // 16 digits
- "9946177098017064", "4081194386488872",
- "3095975979578034", "3662215692222536",
- "6723210018630429", "4411962856225025",
- "8276996369036686", "4449796938248871",
- "3350852696538147", "5011802870046957"
- ];
-
- // Creates a tab, loads a page with a form field, sets the value of the
- // field, and then removes the tab to trigger data collection.
- function* createAndRemoveTab(formValue) {
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Set form value.
- yield setInputValue(browser, formValue);
-
- // Remove the tab.
- yield promiseRemoveTab(tab);
- }
-
- // Test that valid CC numbers are not collected.
- for (let number of validCCNumbers) {
- yield createAndRemoveTab(number);
- let [{state}] = JSON.parse(ss.getClosedTabData(window));
- ok(!("formdata" in state), "valid CC numbers are not collected");
- }
-
- // Test that non-CC numbers are still collected.
- for (let number of invalidCCNumbers) {
- yield createAndRemoveTab(number);
- let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window));
- is(formdata.id.txt, number,
- "numbers that are not valid CC numbers are still collected");
- }
-});
-
-function setInputValue(browser, formValue) {
- return ContentTask.spawn(browser, formValue, function* (formValue) {
- content.document.getElementById("txt").setUserInput(formValue);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_formdata_format.js b/browser/components/sessionstore/test/browser_formdata_format.js
deleted file mode 100644
index 6a1b5975d..000000000
--- a/browser/components/sessionstore/test/browser_formdata_format.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-function test() {
- /** Tests formdata format **/
- waitForExplicitFinish();
-
- let formData = [
- { },
- // old format
- { "#input1" : "value0" },
- { "#input1" : "value1", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value2" },
- { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value3" },
- // new format
- { id: { "input1" : "value4" } },
- { id: { "input1" : "value5" }, xpath: {} },
- { id: { "input1" : "value6" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value7" } },
- { id: {}, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value8" } },
- { xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value9" } },
- // combinations
- { "#input1" : "value10", id: { "input1" : "value11" } },
- { "#input1" : "value12", id: { "input1" : "value13" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value14" } },
- { "#input1" : "value15", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value16" } },
- { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value17", id: { "input1" : "value18" } },
- { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value19", id: { "input1" : "value20" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value21" } },
- { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value22", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value23" } },
- { "#input1" : "value24", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value25", id: { "input1" : "value26" } },
- { "#input1" : "value27", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value28", id: { "input1" : "value29" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value30" } },
- { "#input1" : "value31", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value32", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value33" } }
- ]
- let expectedValues = [
- [ "" , "" ],
- // old format
- [ "value0", "" ],
- [ "value1", "value2" ],
- [ "", "value3" ],
- // new format
- [ "value4", "" ],
- [ "value5", "" ],
- [ "value6", "value7" ],
- [ "", "value8" ],
- [ "", "value9" ],
- // combinations
- [ "value11", "" ],
- [ "value13", "value14" ],
- [ "", "value16" ],
- [ "value18", "" ],
- [ "value20", "value21" ],
- [ "", "value23" ],
- [ "value26", "" ],
- [ "value29", "value30" ],
- [ "", "value33" ]
- ];
- let testTabCount = 0;
- let callback = function() {
- testTabCount--;
- if (testTabCount == 0) {
- finish();
- }
- };
-
- for (let i = 0; i < formData.length; i++) {
- testTabCount++;
- testTabRestoreData(formData[i], expectedValues[i], callback);
- }
-}
-
-function testTabRestoreData(aFormData, aExpectedValue, aCallback) {
- let URL = ROOT + "browser_formdata_format_sample.html";
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
-
- aFormData.url = URL;
- let tabState = { entries: [{ url: URL }], formdata: aFormData };
-
- Task.spawn(function () {
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield promiseTabState(tab, tabState);
-
- yield TabStateFlusher.flush(tab.linkedBrowser);
- let restoredTabState = JSON.parse(ss.getTabState(tab));
- let restoredFormData = restoredTabState.formdata;
-
- if (restoredFormData) {
- let doc = tab.linkedBrowser.contentDocument;
- let input1 = doc.getElementById("input1");
- let input2 = doc.querySelector("input[name=input2]");
-
- // test format
- ok("id" in restoredFormData || "xpath" in restoredFormData,
- "FormData format is valid: " + restoredFormData);
- // validate that there are no old keys
- for (let key of Object.keys(restoredFormData)) {
- if (["id", "xpath", "url"].indexOf(key) === -1) {
- ok(false, "FormData format is invalid.");
- }
- }
- // test id
- is(input1.value, aExpectedValue[0],
- "FormData by 'id' has been restored correctly");
- // test xpath
- is(input2.value, aExpectedValue[1],
- "FormData by 'xpath' has been restored correctly");
- }
-
- // clean up
- gBrowser.removeTab(tab);
-
- // This test might time out if the task fails.
- }).then(aCallback);
-}
diff --git a/browser/components/sessionstore/test/browser_formdata_format_sample.html b/browser/components/sessionstore/test/browser_formdata_format_sample.html
deleted file mode 100644
index f991e3657..000000000
--- a/browser/components/sessionstore/test/browser_formdata_format_sample.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<!DOCTYPE html>
-<title>Test formdata format</title>
-
-<!-- input events -->
-<h3>Input fields</h3>
-<input type="text" id="input1">
-<input type="text" name="input2"> \ No newline at end of file
diff --git a/browser/components/sessionstore/test/browser_formdata_sample.html b/browser/components/sessionstore/test/browser_formdata_sample.html
deleted file mode 100644
index 6cbb54fb5..000000000
--- a/browser/components/sessionstore/test/browser_formdata_sample.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_formdata_sample.html</title>
- </head>
- <body>
- <input id="txt" />
-
- <script type="text/javascript;version=1.8">
- let isOuter = window == window.top;
-
- if (isOuter) {
- let iframe = document.createElement("iframe");
- iframe.setAttribute("src", "https://example.com" + location.pathname);
- document.body.appendChild(iframe);
- }
- </script>
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_formdata_xpath.js b/browser/components/sessionstore/test/browser_formdata_xpath.js
deleted file mode 100644
index d69feb546..000000000
--- a/browser/components/sessionstore/test/browser_formdata_xpath.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = ROOT + "browser_formdata_xpath_sample.html";
-
-/**
- * Bug 346337 - Generic form data restoration tests.
- */
-add_task(function setup() {
- // make sure we don't save form data at all (except for tab duplication)
- Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2);
-
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.sessionstore.privacy_level");
- });
-});
-
-const FILE1 = createFilePath("346337_test1.file");
-const FILE2 = createFilePath("346337_test2.file");
-
-const FIELDS = {
- "//input[@name='input']": Date.now().toString(),
- "//input[@name='spaced 1']": Math.random().toString(),
- "//input[3]": "three",
- "//input[@type='checkbox']": true,
- "//input[@name='uncheck']": false,
- "//input[@type='radio'][1]": false,
- "//input[@type='radio'][2]": true,
- "//input[@type='radio'][3]": false,
- "//select": 2,
- "//select[@multiple]": [1, 3],
- "//textarea[1]": "",
- "//textarea[2]": "Some text... " + Math.random(),
- "//textarea[3]": "Some more text\n" + new Date(),
- "//input[@type='file'][1]": [FILE1],
- "//input[@type='file'][2]": [FILE1, FILE2]
-};
-
-add_task(function test_form_data_restoration() {
- // Load page with some input fields.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Fill in some values.
- for (let xpath of Object.keys(FIELDS)) {
- yield setFormValue(browser, xpath);
- }
-
- // Duplicate the tab.
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- // Check that all form values have been duplicated.
- for (let xpath of Object.keys(FIELDS)) {
- let expected = JSON.stringify(FIELDS[xpath]);
- let actual = JSON.stringify(yield getFormValue(browser2, xpath));
- is(actual, expected, "The value for \"" + xpath + "\" was correctly restored");
- }
-
- // Remove all tabs.
- yield promiseRemoveTab(tab2);
- yield promiseRemoveTab(tab);
-
- // Restore one of the tabs again.
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that none of the form values have been restored due to the privacy
- // level settings.
- for (let xpath of Object.keys(FIELDS)) {
- let expected = FIELDS[xpath];
- if (expected) {
- let actual = yield getFormValue(browser, xpath, expected);
- isnot(actual, expected, "The value for \"" + xpath + "\" was correctly discarded");
- }
- }
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
-
-function createFilePath(leaf) {
- let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
- file.append(leaf);
- return file.path;
-}
-
-function isArrayOfNumbers(value) {
- return Array.isArray(value) && value.every(n => typeof(n) === "number");
-}
-
-function isArrayOfStrings(value) {
- return Array.isArray(value) && value.every(n => typeof(n) === "string");
-}
-
-function getFormValue(browser, xpath) {
- let value = FIELDS[xpath];
-
- if (typeof value == "string") {
- return getInputValue(browser, {xpath: xpath});
- }
-
- if (typeof value == "boolean") {
- return getInputChecked(browser, {xpath: xpath});
- }
-
- if (typeof value == "number") {
- return getSelectedIndex(browser, {xpath: xpath});
- }
-
- if (isArrayOfNumbers(value)) {
- return getMultipleSelected(browser, {xpath: xpath});
- }
-
- if (isArrayOfStrings(value)) {
- return getFileNameArray(browser, {xpath: xpath});
- }
-
- throw new Error("unknown input type");
-}
-
-function setFormValue(browser, xpath) {
- let value = FIELDS[xpath];
-
- if (typeof value == "string") {
- return setInputValue(browser, {xpath: xpath, value: value});
- }
-
- if (typeof value == "boolean") {
- return setInputChecked(browser, {xpath: xpath, checked: value});
- }
-
- if (typeof value == "number") {
- return setSelectedIndex(browser, {xpath: xpath, index: value});
- }
-
- if (isArrayOfNumbers(value)) {
- return setMultipleSelected(browser, {xpath: xpath, indices: value});
- }
-
- if (isArrayOfStrings(value)) {
- return setFileNameArray(browser, {xpath: xpath, names: value});
- }
-
- throw new Error("unknown input type");
-}
diff --git a/browser/components/sessionstore/test/browser_formdata_xpath_sample.html b/browser/components/sessionstore/test/browser_formdata_xpath_sample.html
deleted file mode 100644
index 682162d6a..000000000
--- a/browser/components/sessionstore/test/browser_formdata_xpath_sample.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<title>Test for bug 346337</title>
-
-<h3>Text Fields</h3>
-<input type="text" name="input">
-<input type="text" name="spaced 1">
-<input>
-
-<h3>Checkboxes and Radio buttons</h3>
-<input type="checkbox" name="check"> Check 1
-<input type="checkbox" name="uncheck" checked> Check 2
-<p>
-<input type="radio" name="group" value="1"> Radio 1
-<input type="radio" name="group" value="some"> Radio 2
-<input type="radio" name="group" checked> Radio 3
-
-<h3>Selects</h3>
-<select name="any">
- <option value="1"> Select 1
- <option value="some"> Select 2
- <option>Select 3
-</select>
-<select multiple="multiple">
- <option value=1> Multi-select 1
- <option value=2> Multi-select 2
- <option value=3> Multi-select 3
- <option value=4> Multi-select 4
-</select>
-
-<h3>Text Areas</h3>
-<textarea name="testarea"></textarea>
-<textarea name="sized one" rows="5" cols="25"></textarea>
-<textarea></textarea>
-
-<h3>File Selector</h3>
-<input type="file">
-<input type="file" multiple>
diff --git a/browser/components/sessionstore/test/browser_frame_history.js b/browser/components/sessionstore/test/browser_frame_history.js
deleted file mode 100644
index e0d152f77..000000000
--- a/browser/components/sessionstore/test/browser_frame_history.js
+++ /dev/null
@@ -1,170 +0,0 @@
-/* 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/. */
-
-/**
- Ensure that frameset history works properly when restoring a tab,
- provided that the frameset is static.
- */
-
-// Loading a toplevel frameset
-add_task(function() {
- let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index.html";
- let tab = gBrowser.addTab(testURL);
- gBrowser.selectedTab = tab;
-
- info("Opening a page with three frames, 4 loads should take place");
- yield waitForLoadsInBrowser(tab.linkedBrowser, 4);
-
- let browser_b = tab.linkedBrowser.contentDocument.getElementsByTagName("frame")[1];
- let document_b = browser_b.contentDocument;
- let links = document_b.getElementsByTagName("a");
-
- // We're going to click on the first link, so listen for another load event
- info("Clicking on link 1, 1 load should take place");
- let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow);
- yield promise;
-
- info("Clicking on link 2, 1 load should take place");
- promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow);
- yield promise;
-
- info("Close then un-close page, 4 loads should take place");
- yield promiseRemoveTab(tab);
- let newTab = ss.undoCloseTab(window, 0);
- yield waitForLoadsInBrowser(newTab.linkedBrowser, 4);
-
- info("Go back in time, 1 load should take place");
- gBrowser.goBack();
- yield waitForLoadsInBrowser(newTab.linkedBrowser, 1);
-
- let expectedURLEnds = ["a.html", "b.html", "c1.html"];
- let frames = newTab.linkedBrowser.contentDocument.getElementsByTagName("frame");
- for (let i = 0; i < frames.length; i++) {
- is(frames[i].contentDocument.location,
- getRootDirectory(gTestPath) + "browser_frame_history_" + expectedURLEnds[i],
- "frame " + i + " has the right url");
- }
- gBrowser.removeTab(newTab);
-});
-
-// Loading the frameset inside an iframe
-add_task(function() {
- let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index2.html";
- let tab = gBrowser.addTab(testURL);
- gBrowser.selectedTab = tab;
-
- info("iframe: Opening a page with an iframe containing three frames, 5 loads should take place");
- yield waitForLoadsInBrowser(tab.linkedBrowser, 5);
-
- let browser_b = tab.linkedBrowser.contentDocument.
- getElementById("iframe").contentDocument.
- getElementsByTagName("frame")[1];
- let document_b = browser_b.contentDocument;
- let links = document_b.getElementsByTagName("a");
-
- // We're going to click on the first link, so listen for another load event
- info("iframe: Clicking on link 1, 1 load should take place");
- let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow);
- yield promise;
-
- info("iframe: Clicking on link 2, 1 load should take place");
- promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow);
- yield promise;
-
- info("iframe: Close then un-close page, 5 loads should take place");
- yield promiseRemoveTab(tab);
- let newTab = ss.undoCloseTab(window, 0);
- yield waitForLoadsInBrowser(newTab.linkedBrowser, 5);
-
- info("iframe: Go back in time, 1 load should take place");
- gBrowser.goBack();
- yield waitForLoadsInBrowser(newTab.linkedBrowser, 1);
-
- let expectedURLEnds = ["a.html", "b.html", "c1.html"];
- let frames = newTab.linkedBrowser.contentDocument.
- getElementById("iframe").contentDocument.
- getElementsByTagName("frame");
- for (let i = 0; i < frames.length; i++) {
- is(frames[i].contentDocument.location,
- getRootDirectory(gTestPath) + "browser_frame_history_" + expectedURLEnds[i],
- "frame " + i + " has the right url");
- }
- gBrowser.removeTab(newTab);
-});
-
-// Now, test that we don't record history if the iframe is added dynamically
-add_task(function() {
- // Start with an empty history
- let blankState = JSON.stringify({
- windows: [{
- tabs: [{ entries: [{ url: "about:blank" }] }],
- _closedTabs: []
- }],
- _closedWindows: []
- });
- ss.setBrowserState(blankState);
-
- let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index_blank.html";
- let tab = gBrowser.addTab(testURL);
- gBrowser.selectedTab = tab;
- yield waitForLoadsInBrowser(tab.linkedBrowser, 1);
-
- info("dynamic: Opening a page with an iframe containing three frames, 4 dynamic loads should take place");
- let doc = tab.linkedBrowser.contentDocument;
- let iframe = doc.createElement("iframe");
- iframe.id = "iframe";
- iframe.src="browser_frame_history_index.html";
- doc.body.appendChild(iframe);
- yield waitForLoadsInBrowser(tab.linkedBrowser, 4);
-
- let browser_b = tab.linkedBrowser.contentDocument.
- getElementById("iframe").contentDocument.
- getElementsByTagName("frame")[1];
- let document_b = browser_b.contentDocument;
- let links = document_b.getElementsByTagName("a");
-
- // We're going to click on the first link, so listen for another load event
- info("dynamic: Clicking on link 1, 1 load should take place");
- let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow);
- yield promise;
-
- info("dynamic: Clicking on link 2, 1 load should take place");
- promise = waitForLoadsInBrowser(tab.linkedBrowser, 1);
- EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow);
- yield promise;
-
- info("Check in the state that we have not stored this history");
- let state = ss.getBrowserState();
- info(JSON.stringify(JSON.parse(state), null, "\t"));
- is(state.indexOf("c1.html"), -1, "History entry was not stored in the session state");;
- gBrowser.removeTab(tab);
-});
-
-// helper functions
-function waitForLoadsInBrowser(aBrowser, aLoadCount) {
- let deferred = Promise.defer();
- let loadCount = 0;
- aBrowser.addEventListener("load", function(aEvent) {
- if (++loadCount < aLoadCount) {
- info("Got " + loadCount + " loads, waiting until we have " + aLoadCount);
- return;
- }
-
- aBrowser.removeEventListener("load", arguments.callee, true);
- deferred.resolve();
- }, true);
- return deferred.promise;
-}
-
-function timeout(delay, task) {
- let deferred = Promise.defer();
- setTimeout(() => deferred.resolve(true), delay);
- task.then(() => deferred.resolve(false), deferred.reject);
- return deferred.promise;
-}
diff --git a/browser/components/sessionstore/test/browser_frame_history_a.html b/browser/components/sessionstore/test/browser_frame_history_a.html
deleted file mode 100755
index 8e7b35d7a..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_a.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- I'm A!
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frame_history_b.html b/browser/components/sessionstore/test/browser_frame_history_b.html
deleted file mode 100755
index 38b43da21..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_b.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <body>
- I'm B!<br/>
- <a target="c" href="browser_frame_history_c1.html">click me first</a><br/>
- <a target="c" href="browser_frame_history_c2.html">then click me</a><br/>
- Close this tab.<br/>
- Restore this tab.<br/>
- Click back.<br/>
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frame_history_c.html b/browser/components/sessionstore/test/browser_frame_history_c.html
deleted file mode 100755
index 0efd7d902..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- I'm C!
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frame_history_c1.html b/browser/components/sessionstore/test/browser_frame_history_c1.html
deleted file mode 100755
index b55c1d45a..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c1.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- I'm C1!
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frame_history_c2.html b/browser/components/sessionstore/test/browser_frame_history_c2.html
deleted file mode 100755
index aec504141..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c2.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- I'm C2!
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frame_history_index.html b/browser/components/sessionstore/test/browser_frame_history_index.html
deleted file mode 100644
index 76eeb4c4d..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <frameset cols="20%,80%">
- <frameset rows="30%,70%">
- <frame src="browser_frame_history_a.html"/>
- <frame src="browser_frame_history_b.html"/>
- </frameset>
- <frame src="browser_frame_history_c.html" name="c"/>
- </frameset>
-</html>
-
diff --git a/browser/components/sessionstore/test/browser_frame_history_index2.html b/browser/components/sessionstore/test/browser_frame_history_index2.html
deleted file mode 100644
index e4dfb4083..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index2.html
+++ /dev/null
@@ -1,4 +0,0 @@
-<html>
- <iframe src="browser_frame_history_index.html" id="iframe" />
-</html>
-
diff --git a/browser/components/sessionstore/test/browser_frame_history_index_blank.html b/browser/components/sessionstore/test/browser_frame_history_index_blank.html
deleted file mode 100644
index 30fd1f58c..000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index_blank.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- </body>
-</html>
-
diff --git a/browser/components/sessionstore/test/browser_frametree.js b/browser/components/sessionstore/test/browser_frametree.js
deleted file mode 100644
index a342f8c66..000000000
--- a/browser/components/sessionstore/test/browser_frametree.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = HTTPROOT + "browser_frametree_sample.html";
-const URL_FRAMESET = HTTPROOT + "browser_frametree_sample_frameset.html";
-
-/**
- * This ensures that loading a page normally, aborting a page load, reloading
- * a page, navigating using the bfcache, and ignoring frames that were
- * created dynamically work as expect. We expect the frame tree to be reset
- * when a page starts loading and we also expect a valid frame tree to exist
- * when it has stopped loading.
- */
-add_task(function test_frametree() {
- const FRAME_TREE_SINGLE = { href: URL };
- const FRAME_TREE_FRAMESET = {
- href: URL_FRAMESET,
- children: [{href: URL}, {href: URL}, {href: URL}]
- };
-
- // Create a tab with a single frame.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseNewFrameTree(browser);
- yield checkFrameTree(browser, FRAME_TREE_SINGLE,
- "loading a page resets and creates the frame tree correctly");
-
- // Load the frameset and create two frames dynamically, the first on
- // DOMContentLoaded and the second on load.
- yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL});
- browser.loadURI(URL_FRAMESET);
- yield promiseNewFrameTree(browser);
- yield checkFrameTree(browser, FRAME_TREE_FRAMESET,
- "dynamic frames created on or after the load event are ignored");
-
- // Go back to the previous single-frame page. There will be no load event as
- // the page is still in the bfcache. We thus make sure this type of navigation
- // resets the frame tree.
- browser.goBack();
- yield promiseNewFrameTree(browser);
- yield checkFrameTree(browser, FRAME_TREE_SINGLE,
- "loading from bfache resets and creates the frame tree correctly");
-
- // Load the frameset again but abort the load early.
- // The frame tree should still be reset and created.
- browser.loadURI(URL_FRAMESET);
- executeSoon(() => browser.stop());
- yield promiseNewFrameTree(browser);
-
- // Load the frameset and check the tree again.
- yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL});
- browser.loadURI(URL_FRAMESET);
- yield promiseNewFrameTree(browser);
- yield checkFrameTree(browser, FRAME_TREE_FRAMESET,
- "reloading a page resets and creates the frame tree correctly");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * This test ensures that we ignore frames that were created dynamically at or
- * after the load event. SessionStore can't handle these and will not restore
- * or collect any data for them.
- */
-add_task(function test_frametree_dynamic() {
- // The frame tree as expected. The first two frames are static
- // and the third one was created on DOMContentLoaded.
- const FRAME_TREE = {
- href: URL_FRAMESET,
- children: [{href: URL}, {href: URL}, {href: URL}]
- };
- const FRAME_TREE_REMOVED = {
- href: URL_FRAMESET,
- children: [{href: URL}, {href: URL}]
- };
-
- // Add an empty tab for a start.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Create dynamic frames on "DOMContentLoaded" and on "load".
- yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL});
- browser.loadURI(URL_FRAMESET);
- yield promiseNewFrameTree(browser);
-
- // Check that the frame tree does not contain the frame created on "load".
- // The two static frames and the one created on DOMContentLoaded must be in
- // the tree.
- yield checkFrameTree(browser, FRAME_TREE,
- "frame tree contains first four frames");
-
- // Remove the last frame in the frameset.
- yield sendMessage(browser, "ss-test:removeLastFrame", {id: "frames"});
- // Check that the frame tree didn't change.
- yield checkFrameTree(browser, FRAME_TREE,
- "frame tree contains first four frames");
-
- // Remove the last frame in the frameset.
- yield sendMessage(browser, "ss-test:removeLastFrame", {id: "frames"});
- // Check that the frame tree excludes the removed frame.
- yield checkFrameTree(browser, FRAME_TREE_REMOVED,
- "frame tree contains first three frames");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Checks whether the current frame hierarchy of a given |browser| matches the
- * |expected| frame hierarchy.
- */
-function checkFrameTree(browser, expected, msg) {
- return sendMessage(browser, "ss-test:mapFrameTree").then(tree => {
- is(JSON.stringify(tree), JSON.stringify(expected), msg);
- });
-}
-
-/**
- * Returns a promise that will be resolved when the given |browser| has loaded
- * and we received messages saying that its frame tree has been reset and
- * recollected.
- */
-function promiseNewFrameTree(browser) {
- let reset = promiseContentMessage(browser, "ss-test:onFrameTreeCollected");
- let collect = promiseContentMessage(browser, "ss-test:onFrameTreeCollected");
- return Promise.all([reset, collect]);
-}
diff --git a/browser/components/sessionstore/test/browser_frametree_sample.html b/browser/components/sessionstore/test/browser_frametree_sample.html
deleted file mode 100644
index dda129448..000000000
--- a/browser/components/sessionstore/test/browser_frametree_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_frametree_sample.html</title>
- </head>
- <body style='width: 100000px; height: 100000px;'>top</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_frametree_sample_frameset.html b/browser/components/sessionstore/test/browser_frametree_sample_frameset.html
deleted file mode 100644
index e1cd08735..000000000
--- a/browser/components/sessionstore/test/browser_frametree_sample_frameset.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_frametree_sample_frameset.html</title>
- </head>
- <frameset id="frames" rows="50%, 50%">
- <frame src="browser_frametree_sample.html">
- <frame src="browser_frametree_sample.html">
- </frameset>
-</html>
diff --git a/browser/components/sessionstore/test/browser_global_store.js b/browser/components/sessionstore/test/browser_global_store.js
deleted file mode 100644
index 792154830..000000000
--- a/browser/components/sessionstore/test/browser_global_store.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests the API for saving global session data.
-add_task(function* () {
- const key1 = "Unique name 1: " + Date.now();
- const key2 = "Unique name 2: " + Date.now();
- const value1 = "Unique value 1: " + Math.random();
- const value2 = "Unique value 2: " + Math.random();
-
- let global = {};
- global[key1] = value1;
-
- const testState = {
- windows: [
- {
- tabs: [
- { entries: [{ url: "about:blank" }] },
- ]
- }
- ],
- global: global
- };
-
- function testRestoredState() {
- is(ss.getGlobalValue(key1), value1, "restored state has global value");
- }
-
- function testGlobalStore() {
- is(ss.getGlobalValue(key2), "", "global value initially not set");
-
- ss.setGlobalValue(key2, value1);
- is(ss.getGlobalValue(key2), value1, "retreived value matches stored");
-
- ss.setGlobalValue(key2, value2);
- is(ss.getGlobalValue(key2), value2, "previously stored value was overwritten");
-
- ss.deleteGlobalValue(key2);
- is(ss.getGlobalValue(key2), "", "global value was deleted");
- }
-
- yield promiseBrowserState(testState);
- testRestoredState();
- testGlobalStore();
-});
diff --git a/browser/components/sessionstore/test/browser_history_persist.js b/browser/components/sessionstore/test/browser_history_persist.js
deleted file mode 100644
index 6b9e62abc..000000000
--- a/browser/components/sessionstore/test/browser_history_persist.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* eslint-env mozilla/frame-script */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Ensure that history entries that should not be persisted are restored in the
- * same state.
- */
-add_task(function check_history_not_persisted() {
- // Create an about:blank tab
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Retrieve the tab state.
- yield TabStateFlusher.flush(browser);
- let state = JSON.parse(ss.getTabState(tab));
- ok(!state.entries[0].persist, "Should have collected the persistence state");
- yield promiseRemoveTab(tab);
- browser = null;
-
- // Open a new tab to restore into.
- tab = gBrowser.addTab("about:blank");
- browser = tab.linkedBrowser;
- yield promiseTabState(tab, state);
-
- yield ContentTask.spawn(browser, null, function() {
- let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
-
- is(sessionHistory.count, 1, "Should be a single history entry");
- is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL");
- });
-
- // Load a new URL into the tab, it should replace the about:blank history entry
- browser.loadURI("about:robots");
- yield promiseBrowserLoaded(browser);
- yield ContentTask.spawn(browser, null, function() {
- let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- is(sessionHistory.count, 1, "Should be a single history entry");
- is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:robots", "Should be the right URL");
- });
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
-
-/**
- * Check that entries default to being persisted when the attribute doesn't
- * exist
- */
-add_task(function check_history_default_persisted() {
- // Create an about:blank tab
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Retrieve the tab state.
- yield TabStateFlusher.flush(browser);
- let state = JSON.parse(ss.getTabState(tab));
- delete state.entries[0].persist;
- yield promiseRemoveTab(tab);
- browser = null;
-
- // Open a new tab to restore into.
- tab = gBrowser.addTab("about:blank");
- browser = tab.linkedBrowser;
- yield promiseTabState(tab, state);
- yield ContentTask.spawn(browser, null, function() {
- let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
-
- is(sessionHistory.count, 1, "Should be a single history entry");
- is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL");
- });
-
- // Load a new URL into the tab, it should replace the about:blank history entry
- browser.loadURI("about:robots");
- yield promiseBrowserLoaded(browser);
- yield ContentTask.spawn(browser, null, function() {
- let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- is(sessionHistory.count, 2, "Should be two history entries");
- is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL");
- is(sessionHistory.getEntryAtIndex(1, false).URI.spec, "about:robots", "Should be the right URL");
- });
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_label_and_icon.js b/browser/components/sessionstore/test/browser_label_and_icon.js
deleted file mode 100644
index db68eb042..000000000
--- a/browser/components/sessionstore/test/browser_label_and_icon.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci} = Components;
-
-/**
- * Make sure that tabs are restored on demand as otherwise the tab will start
- * loading immediately and we can't check its icon and label.
- */
-add_task(function setup() {
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
- });
-});
-
-/**
- * Ensure that a pending tab has label and icon correctly set.
- */
-add_task(function test_label_and_icon() {
- // Create a new tab.
- let tab = gBrowser.addTab("about:robots");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Retrieve the tab state.
- yield TabStateFlusher.flush(browser);
- let state = ss.getTabState(tab);
- yield promiseRemoveTab(tab);
- browser = null;
-
- // Open a new tab to restore into.
- tab = gBrowser.addTab("about:blank");
- ss.setTabState(tab, state);
- yield promiseTabRestoring(tab);
-
- // Check that label and icon are set for the restoring tab.
- ok(gBrowser.getIcon(tab).startsWith("data:image/png;"), "icon is set");
- is(tab.label, "Gort! Klaatu barada nikto!", "label is set");
-
- let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
- .getService(Ci.nsISerializationHelper);
- let serializedPrincipal = tab.getAttribute("iconLoadingPrincipal");
- let iconLoadingPrincipal = serhelper.deserializeObject(serializedPrincipal)
- .QueryInterface(Ci.nsIPrincipal);
- is(iconLoadingPrincipal.origin, "about:robots", "correct loadingPrincipal used");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_merge_closed_tabs.js b/browser/components/sessionstore/test/browser_merge_closed_tabs.js
deleted file mode 100644
index b26e86f22..000000000
--- a/browser/components/sessionstore/test/browser_merge_closed_tabs.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This test ensures that closed tabs are merged when restoring
- * a window state without overwriting tabs.
- */
-add_task(function () {
- const initialState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:blank" }] }
- ],
- _closedTabs: [
- { state: { entries: [{ ID: 1000, url: "about:blank" }]} },
- { state: { entries: [{ ID: 1001, url: "about:blank" }]} }
- ]
- }]
- }
-
- const restoreState = {
- windows: [{
- tabs: [
- { entries: [{ url: "about:robots" }] }
- ],
- _closedTabs: [
- { state: { entries: [{ ID: 1002, url: "about:robots" }]} },
- { state: { entries: [{ ID: 1003, url: "about:robots" }]} },
- { state: { entries: [{ ID: 1004, url: "about:robots" }]} }
- ]
- }]
- }
-
- const maxTabsUndo = 4;
- gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", maxTabsUndo);
-
- // Open a new window and restore it to an initial state.
- let win = yield promiseNewWindowLoaded({private: false});
- SessionStore.setWindowState(win, JSON.stringify(initialState), true);
- is(SessionStore.getClosedTabCount(win), 2, "2 closed tabs after restoring initial state");
-
- // Restore the new state but do not overwrite existing tabs (this should
- // cause the closed tabs to be merged).
- SessionStore.setWindowState(win, JSON.stringify(restoreState), false);
-
- // Verify the windows closed tab data is correct.
- let iClosed = initialState.windows[0]._closedTabs;
- let rClosed = restoreState.windows[0]._closedTabs;
- let cData = JSON.parse(SessionStore.getClosedTabData(win));
-
- is(cData.length, Math.min(iClosed.length + rClosed.length, maxTabsUndo),
- "Number of closed tabs is correct");
-
- // When the closed tabs are merged the restored tabs are considered to be
- // closed more recently.
- for (let i = 0; i < cData.length; i++) {
- if (i < rClosed.length) {
- is(cData[i].state.entries[0].ID, rClosed[i].state.entries[0].ID,
- "Closed tab entry matches");
- } else {
- is(cData[i].state.entries[0].ID, iClosed[i - rClosed.length].state.entries[0].ID,
- "Closed tab entry matches");
- }
- }
-
- // Clean up.
- gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
- yield BrowserTestUtils.closeWindow(win);
-});
-
-
diff --git a/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js b/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js
deleted file mode 100644
index fc958b293..000000000
--- a/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page.";
-
-add_task(function*() {
- // Load an empty, non-remote tab at about:blank...
- let tab = gBrowser.addTab("about:blank", {
- forceNotRemote: true,
- });
- gBrowser.selectedTab = tab;
- let browser = gBrowser.selectedBrowser;
- ok(!browser.isRemoteBrowser, "Ensure browser is not remote");
- // Load a remote page, and then another remote page immediately
- // after.
- browser.loadURI(PAGE_1);
- browser.stop();
- browser.loadURI(PAGE_2);
- yield BrowserTestUtils.browserLoaded(browser);
-
- ok(browser.isRemoteBrowser, "Should have switched remoteness");
- yield TabStateFlusher.flush(browser);
- let state = JSON.parse(ss.getTabState(tab));
- let entries = state.entries;
- is(entries.length, 1, "There should only be one entry");
- is(entries[0].url, PAGE_2, "Should have PAGE_2 as the sole history entry");
- is(browser.currentURI.spec, PAGE_2, "Should have PAGE_2 as the browser currentURI");
-
- yield ContentTask.spawn(browser, PAGE_2, function*(PAGE_2) {
- docShell.QueryInterface(Ci.nsIWebNavigation);
- Assert.equal(docShell.currentURI.spec, PAGE_2,
- "Content should have PAGE_2 as the browser currentURI");
- });
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_newtab_userTypedValue.js b/browser/components/sessionstore/test/browser_newtab_userTypedValue.js
deleted file mode 100644
index 66dc93380..000000000
--- a/browser/components/sessionstore/test/browser_newtab_userTypedValue.js
+++ /dev/null
@@ -1,72 +0,0 @@
-"use strict";
-
-requestLongerTimeout(4);
-
-/**
- * Test that when restoring an 'initial page' with session restore, it
- * produces an empty URL bar, rather than leaving its URL explicitly
- * there as a 'user typed value'.
- */
-add_task(function* () {
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:logo");
- let tabOpenedAndSwitchedTo = BrowserTestUtils.switchTab(win.gBrowser, () => {});
-
- // This opens about:newtab:
- win.BrowserOpenTab();
- let tab = yield tabOpenedAndSwitchedTo;
- is(win.gURLBar.value, "", "URL bar should be empty");
- is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null");
- let state = JSON.parse(SessionStore.getTabState(tab));
- ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state");
- tab = null;
-
- yield BrowserTestUtils.closeWindow(win);
-
- ok(SessionStore.getClosedWindowCount(), "Should have a closed window");
-
- win = SessionStore.undoCloseWindow(0);
- yield TestUtils.topicObserved("sessionstore-single-window-restored",
- subject => subject == win);
- // Don't wait for load here because it's about:newtab and we may have swapped in
- // a preloaded browser.
- yield TabStateFlusher.flush(win.gBrowser.selectedBrowser);
-
- is(win.gURLBar.value, "", "URL bar should be empty");
- tab = win.gBrowser.selectedTab;
- is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null");
- state = JSON.parse(SessionStore.getTabState(tab));
- ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state");
-
- yield BrowserTestUtils.removeTab(tab);
-
- for (let url of gInitialPages) {
- if (url == BROWSER_NEW_TAB_URL) {
- continue; // We tested about:newtab using BrowserOpenTab() above.
- }
- info("Testing " + url + " - " + new Date());
- yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url);
- yield BrowserTestUtils.closeWindow(win);
-
- ok(SessionStore.getClosedWindowCount(), "Should have a closed window");
-
- win = SessionStore.undoCloseWindow(0);
- yield TestUtils.topicObserved("sessionstore-single-window-restored",
- subject => subject == win);
- yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
- yield TabStateFlusher.flush(win.gBrowser.selectedBrowser);
-
- is(win.gURLBar.value, "", "URL bar should be empty");
- tab = win.gBrowser.selectedTab;
- is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null");
- state = JSON.parse(SessionStore.getTabState(tab));
- ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state");
-
- info("Removing tab - " + new Date());
- yield BrowserTestUtils.removeTab(tab);
- info("Finished removing tab - " + new Date());
- }
- info("Removing window - " + new Date());
- yield BrowserTestUtils.closeWindow(win);
- info("Finished removing window - " + new Date());
-});
diff --git a/browser/components/sessionstore/test/browser_pageStyle.js b/browser/components/sessionstore/test/browser_pageStyle.js
deleted file mode 100644
index 7abee5d9d..000000000
--- a/browser/components/sessionstore/test/browser_pageStyle.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const URL = getRootDirectory(gTestPath) + "browser_pageStyle_sample.html";
-const URL_NESTED = getRootDirectory(gTestPath) + "browser_pageStyle_sample_nested.html";
-
-/**
- * This test ensures that page style information is correctly persisted.
- */
-add_task(function page_style() {
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- let sheets = yield getStyleSheets(browser);
-
- // Enable all style sheets one by one.
- for (let [title, disabled] of sheets) {
- yield enableStyleSheetsForSet(browser, title);
-
- let tab2 = gBrowser.duplicateTab(tab);
- yield promiseTabRestored(tab2);
-
- let sheets = yield getStyleSheets(tab2.linkedBrowser);
- let enabled = sheets.filter(([title, disabled]) => !disabled);
-
- if (title.startsWith("fail_")) {
- ok(!enabled.length, "didn't restore " + title);
- } else {
- is(enabled.length, 1, "restored one style sheet");
- is(enabled[0][0], title, "restored correct sheet");
- }
-
- gBrowser.removeTab(tab2);
- }
-
- // Disable all styles and verify that this is correctly persisted.
- yield setAuthorStyleDisabled(browser, true);
-
- let tab2 = gBrowser.duplicateTab(tab);
- yield promiseTabRestored(tab2);
-
- let authorStyleDisabled = yield getAuthorStyleDisabled(tab2.linkedBrowser);
- ok(authorStyleDisabled, "disabled all stylesheets");
-
- // Clean up.
- gBrowser.removeTab(tab);
- gBrowser.removeTab(tab2);
-});
-
-/**
- * This test ensures that page style notification from nested documents are
- * received and the page style is persisted correctly.
- */
-add_task(function nested_page_style() {
- let tab = gBrowser.addTab(URL_NESTED);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- yield enableSubDocumentStyleSheetsForSet(browser, "alternate");
- yield promiseRemoveTab(tab);
-
- let [{state: {pageStyle}}] = JSON.parse(ss.getClosedTabData(window));
- let expected = JSON.stringify({children: [{pageStyle: "alternate"}]});
- is(JSON.stringify(pageStyle), expected, "correct pageStyle persisted");
-});
-
-function getStyleSheets(browser) {
- return sendMessage(browser, "ss-test:getStyleSheets");
-}
-
-function enableStyleSheetsForSet(browser, name) {
- return sendMessage(browser, "ss-test:enableStyleSheetsForSet", name);
-}
-
-function enableSubDocumentStyleSheetsForSet(browser, name) {
- return sendMessage(browser, "ss-test:enableSubDocumentStyleSheetsForSet", {
- id: "iframe", set: name
- });
-}
-
-function getAuthorStyleDisabled(browser) {
- return sendMessage(browser, "ss-test:getAuthorStyleDisabled");
-}
-
-function setAuthorStyleDisabled(browser, val) {
- return sendMessage(browser, "ss-test:setAuthorStyleDisabled", val)
-}
diff --git a/browser/components/sessionstore/test/browser_pageStyle_sample.html b/browser/components/sessionstore/test/browser_pageStyle_sample.html
deleted file mode 100644
index 810054049..000000000
--- a/browser/components/sessionstore/test/browser_pageStyle_sample.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>pageStyle sample</title>
-
- <link href="404.css" title="default" rel="stylesheet">
- <link href="404.css" title="alternate" rel="alternate stylesheet">
- <link href="404.css" title="altERnate" rel=" styLEsheet altERnate ">
- <link href="404.css" title="media_empty" rel="alternate stylesheet" media="">
- <link href="404.css" title="media_all" rel="alternate stylesheet" media="all">
- <link href="404.css" title="media_ALL" rel="alternate stylesheet" media=" ALL ">
- <link href="404.css" title="media_screen" rel="alternate stylesheet" media="screen">
- <link href="404.css" title="media_print_screen" rel="alternate stylesheet" media="print,screen">
-</head>
-<body></body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html b/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html
deleted file mode 100644
index 157609fa6..000000000
--- a/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>pageStyle sample (nested)</title>
-</head>
-<body>
- <iframe id="iframe" src="browser_pageStyle_sample.html"/>
-</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_page_title.js b/browser/components/sessionstore/test/browser_page_title.js
deleted file mode 100644
index 9bbb1ca76..000000000
--- a/browser/components/sessionstore/test/browser_page_title.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-const URL = "data:text/html,<title>initial title</title>";
-
-add_task(function* () {
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- // Remove the tab.
- yield promiseRemoveTab(tab);
-
- // Check the title.
- let [{state: {entries}}] = JSON.parse(ss.getClosedTabData(window));
- is(entries[0].title, "initial title", "correct title");
-});
-
-add_task(function* () {
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to ensure we collected the initial title.
- yield TabStateFlusher.flush(browser);
-
- // Set a new title.
- yield ContentTask.spawn(browser, null, function* () {
- return new Promise(resolve => {
- addEventListener("DOMTitleChanged", function onTitleChanged() {
- removeEventListener("DOMTitleChanged", onTitleChanged);
- resolve();
- });
-
- content.document.title = "new title";
- });
- });
-
- // Remove the tab.
- yield promiseRemoveTab(tab);
-
- // Check the title.
- let [{state: {entries}}] = JSON.parse(ss.getClosedTabData(window));
- is(entries[0].title, "new title", "correct title");
-});
diff --git a/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js b/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js
deleted file mode 100644
index 1deb461c8..000000000
--- a/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js
+++ /dev/null
@@ -1,95 +0,0 @@
-"use strict";
-
-const SELFCHROMEURL =
- "chrome://mochitests/content/browser/browser/" +
- "components/sessionstore/test/browser_parentProcessRestoreHash.js";
-
-const Cm = Components.manager;
-
-const TESTCLASSID = "78742c04-3630-448c-9be3-6c5070f062de";
-
-const TESTURL = "about:testpageforsessionrestore#foo";
-
-
-let TestAboutPage = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
- getURIFlags: function(aURI) {
- // No CAN_ or MUST_LOAD_IN_CHILD means this loads in the parent:
- return Ci.nsIAboutModule.ALLOW_SCRIPT |
- Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT |
- Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT;
- },
-
- newChannel: function(aURI, aLoadInfo) {
- // about: page inception!
- let newURI = Services.io.newURI(SELFCHROMEURL, null, null);
- let channel = Services.io.newChannelFromURIWithLoadInfo(newURI,
- aLoadInfo);
- channel.originalURI = aURI;
- return channel;
- },
-
- createInstance: function(outer, iid) {
- if (outer != null) {
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
- return this.QueryInterface(iid);
- },
-
- register: function() {
- Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory(
- Components.ID(TESTCLASSID), "Only here for a test",
- "@mozilla.org/network/protocol/about;1?what=testpageforsessionrestore", this);
- },
-
- unregister: function() {
- Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory(
- Components.ID(TESTCLASSID), this);
- }
-};
-
-
-/**
- * Test that switching from a remote to a parent process browser
- * correctly clears the userTypedValue
- */
-add_task(function* () {
- TestAboutPage.register();
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/", true, true);
- ok(tab.linkedBrowser.isRemoteBrowser, "Browser should be remote");
-
- let resolveLocationChangePromise;
- let locationChangePromise = new Promise(r => resolveLocationChangePromise = r);
- let wpl = {
- onStateChange(wpl, request, state, status) {
- let location = request.QueryInterface(Ci.nsIChannel).originalURI;
- // Ignore about:blank loads.
- let docStop = Ci.nsIWebProgressListener.STATE_STOP |
- Ci.nsIWebProgressListener.STATE_IS_NETWORK;
- if (location.spec == "about:blank" || (state & docStop == docStop)) {
- return;
- }
- is(location.spec, TESTURL, "Got the expected URL");
- resolveLocationChangePromise();
- },
- };
- gBrowser.addProgressListener(wpl);
-
- gURLBar.value = TESTURL;
- gURLBar.select();
- EventUtils.sendKey("return");
-
- yield locationChangePromise;
-
- ok(!tab.linkedBrowser.isRemoteBrowser, "Browser should no longer be remote");
-
- is(gURLBar.textValue, TESTURL, "URL bar visible value should be correct.");
- is(gURLBar.value, TESTURL, "URL bar value should be correct.");
- is(gURLBar.getAttribute("pageproxystate"), "valid", "URL bar is in valid page proxy state");
-
- ok(!tab.linkedBrowser.userTypedValue, "No userTypedValue should be on the browser.");
-
- yield BrowserTestUtils.removeTab(tab);
- gBrowser.removeProgressListener(wpl);
- TestAboutPage.unregister();
-});
diff --git a/browser/components/sessionstore/test/browser_pending_tabs.js b/browser/components/sessionstore/test/browser_pending_tabs.js
deleted file mode 100644
index e734e55c9..000000000
--- a/browser/components/sessionstore/test/browser_pending_tabs.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-const TAB_STATE = {
- entries: [{ url: "about:mozilla" }, { url: "about:robots" }],
- index: 1,
-};
-
-add_task(function* () {
- // Create a background tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // The tab shouldn't be restored right away.
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- // Prepare the tab state.
- let promise = promiseTabRestoring(tab);
- ss.setTabState(tab, JSON.stringify(TAB_STATE));
- ok(tab.hasAttribute("pending"), "tab is pending");
- yield promise;
-
- // Flush to ensure the parent has all data.
- yield TabStateFlusher.flush(browser);
-
- // Check that the shistory index is the one we restored.
- let tabState = TabState.collect(tab);
- is(tabState.index, TAB_STATE.index, "correct shistory index");
-
- // Check we don't collect userTypedValue when we shouldn't.
- ok(!tabState.userTypedValue, "tab didn't have a userTypedValue");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_privatetabs.js b/browser/components/sessionstore/test/browser_privatetabs.js
deleted file mode 100644
index cc02e56cf..000000000
--- a/browser/components/sessionstore/test/browser_privatetabs.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function cleanup() {
- info("Forgetting closed tabs");
- while (ss.getClosedTabCount(window)) {
- ss.forgetClosedTab(window, 0);
- }
-});
-
-add_task(function() {
- let URL_PUBLIC = "http://example.com/public/" + Math.random();
- let URL_PRIVATE = "http://example.com/private/" + Math.random();
- let tab1, tab2;
- try {
- // Setup a public tab and a private tab
- info("Setting up public tab");
- tab1 = gBrowser.addTab(URL_PUBLIC);
- yield promiseBrowserLoaded(tab1.linkedBrowser);
-
- info("Setting up private tab");
- tab2 = gBrowser.addTab();
- yield promiseBrowserLoaded(tab2.linkedBrowser);
- yield setUsePrivateBrowsing(tab2.linkedBrowser, true);
- tab2.linkedBrowser.loadURI(URL_PRIVATE);
- yield promiseBrowserLoaded(tab2.linkedBrowser);
-
- info("Flush to make sure chrome received all data.");
- yield TabStateFlusher.flush(tab1.linkedBrowser);
- yield TabStateFlusher.flush(tab2.linkedBrowser);
-
- info("Checking out state");
- let state = yield promiseRecoveryFileContents();
-
- info("State: " + state);
- // Ensure that sessionstore.js only knows about the public tab
- ok(state.indexOf(URL_PUBLIC) != -1, "State contains public tab");
- ok(state.indexOf(URL_PRIVATE) == -1, "State does not contain private tab");
-
- // Ensure that we can close and undo close the public tab but not the private tab
- gBrowser.removeTab(tab2);
- tab2 = null;
-
- gBrowser.removeTab(tab1);
- tab1 = null;
-
- tab1 = ss.undoCloseTab(window, 0);
- ok(true, "Public tab supports undo close");
-
- is(ss.getClosedTabCount(window), 0, "Private tab does not support undo close");
-
- } finally {
- if (tab1) {
- gBrowser.removeTab(tab1);
- }
- if (tab2) {
- gBrowser.removeTab(tab2);
- }
- }
-});
-
-add_task(function () {
- const FRAME_SCRIPT = "data:," +
- "docShell.QueryInterface%28Components.interfaces.nsILoadContext%29.usePrivateBrowsing%3Dtrue";
-
- // Clear the list of closed windows.
- forgetClosedWindows();
-
- // Create a new window to attach our frame script to.
- let win = yield promiseNewWindowLoaded();
- let mm = win.getGroupMessageManager("browsers");
- mm.loadFrameScript(FRAME_SCRIPT, true);
-
- // Create a new tab in the new window that will load the frame script.
- let tab = win.gBrowser.addTab("about:mozilla");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Check that we consider the tab as private.
- let state = JSON.parse(ss.getTabState(tab));
- ok(state.isPrivate, "tab considered private");
-
- // Ensure we don't allow restoring closed private tabs in non-private windows.
- win.gBrowser.removeTab(tab);
- is(ss.getClosedTabCount(win), 0, "no tabs to restore");
-
- // Create a new tab in the new window that will load the frame script.
- tab = win.gBrowser.addTab("about:mozilla");
- browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Check that we consider the tab as private.
- state = JSON.parse(ss.getTabState(tab));
- ok(state.isPrivate, "tab considered private");
-
- // Check that all private tabs are removed when the non-private
- // window is closed and we don't save windows without any tabs.
- yield BrowserTestUtils.closeWindow(win);
- is(ss.getClosedWindowCount(), 0, "no windows to restore");
-});
-
-add_task(function () {
- // Clear the list of closed windows.
- forgetClosedWindows();
-
- // Create a new window to attach our frame script to.
- let win = yield promiseNewWindowLoaded({private: true});
-
- // Create a new tab in the new window that will load the frame script.
- let tab = win.gBrowser.addTab("about:mozilla");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- yield TabStateFlusher.flush(browser);
-
- // Check that we consider the tab as private.
- let state = JSON.parse(ss.getTabState(tab));
- ok(state.isPrivate, "tab considered private");
-
- // Ensure that closed tabs in a private windows can be restored.
- win.gBrowser.removeTab(tab);
- is(ss.getClosedTabCount(win), 1, "there is a single tab to restore");
-
- // Ensure that closed private windows can never be restored.
- yield BrowserTestUtils.closeWindow(win);
- is(ss.getClosedWindowCount(), 0, "no windows to restore");
-});
-
-function setUsePrivateBrowsing(browser, val) {
- return sendMessage(browser, "ss-test:setUsePrivateBrowsing", val);
-}
-
diff --git a/browser/components/sessionstore/test/browser_purge_shistory.js b/browser/components/sessionstore/test/browser_purge_shistory.js
deleted file mode 100644
index 28c6f6f24..000000000
--- a/browser/components/sessionstore/test/browser_purge_shistory.js
+++ /dev/null
@@ -1,59 +0,0 @@
-"use strict";
-
-/**
- * This test checks that pending tabs are treated like fully loaded tabs when
- * purging session history. Just like for fully loaded tabs we want to remove
- * every but the current shistory entry.
- */
-
-const TAB_STATE = {
- entries: [{url: "about:mozilla"}, {url: "about:robots"}],
- index: 1,
-};
-
-function checkTabContents(browser) {
- return ContentTask.spawn(browser, null, function* () {
- let Ci = Components.interfaces;
- let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation);
- let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal);
- Assert.ok(history && history.count == 1 && content.document.documentURI == "about:mozilla",
- "expected tab contents found");
- });
-}
-
-add_task(function* () {
- // Create a new tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- yield promiseTabState(tab, TAB_STATE);
-
- // Create another new tab.
- let tab2 = gBrowser.addTab("about:blank");
- let browser2 = tab2.linkedBrowser;
- yield promiseBrowserLoaded(browser2);
-
- // The tab shouldn't be restored right away.
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- // Prepare the tab state.
- let promise = promiseTabRestoring(tab2);
- ss.setTabState(tab2, JSON.stringify(TAB_STATE));
- ok(tab2.hasAttribute("pending"), "tab is pending");
- yield promise;
-
- // Purge session history.
- Services.obs.notifyObservers(null, "browser:purge-session-history", "");
- yield checkTabContents(browser);
- ok(tab2.hasAttribute("pending"), "tab is still pending");
-
- // Kick off tab restoration.
- gBrowser.selectedTab = tab2;
- yield promiseTabRestored(tab2);
- yield checkTabContents(browser2);
- ok(!tab2.hasAttribute("pending"), "tab is not pending anymore");
-
- // Cleanup.
- gBrowser.removeTab(tab2);
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js b/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js
deleted file mode 100644
index 7dbee03fd..000000000
--- a/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js
+++ /dev/null
@@ -1,342 +0,0 @@
-"use strict";
-
-/**
- * This set of tests checks that the remoteness is properly
- * set for each browser in a window when that window has
- * session state loaded into it.
- */
-
-/**
- * Takes a SessionStore window state object for a single
- * window, sets the selected tab for it, and then returns
- * the object to be passed to SessionStore.setWindowState.
- *
- * @param state (object)
- * The state to prepare to be sent to a window. This is
- * state should just be for a single window.
- * @param selected (int)
- * The 1-based index of the selected tab. Note that
- * If this is 0, then the selected tab will not change
- * from what's already selected in the window that we're
- * sending state to.
- * @returns (object)
- * The JSON encoded string to call
- * SessionStore.setWindowState with.
- */
-function prepareState(state, selected) {
- // We'll create a copy so that we don't accidentally
- // modify the caller's selected property.
- let copy = {};
- Object.assign(copy, state);
- copy.selected = selected;
-
- return {
- windows: [ copy ],
- };
-}
-
-const SIMPLE_STATE = {
- tabs: [
- { entries: [{ url: "http://example.com/", title: "title" }] },
- { entries: [{ url: "http://example.com/", title: "title" }] },
- { entries: [{ url: "http://example.com/", title: "title" }] },
- ],
- title: "",
- _closedTabs: [],
-};
-
-const PINNED_STATE = {
- tabs: [
- { entries: [{ url: "http://example.com/", title: "title" }], pinned: true },
- { entries: [{ url: "http://example.com/", title: "title" }], pinned: true },
- { entries: [{ url: "http://example.com/", title: "title" }] },
- ],
- title: "",
- _closedTabs: [],
-};
-
-/**
- * This is where most of the action is happening. This function takes
- * an Array of "test scenario" Objects and runs them. For each scenario, a
- * window is opened, put into some state, and then a new state is
- * loaded into that window. We then check to make sure that the
- * right things have happened in that window wrt remoteness flips.
- *
- * The schema for a testing scenario Object is as follows:
- *
- * initialRemoteness:
- * an Array that represents the starting window. Each bool
- * in the Array represents the window tabs in order. A "true"
- * indicates that that tab should be remote. "false" if the tab
- * should be non-remote.
- *
- * initialSelectedTab:
- * The 1-based index of the tab that we want to select for the
- * restored window. This is 1-based to avoid confusion with the
- * selectedTab property described down below, though you probably
- * want to set this to be greater than 0, since the initial window
- * needs to have a defined initial selected tab. Because of this,
- * the test will throw if initialSelectedTab is 0.
- *
- * stateToRestore:
- * A JS Object for the state to send down to the window.
- *
- * selectedTab:
- * The 1-based index of the tab that we want to select for the
- * restored window. Leave this at 0 if you don't want to change
- * the selection from the initial window state.
- *
- * expectedFlips:
- * an Array that represents the window that we end up with after
- * restoring state. Each bool in the Array represents the window tabs,
- * in order. A "true" indicates that the tab should have flipped
- * its remoteness once. "false" indicates that the tab should never
- * have flipped remoteness. Note that any tab that flips its remoteness
- * more than once will cause a test failure.
- *
- * expectedRemoteness:
- * an Array that represents the window that we end up with after
- * restoring state. Each bool in the Array represents the window
- * tabs in order. A "true" indicates that the tab be remote, and
- * a "false" indicates that the tab should be "non-remote". We
- * need this Array in order to test pinned tabs which will also
- * be loaded by default, and therefore should end up remote.
- *
- */
-function* runScenarios(scenarios) {
- for (let scenario of scenarios) {
- // Let's make sure our scenario is sane first.
- Assert.equal(scenario.expectedFlips.length,
- scenario.expectedRemoteness.length,
- "All expected flips and remoteness needs to be supplied");
- Assert.ok(scenario.initialSelectedTab > 0,
- "You must define an initially selected tab");
-
- // First, we need to create the initial conditions, so we
- // open a new window to put into our starting state...
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let tabbrowser = win.gBrowser;
- Assert.ok(tabbrowser.selectedBrowser.isRemoteBrowser,
- "The initial browser should be remote.");
- // Now put the window into the expected initial state.
- for (let i = 0; i < scenario.initialRemoteness.length; ++i) {
- let tab;
- if (i > 0) {
- // The window starts with one tab, so we need to create
- // any of the additional ones required by this test.
- info("Opening a new tab");
- tab = yield BrowserTestUtils.openNewForegroundTab(tabbrowser)
- } else {
- info("Using the selected tab");
- tab = tabbrowser.selectedTab;
- }
- let browser = tab.linkedBrowser;
- let remotenessState = scenario.initialRemoteness[i];
- tabbrowser.updateBrowserRemoteness(browser, remotenessState);
- }
-
- // And select the requested tab.
- let tabToSelect = tabbrowser.tabs[scenario.initialSelectedTab - 1];
- if (tabbrowser.selectedTab != tabToSelect) {
- yield BrowserTestUtils.switchTab(tabbrowser, tabToSelect);
- }
-
- // Hook up an event listener to make sure that the right
- // tabs flip remoteness, and only once.
- let flipListener = {
- seenBeforeTabs: new Set(),
- seenAfterTabs: new Set(),
- handleEvent(e) {
- let index = Array.from(tabbrowser.tabs).indexOf(e.target);
- switch (e.type) {
- case "BeforeTabRemotenessChange":
- info(`Saw tab at index ${index} before remoteness flip`);
- if (this.seenBeforeTabs.has(e.target)) {
- Assert.ok(false, "Saw tab before remoteness flip more than once");
- }
- this.seenBeforeTabs.add(e.target);
- break;
- case "TabRemotenessChange":
- info(`Saw tab at index ${index} after remoteness flip`);
- if (this.seenAfterTabs.has(e.target)) {
- Assert.ok(false, "Saw tab after remoteness flip more than once");
- }
- this.seenAfterTabs.add(e.target);
- break;
- }
- },
- };
-
- win.addEventListener("BeforeTabRemotenessChange", flipListener);
- win.addEventListener("TabRemotenessChange", flipListener);
-
- // Okay, time to test!
- let state = prepareState(scenario.stateToRestore,
- scenario.selectedTab);
-
- SessionStore.setWindowState(win, state, true);
-
- win.removeEventListener("BeforeTabRemotenessChange", flipListener);
- win.removeEventListener("TabRemotenessChange", flipListener);
-
- // Because we know that scenario.expectedFlips and
- // scenario.expectedRemoteness have the same length, we
- // can check that we satisfied both with the same loop.
- for (let i = 0; i < scenario.expectedFlips.length; ++i) {
- let expectedToFlip = scenario.expectedFlips[i];
- let expectedRemoteness = scenario.expectedRemoteness[i];
- let tab = tabbrowser.tabs[i];
- if (expectedToFlip) {
- Assert.ok(flipListener.seenBeforeTabs.has(tab),
- `We should have seen tab at index ${i} before remoteness flip`);
- Assert.ok(flipListener.seenAfterTabs.has(tab),
- `We should have seen tab at index ${i} after remoteness flip`);
- } else {
- Assert.ok(!flipListener.seenBeforeTabs.has(tab),
- `We should not have seen tab at index ${i} before remoteness flip`);
- Assert.ok(!flipListener.seenAfterTabs.has(tab),
- `We should not have seen tab at index ${i} after remoteness flip`);
- }
-
- Assert.equal(tab.linkedBrowser.isRemoteBrowser, expectedRemoteness,
- "Should have gotten the expected remoteness " +
- `for the tab at index ${i}`);
- }
-
- yield BrowserTestUtils.closeWindow(win);
- }
-}
-
-/**
- * Tests that if we restore state to browser windows with
- * a variety of initial remoteness states, that we only flip
- * the remoteness on the necessary tabs. For this particular
- * set of tests, we assume that tabs are restoring on demand.
- */
-add_task(function*() {
- // This test opens and closes windows, which might bog down
- // a debug build long enough to time out the test, so we
- // extend the tolerance on timeouts.
- requestLongerTimeout(5);
-
- yield SpecialPowers.pushPrefEnv({
- "set": [["browser.sessionstore.restore_on_demand", true]],
- });
-
- const TEST_SCENARIOS = [
- // Only one tab in the new window, and it's remote. This
- // is the common case, since this is how restoration occurs
- // when the restored window is being opened.
- {
- initialRemoteness: [true],
- initialSelectedTab: 1,
- stateToRestore: SIMPLE_STATE,
- selectedTab: 3,
- // The initial tab is remote and should go into
- // the background state. The second and third tabs
- // are new and should be initialized non-remote.
- expectedFlips: [true, false, true],
- // Only the selected tab should be remote.
- expectedRemoteness: [false, false, true],
- },
-
- // A single remote tab, and this is the one that's going
- // to be selected once state is restored.
- {
- initialRemoteness: [true],
- initialSelectedTab: 1,
- stateToRestore: SIMPLE_STATE,
- selectedTab: 1,
- // The initial tab is remote and selected, so it should
- // not flip remoteness. The other two new tabs should
- // be non-remote by default.
- expectedFlips: [false, false, false],
- // Only the selected tab should be remote.
- expectedRemoteness: [true, false, false],
- },
-
- // A single remote tab which starts selected. We set the
- // selectedTab to 0 which is equivalent to "don't change
- // the tab selection in the window".
- {
- initialRemoteness: [true],
- initialSelectedTab: 1,
- stateToRestore: SIMPLE_STATE,
- selectedTab: 0,
- // The initial tab is remote and selected, so it should
- // not flip remoteness. The other two new tabs should
- // be non-remote by default.
- expectedFlips: [false, false, false],
- // Only the selected tab should be remote.
- expectedRemoteness: [true, false, false],
- },
-
- // An initially remote tab, but we're going to load
- // some pinned tabs now, and the pinned tabs should load
- // right away.
- {
- initialRemoteness: [true],
- initialSelectedTab: 1,
- stateToRestore: PINNED_STATE,
- selectedTab: 3,
- // The initial tab is pinned and will load right away,
- // so it should stay remote. The second tab is new
- // and pinned, so it should start remote and not flip.
- // The third tab is not pinned, but it is selected,
- // so it will start non-remote, and then flip remoteness.
- expectedFlips: [false, false, true],
- // Both pinned tabs and the selected tabs should all
- // end up being remote.
- expectedRemoteness: [true, true, true],
- },
-
- // A single non-remote tab.
- {
- initialRemoteness: [false],
- initialSelectedTab: 1,
- stateToRestore: SIMPLE_STATE,
- selectedTab: 2,
- // The initial tab is non-remote and should stay
- // that way. The second and third tabs are new and
- // should be initialized non-remote.
- expectedFlips: [false, true, false],
- // Only the selected tab should be remote.
- expectedRemoteness: [false, true, false],
- },
-
- // A mixture of remote and non-remote tabs.
- {
- initialRemoteness: [true, false, true],
- initialSelectedTab: 1,
- stateToRestore: SIMPLE_STATE,
- selectedTab: 3,
- // The initial tab is remote and should flip to non-remote
- // as it is put into the background. The second tab should
- // stay non-remote, and the third one should stay remote.
- expectedFlips: [true, false, false],
- // Only the selected tab should be remote.
- expectedRemoteness: [false, false, true],
- },
-
- // An initially non-remote tab, but we're going to load
- // some pinned tabs now, and the pinned tabs should load
- // right away.
- {
- initialRemoteness: [false],
- initialSelectedTab: 1,
- stateToRestore: PINNED_STATE,
- selectedTab: 3,
- // The initial tab is pinned and will load right away,
- // so it should flip remoteness. The second tab is new
- // and pinned, so it should start remote and not flip.
- // The third tab is not pinned, but it is selected,
- // so it will start non-remote, and then flip remoteness.
- expectedFlips: [true, false, true],
- // Both pinned tabs and the selected tabs should all
- // end up being remote.
- expectedRemoteness: [true, true, true],
- },
- ];
-
- yield* runScenarios(TEST_SCENARIOS);
-});
diff --git a/browser/components/sessionstore/test/browser_replace_load.js b/browser/components/sessionstore/test/browser_replace_load.js
deleted file mode 100644
index 5464a0874..000000000
--- a/browser/components/sessionstore/test/browser_replace_load.js
+++ /dev/null
@@ -1,52 +0,0 @@
-"use strict";
-
-const STATE = {
- entries: [{url: "about:robots"}, {url: "about:mozilla"}],
- selected: 2
-};
-
-/**
- * Bug 1100223. Calling browser.loadURI() while a tab is loading causes
- * sessionstore to override the desired target URL. This test ensures that
- * calling loadURI() on a pending tab causes the tab to no longer be marked
- * as pending and correctly finish the instructed load while keeping the
- * restored history around.
- */
-add_task(function* () {
- yield testSwitchToTab("about:mozilla#fooobar", {ignoreFragment: "whenComparingAndReplace"});
- yield testSwitchToTab("about:mozilla?foo=bar", {replaceQueryString: true});
-});
-
-var testSwitchToTab = Task.async(function* (url, options) {
- // Create a background tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // The tab shouldn't be restored right away.
- Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true);
-
- // Prepare the tab state.
- let promise = promiseTabRestoring(tab);
- ss.setTabState(tab, JSON.stringify(STATE));
- ok(tab.hasAttribute("pending"), "tab is pending");
- yield promise;
-
- // Switch-to-tab with a similar URI.
- switchToTabHavingURI(url, false, options);
-
- // Tab should now restore
- yield promiseTabRestored(tab);
- is(browser.currentURI.spec, url, "correct URL loaded");
-
- // Check that we didn't lose any history entries.
- yield ContentTask.spawn(browser, null, function* () {
- let Ci = Components.interfaces;
- let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation);
- let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal);
- Assert.equal(history && history.count, 3, "three history entries");
- });
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js b/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js
deleted file mode 100644
index 5767c6c0f..000000000
--- a/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Bug 1267910 - The regression test case for session cookies.
- */
-
-"use strict";
-
-const TEST_HOST = "www.example.com";
-const COOKIE =
-{
- name: "test1",
- value: "yes1",
- path: "/browser/browser/components/sessionstore/test/"
-};
-const SESSION_DATA = `
-{
- "version": ["sessionrestore", 1],
- "windows": [{
- "tabs": [{
- "entries": [],
- "lastAccessed": 1463893009797,
- "hidden": false,
- "attributes": {},
- "image": null
- }, {
- "entries": [{
- "url": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html",
- \"charset": "UTF-8",
- "ID": 0,
- "docshellID": 2,
- "originalURI": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html",
- \"docIdentifier": 0,
- "persist": true
- }],
- "lastAccessed": 1463893009321,
- "hidden": false,
- "attributes": {},
- "userContextId": 0,
- "index": 1,
- "image": "http://www.example.com/favicon.ico"
- }],
- "selected": 1,
- "_closedTabs": [],
- "busy": false,
- "width": 1024,
- "height": 768,
- "screenX": 4,
- "screenY": 23,
- "sizemode": "normal",
- "cookies": [{
- "host": "www.example.com",
- "value": "yes1",
- "path": "/browser/browser/components/sessionstore/test/",
- "name": "test1"
- }]
- }],
- "selectedWindow": 1,
- "_closedWindows": [],
- "session": {
- "lastUpdate": 1463893009801,
- "startTime": 1463893007134,
- "recentCrashes": 0
- },
- "global": {}
-}`;
-const SESSION_DATA_OA = `
-{
- "version": ["sessionrestore", 1],
- "windows": [{
- "tabs": [{
- "entries": [],
- "lastAccessed": 1463893009797,
- "hidden": false,
- "attributes": {},
- "image": null
- }, {
- "entries": [{
- "url": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html",
- \"charset": "UTF-8",
- "ID": 0,
- "docshellID": 2,
- "originalURI": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html",
- \"docIdentifier": 0,
- "persist": true
- }],
- "lastAccessed": 1463893009321,
- "hidden": false,
- "attributes": {},
- "userContextId": 0,
- "index": 1,
- "image": "http://www.example.com/favicon.ico"
- }],
- "selected": 1,
- "_closedTabs": [],
- "busy": false,
- "width": 1024,
- "height": 768,
- "screenX": 4,
- "screenY": 23,
- "sizemode": "normal",
- "cookies": [{
- "host": "www.example.com",
- "value": "yes1",
- "path": "/browser/browser/components/sessionstore/test/",
- "name": "test1",
- "originAttributes": {
- "addonId": "",
- "appId": 0,
- "inIsolatedMozBrowser": false,
- "userContextId": 0
- }
- }]
- }],
- "selectedWindow": 1,
- "_closedWindows": [],
- "session": {
- "lastUpdate": 1463893009801,
- "startTime": 1463893007134,
- "recentCrashes": 0
- },
- "global": {}
-}`;
-
-add_task(function* run_test() {
- // Wait until initialization is complete.
- yield SessionStore.promiseInitialized;
-
- // Clear cookies.
- Services.cookies.removeAll();
-
- // Open a new window.
- let win = yield promiseNewWindowLoaded();
-
- // Restore window with session cookies that have no originAttributes.
- ss.setWindowState(win, SESSION_DATA, true);
-
- let enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {});
- let cookie;
- let cookieCount = 0;
- while (enumerator.hasMoreElements()) {
- cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
- cookieCount++;
- }
-
- // Check that the cookie is restored successfully.
- is(cookieCount, 1, "expected one cookie");
- is(cookie.name, COOKIE.name, "cookie name successfully restored");
- is(cookie.value, COOKIE.value, "cookie value successfully restored");
- is(cookie.path, COOKIE.path, "cookie path successfully restored");
-
- // Clear cookies.
- Services.cookies.removeAll();
-
- // Restore window with session cookies that have originAttributes within.
- ss.setWindowState(win, SESSION_DATA_OA, true);
-
- enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {});
- cookieCount = 0;
- while (enumerator.hasMoreElements()) {
- cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
- cookieCount++;
- }
-
- // Check that the cookie is restored successfully.
- is(cookieCount, 1, "expected one cookie");
- is(cookie.name, COOKIE.name, "cookie name successfully restored");
- is(cookie.value, COOKIE.value, "cookie value successfully restored");
- is(cookie.path, COOKIE.path, "cookie path successfully restored");
-
- // Close our window.
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/sessionstore/test/browser_restore_redirect.js b/browser/components/sessionstore/test/browser_restore_redirect.js
deleted file mode 100644
index bea6e9f47..000000000
--- a/browser/components/sessionstore/test/browser_restore_redirect.js
+++ /dev/null
@@ -1,69 +0,0 @@
-"use strict";
-
-const BASE = "http://example.com/browser/browser/components/sessionstore/test/";
-const TARGET = BASE + "restore_redirect_target.html";
-
-/**
- * Ensure that a http redirect leaves a working tab.
- */
-add_task(function check_http_redirect() {
- let state = {
- entries: [{ url: BASE + "restore_redirect_http.html" }]
- };
-
- // Open a new tab to restore into.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseTabState(tab, state);
-
- info("Restored tab");
-
- yield TabStateFlusher.flush(browser);
- let data = TabState.collect(tab);
- is(data.entries.length, 1, "Should be one entry in session history");
- is(data.entries[0].url, TARGET, "Should be the right session history entry");
-
- ok(!("__SS_data" in browser), "Temporary restore data should have been cleared");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
-
-/**
- * Ensure that a js redirect leaves a working tab.
- */
-add_task(function check_js_redirect() {
- let state = {
- entries: [{ url: BASE + "restore_redirect_js.html" }]
- };
-
- let loadPromise = new Promise(resolve => {
- function listener(msg) {
- if (msg.data.url.endsWith("restore_redirect_target.html")) {
- window.messageManager.removeMessageListener("ss-test:loadEvent", listener);
- resolve();
- }
- }
-
- window.messageManager.addMessageListener("ss-test:loadEvent", listener);
- });
-
- // Open a new tab to restore into.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseTabState(tab, state);
-
- info("Restored tab");
-
- yield loadPromise;
-
- yield TabStateFlusher.flush(browser);
- let data = TabState.collect(tab);
- is(data.entries.length, 1, "Should be one entry in session history");
- is(data.entries[0].url, TARGET, "Should be the right session history entry");
-
- ok(!("__SS_data" in browser), "Temporary restore data should have been cleared");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js b/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js
deleted file mode 100644
index e29cd5e49..000000000
--- a/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that even if the user has set their tabs to restore
- * immediately on session start, that background tabs after a
- * content process crash restore on demand.
- */
-
-"use strict";
-
-const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page.";
-
-add_task(function* setup() {
- yield pushPrefs(["dom.ipc.processCount", 1],
- ["browser.tabs.animate", false],
- ["browser.sessionstore.restore_on_demand", false]);
-});
-
-add_task(function* test_revive_bg_tabs_on_demand() {
- let newTab1 = gBrowser.addTab(PAGE_1);
- let browser1 = newTab1.linkedBrowser;
- gBrowser.selectedTab = newTab1;
-
- let newTab2 = gBrowser.addTab(PAGE_2);
- let browser2 = newTab2.linkedBrowser;
-
- yield BrowserTestUtils.browserLoaded(browser1);
- yield BrowserTestUtils.browserLoaded(browser2);
-
- yield TabStateFlusher.flush(browser2);
-
- // Now crash the selected tab
- let windowReady = BrowserTestUtils.waitForEvent(window, "SSWindowStateReady");
- yield BrowserTestUtils.crashBrowser(browser1);
-
- ok(newTab1.hasAttribute("crashed"), "Selected tab should be crashed");
- ok(!newTab2.hasAttribute("crashed"), "Background tab should not be crashed");
-
- // Wait until we've had a chance to restore all tabs immediately
- yield windowReady;
-
- // But we should not have restored the background tab
- ok(newTab2.hasAttribute("pending"), "Background tab should be pending");
-
- // Now select newTab2 to make sure it restores.
- let newTab2Restored = promiseTabRestored(newTab2);
- gBrowser.selectedTab = newTab2;
- yield newTab2Restored;
-
- ok(browser2.isRemoteBrowser, "Restored browser should be remote");
-
- yield BrowserTestUtils.removeTab(newTab1);
- yield BrowserTestUtils.removeTab(newTab2);
-});
diff --git a/browser/components/sessionstore/test/browser_scrollPositions.js b/browser/components/sessionstore/test/browser_scrollPositions.js
deleted file mode 100644
index 865520772..000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const BASE = "http://example.com/browser/browser/components/sessionstore/test/"
-const URL = BASE + "browser_scrollPositions_sample.html";
-const URL_FRAMESET = BASE + "browser_scrollPositions_sample_frameset.html";
-
-// Randomized set of scroll positions we will use in this test.
-const SCROLL_X = Math.round(100 * (1 + Math.random()));
-const SCROLL_Y = Math.round(200 * (1 + Math.random()));
-const SCROLL_STR = SCROLL_X + "," + SCROLL_Y;
-
-const SCROLL2_X = Math.round(300 * (1 + Math.random()));
-const SCROLL2_Y = Math.round(400 * (1 + Math.random()));
-const SCROLL2_STR = SCROLL2_X + "," + SCROLL2_Y;
-
-requestLongerTimeout(2);
-
-/**
- * This test ensures that we properly serialize and restore scroll positions
- * for an average page without any frames.
- */
-add_task(function test_scroll() {
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Scroll down a little.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y});
- yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is fine");
-
- // Duplicate and check that the scroll position is restored.
- let tab2 = ss.duplicateTab(window, tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- let scroll = yield sendMessage(browser2, "ss-test:getScrollPosition");
- is(JSON.stringify(scroll), JSON.stringify({x: SCROLL_X, y: SCROLL_Y}),
- "scroll position has been duplicated correctly");
-
- // Check that reloading retains the scroll positions.
- browser2.reload();
- yield promiseBrowserLoaded(browser2);
- yield checkScroll(tab2, {scroll: SCROLL_STR}, "reloading retains scroll positions");
-
- // Check that a force-reload resets scroll positions.
- browser2.reloadWithFlags(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
- yield promiseBrowserLoaded(browser2);
- yield checkScroll(tab2, null, "force-reload resets scroll positions");
-
- // Scroll back to the top and check that the position has been reset. We
- // expect the scroll position to be "null" here because there is no data to
- // be stored if the frame is in its default scroll position.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0});
- yield checkScroll(tab, null, "no scroll stored");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
- yield promiseRemoveTab(tab2);
-});
-
-/**
- * This tests ensures that we properly serialize and restore scroll positions
- * for multiple frames of pages with framesets.
- */
-add_task(function test_scroll_nested() {
- let tab = gBrowser.addTab(URL_FRAMESET);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Scroll the first child frame down a little.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y, frame: 0});
- yield checkScroll(tab, {children: [{scroll: SCROLL_STR}]}, "scroll is fine");
-
- // Scroll the second child frame down a little.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL2_X, y: SCROLL2_Y, frame: 1});
- yield checkScroll(tab, {children: [{scroll: SCROLL_STR}, {scroll: SCROLL2_STR}]}, "scroll is fine");
-
- // Duplicate and check that the scroll position is restored.
- let tab2 = ss.duplicateTab(window, tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- let scroll = yield sendMessage(browser2, "ss-test:getScrollPosition", {frame: 0});
- is(JSON.stringify(scroll), JSON.stringify({x: SCROLL_X, y: SCROLL_Y}),
- "scroll position #1 has been duplicated correctly");
-
- scroll = yield sendMessage(browser2, "ss-test:getScrollPosition", {frame: 1});
- is(JSON.stringify(scroll), JSON.stringify({x: SCROLL2_X, y: SCROLL2_Y}),
- "scroll position #2 has been duplicated correctly");
-
- // Check that resetting one frame's scroll position removes it from the
- // serialized value.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0, frame: 0});
- yield checkScroll(tab, {children: [null, {scroll: SCROLL2_STR}]}, "scroll is fine");
-
- // Check the resetting all frames' scroll positions nulls the stored value.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0, frame: 1});
- yield checkScroll(tab, null, "no scroll stored");
-
- // Cleanup.
- yield promiseRemoveTab(tab);
- yield promiseRemoveTab(tab2);
-});
-
-/**
- * Test that scroll positions persist after restoring background tabs in
- * a restored window (bug 1228518).
- */
-add_task(function test_scroll_background_tabs() {
- pushPrefs(["browser.sessionstore.restore_on_demand", true]);
-
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
- let tab = newWin.gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield BrowserTestUtils.browserLoaded(browser);
-
- // Scroll down a little.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y});
- yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is fine");
-
- // Close the window
- yield BrowserTestUtils.closeWindow(newWin);
-
- // Now restore the window
- newWin = ss.undoCloseWindow(0);
-
- // Make sure to wait for the window to be restored.
- yield BrowserTestUtils.waitForEvent(newWin, "SSWindowStateReady");
-
- is(newWin.gBrowser.tabs.length, 2, "There should be two tabs");
-
- // The second tab should be the one we loaded URL at still
- tab = newWin.gBrowser.tabs[1];
- yield promiseTabRestoring(tab);
-
- ok(tab.hasAttribute("pending"), "Tab should be pending");
- browser = tab.linkedBrowser;
-
- // Ensure there are no pending queued messages in the child.
- yield TabStateFlusher.flush(browser);
-
- // Now check to see if the background tab remembers where it
- // should be scrolled to.
- newWin.gBrowser.selectedTab = tab;
- yield promiseTabRestored(tab);
-
- yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is still fine");
-
- yield BrowserTestUtils.closeWindow(newWin);
-});
diff --git a/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js b/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js
deleted file mode 100644
index 735a87634..000000000
--- a/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const BASE = "http://example.com/browser/browser/components/sessionstore/test/"
-const READER_MODE_URL = "about:reader?url=" +
- encodeURIComponent(BASE + "browser_scrollPositions_readerModeArticle.html");
-
-// Randomized set of scroll positions we will use in this test.
-const SCROLL_READER_MODE_Y = Math.round(400 * (1 + Math.random()));
-const SCROLL_READER_MODE_STR = "0," + SCROLL_READER_MODE_Y;
-
-requestLongerTimeout(2);
-
-/**
- * Test that scroll positions of about reader page after restoring background
- * tabs in a restored window (bug 1153393).
- */
-add_task(function test_scroll_background_about_reader_tabs() {
- pushPrefs(["browser.sessionstore.restore_on_demand", true]);
-
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
- let tab = newWin.gBrowser.addTab(READER_MODE_URL);
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.browserLoaded(browser),
- BrowserTestUtils.waitForContentEvent(browser, "AboutReaderContentReady")
- ]);
-
- // Scroll down a little.
- yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: SCROLL_READER_MODE_Y});
- yield checkScroll(tab, {scroll: SCROLL_READER_MODE_STR}, "scroll is fine");
-
- // Close the window
- yield BrowserTestUtils.closeWindow(newWin);
-
- // Now restore the window
- newWin = ss.undoCloseWindow(0);
-
- // Make sure to wait for the window to be restored.
- yield BrowserTestUtils.waitForEvent(newWin, "SSWindowStateReady");
-
- is(newWin.gBrowser.tabs.length, 2, "There should be two tabs");
-
- // The second tab should be the one we loaded URL at still
- tab = newWin.gBrowser.tabs[1];
- yield promiseTabRestoring(tab);
-
- ok(tab.hasAttribute("pending"), "Tab should be pending");
- browser = tab.linkedBrowser;
-
- // Ensure there are no pending queued messages in the child.
- yield TabStateFlusher.flush(browser);
-
- // Now check to see if the background tab remembers where it
- // should be scrolled to.
- newWin.gBrowser.selectedTab = tab;
- yield Promise.all([
- promiseTabRestored(tab),
- BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "AboutReaderContentReady")
- ]);
-
- yield checkScroll(tab, {scroll: SCROLL_READER_MODE_STR}, "scroll is still fine");
-
- yield BrowserTestUtils.closeWindow(newWin);
-});
diff --git a/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html b/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html
deleted file mode 100644
index 55452e043..000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Article title</title>
-<meta name="description" content="This is the article description." />
-</head>
-<body>
-<header>Site header</header>
-<div>
-<h1>Article title</h1>
-<h2 class="author">by Jane Doe</h2>
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-</div>
-</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_scrollPositions_sample.html b/browser/components/sessionstore/test/browser_scrollPositions_sample.html
deleted file mode 100644
index 0182783db..000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_scrollPositions_sample.html</title>
- </head>
- <body style='width: 100000px; height: 100000px;'>top</body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html b/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html
deleted file mode 100644
index c7e363fa1..000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_scrollPositions_sample_frameset.html</title>
- </head>
- <frameset id="frames" rows="50%, 50%">
- <frame src="browser_scrollPositions_sample.html">
- <frame src="browser_scrollPositions_sample.html">
- </frameset>
-</html>
diff --git a/browser/components/sessionstore/test/browser_send_async_message_oom.js b/browser/components/sessionstore/test/browser_send_async_message_oom.js
deleted file mode 100644
index 6afd771db..000000000
--- a/browser/components/sessionstore/test/browser_send_async_message_oom.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
-
-const HISTOGRAM_NAME = "FX_SESSION_RESTORE_SEND_UPDATE_CAUSED_OOM";
-
-/**
- * Test that an OOM in sendAsyncMessage in a framescript will be reported
- * to Telemetry.
- */
-
-add_task(function* init() {
- Services.telemetry.canRecordExtended = true;
-});
-
-function frameScript() {
- // Make send[A]syncMessage("SessionStore:update", ...) simulate OOM.
- // Other operations are unaffected.
- let mm = docShell.sameTypeRootTreeItem.
- QueryInterface(Ci.nsIDocShell).
- QueryInterface(Ci.nsIInterfaceRequestor).
- getInterface(Ci.nsIContentFrameMessageManager);
-
- let wrap = function(original) {
- return function(name, ...args) {
- if (name != "SessionStore:update") {
- return original(name, ...args);
- }
- throw new Components.Exception("Simulated OOM", Cr.NS_ERROR_OUT_OF_MEMORY);
- }
- }
-
- mm.sendAsyncMessage = wrap(mm.sendAsyncMessage);
- mm.sendSyncMessage = wrap(mm.sendSyncMessage);
-}
-
-add_task(function*() {
- // Capture original state.
- let snapshot = Services.telemetry.getHistogramById(HISTOGRAM_NAME).snapshot();
-
- // Open a browser, configure it to cause OOM.
- let newTab = gBrowser.addTab("about:robots");
- let browser = newTab.linkedBrowser;
- yield ContentTask.spawn(browser, null, frameScript);
-
-
- let promiseReported = new Promise(resolve => {
- browser.messageManager.addMessageListener("SessionStore:error", resolve);
- });
-
- // Attempt to flush. This should fail.
- let promiseFlushed = TabStateFlusher.flush(browser);
- promiseFlushed.then((success) => {
- if (success) {
- throw new Error("Flush should have failed")
- }
- });
-
- // The frame script should report an error.
- yield promiseReported;
-
- // Give us some time to handle that error.
- yield new Promise(resolve => setTimeout(resolve, 10));
-
- // By now, Telemetry should have been updated.
- let snapshot2 = Services.telemetry.getHistogramById(HISTOGRAM_NAME).snapshot();
- gBrowser.removeTab(newTab);
-
- Assert.ok(snapshot2.sum > snapshot.sum);
-});
-
-add_task(function* cleanup() {
- Services.telemetry.canRecordExtended = false;
-});
diff --git a/browser/components/sessionstore/test/browser_sessionHistory.js b/browser/components/sessionstore/test/browser_sessionHistory.js
deleted file mode 100644
index f4523e06a..000000000
--- a/browser/components/sessionstore/test/browser_sessionHistory.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-requestLongerTimeout(2);
-
-/**
- * Ensure that starting a load invalidates shistory.
- */
-add_task(function test_load_start() {
- // Create a new tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Load a new URI.
- yield BrowserTestUtils.loadURI(browser, "about:mozilla");
-
- // Remove the tab before it has finished loading.
- yield promiseContentMessage(browser, "ss-test:OnHistoryReplaceEntry");
- yield promiseRemoveTab(tab);
-
- // Undo close the tab.
- tab = ss.undoCloseTab(window, 0);
- browser = tab.linkedBrowser;
- yield promiseTabRestored(tab);
-
- // Check that the correct URL was restored.
- is(browser.currentURI.spec, "about:mozilla", "url is correct");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that anchor navigation invalidates shistory.
- */
-add_task(function test_hashchange() {
- const URL = "data:text/html;charset=utf-8,<a id=a href=%23>clickme</a>";
-
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Check that we start with a single shistory entry.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is one shistory entry");
-
- // Click the link and wait for a hashchange event.
- browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a"});
- yield promiseContentMessage(browser, "ss-test:hashchange");
-
- // Check that we now have two shistory entries.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there are two shistory entries");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that loading pages from the bfcache invalidates shistory.
- */
-add_task(function test_pageshow() {
- const URL = "data:text/html;charset=utf-8,<h1>first</h1>";
- const URL2 = "data:text/html;charset=utf-8,<h1>second</h1>";
-
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Create a second shistory entry.
- browser.loadURI(URL2);
- yield promiseBrowserLoaded(browser);
-
- // Go back to the previous url which is loaded from the bfcache.
- browser.goBack();
- yield promiseContentMessage(browser, "ss-test:onFrameTreeCollected");
- is(browser.currentURI.spec, URL, "correct url after going back");
-
- // Check that loading from bfcache did invalidate shistory.
- yield TabStateFlusher.flush(browser);
- let {index} = JSON.parse(ss.getTabState(tab));
- is(index, 1, "first history entry is selected");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that subframe navigation invalidates shistory.
- */
-add_task(function test_subframes() {
- const URL = "data:text/html;charset=utf-8," +
- "<iframe src=http%3A//example.com/ name=t></iframe>" +
- "<a id=a1 href=http%3A//example.com/1 target=t>clickme</a>" +
- "<a id=a2 href=http%3A//example.com/%23 target=t>clickme</a>";
-
- // Create a new tab.
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Check that we have a single shistory entry.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is one shistory entry");
- is(entries[0].children.length, 1, "the entry has one child");
-
- // Navigate the subframe.
- browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a1"});
- yield promiseBrowserLoaded(browser, false /* don't ignore subframes */);
-
- // Check shistory.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there now are two shistory entries");
- is(entries[1].children.length, 1, "the second entry has one child");
-
- // Go back in history.
- browser.goBack();
- yield promiseBrowserLoaded(browser, false /* don't ignore subframes */);
-
- // Navigate the subframe again.
- browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a2"});
- yield promiseContentMessage(browser, "ss-test:hashchange");
-
- // Check shistory.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there now are two shistory entries");
- is(entries[1].children.length, 1, "the second entry has one child");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that navigating from an about page invalidates shistory.
- */
-add_task(function test_about_page_navigate() {
- // Create a new tab.
- let tab = gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Check that we have a single shistory entry.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is one shistory entry");
- is(entries[0].url, "about:blank", "url is correct");
-
- browser.loadURI("about:robots");
- yield promiseBrowserLoaded(browser);
-
- // Check that we have changed the history entry.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 1, "there is one shistory entry");
- is(entries[0].url, "about:robots", "url is correct");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that history.pushState and history.replaceState invalidate shistory.
- */
-add_task(function test_pushstate_replacestate() {
- // Create a new tab.
- let tab = gBrowser.addTab("http://example.com/1");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Check that we have a single shistory entry.
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
- is(entries.length, 1, "there is one shistory entry");
- is(entries[0].url, "http://example.com/1", "url is correct");
-
- yield ContentTask.spawn(browser, {}, function* () {
- content.window.history.pushState({}, "", 'test-entry/');
- });
-
- // Check that we have added the history entry.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there is another shistory entry");
- is(entries[1].url, "http://example.com/test-entry/", "url is correct");
-
- yield ContentTask.spawn(browser, {}, function* () {
- content.window.history.replaceState({}, "", "test-entry2/");
- });
-
- // Check that we have modified the history entry.
- yield TabStateFlusher.flush(browser);
- ({entries} = JSON.parse(ss.getTabState(tab)));
- is(entries.length, 2, "there is still two shistory entries");
- is(entries[1].url, "http://example.com/test-entry/test-entry2/", "url is correct");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that slow loading subframes will invalidate shistory.
- */
-add_task(function test_slow_subframe_load() {
- const SLOW_URL = "http://mochi.test:8888/browser/browser/components/" +
- "sessionstore/test/browser_sessionHistory_slow.sjs";
-
- const URL = "data:text/html;charset=utf-8," +
- "<frameset cols=50%25,50%25>" +
- "<frame src='" + SLOW_URL + "'>" +
- "</frameset>";
-
- // Add a new tab with a slow loading subframe
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- yield TabStateFlusher.flush(browser);
- let {entries} = JSON.parse(ss.getTabState(tab));
-
- // Check the number of children.
- is(entries.length, 1, "there is one root entry ...");
- is(entries[0].children.length, 1, "... with one child entries");
-
- // Check URLs.
- ok(entries[0].url.startsWith("data:text/html"), "correct root url");
- is(entries[0].children[0].url, SLOW_URL, "correct url for subframe");
-
- // Cleanup.
- gBrowser.removeTab(tab);
-});
diff --git a/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs b/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs
deleted file mode 100644
index 41da3c2ad..000000000
--- a/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-const DELAY_MS = "2000";
-
-let timer;
-
-function handleRequest(req, resp) {
- resp.processAsync();
- resp.setHeader("Cache-Control", "no-cache", false);
- resp.setHeader("Content-Type", "text/html;charset=utf-8", false);
-
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.init(() => {
- resp.write("hi");
- resp.finish();
- }, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
-}
diff --git a/browser/components/sessionstore/test/browser_sessionStorage.html b/browser/components/sessionstore/test/browser_sessionStorage.html
deleted file mode 100644
index 7e2dccf4a..000000000
--- a/browser/components/sessionstore/test/browser_sessionStorage.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8">
- <title>browser_sessionStorage.html</title>
- </head>
- <body>
- <script type="text/javascript;version=1.8">
- let isOuter = window == window.top;
- let args = window.location.search.slice(1).split("&");
- let rand = args[0];
-
- if (isOuter) {
- let iframe = document.createElement("iframe");
- let isSecure = args.indexOf("secure") > -1;
- let scheme = isSecure ? "https" : "http";
- iframe.setAttribute("src", scheme + "://example.com" + location.pathname + "?" + rand);
- document.body.appendChild(iframe);
- }
-
- if (sessionStorage.length === 0) {
- sessionStorage.test = (isOuter ? "outer" : "inner") + "-value-" + rand;
- document.title = sessionStorage.test;
- }
- </script>
- </body>
-</html>
diff --git a/browser/components/sessionstore/test/browser_sessionStorage.js b/browser/components/sessionstore/test/browser_sessionStorage.js
deleted file mode 100644
index b580c5cc2..000000000
--- a/browser/components/sessionstore/test/browser_sessionStorage.js
+++ /dev/null
@@ -1,188 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const RAND = Math.random();
-const URL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_sessionStorage.html" +
- "?" + RAND;
-
-const OUTER_VALUE = "outer-value-" + RAND;
-const INNER_VALUE = "inner-value-" + RAND;
-
-/**
- * This test ensures that setting, modifying and restoring sessionStorage data
- * works as expected.
- */
-add_task(function session_storage() {
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
-
- let {storage} = JSON.parse(ss.getTabState(tab));
- is(storage["http://example.com"].test, INNER_VALUE,
- "sessionStorage data for example.com has been serialized correctly");
- is(storage["http://mochi.test:8888"].test, OUTER_VALUE,
- "sessionStorage data for mochi.test has been serialized correctly");
-
- // Ensure that modifying sessionStore values works for the inner frame only.
- yield modifySessionStorage(browser, {test: "modified1"}, {frameIndex: 0});
- yield TabStateFlusher.flush(browser);
-
- ({storage} = JSON.parse(ss.getTabState(tab)));
- is(storage["http://example.com"].test, "modified1",
- "sessionStorage data for example.com has been serialized correctly");
- is(storage["http://mochi.test:8888"].test, OUTER_VALUE,
- "sessionStorage data for mochi.test has been serialized correctly");
-
- // Ensure that modifying sessionStore values works for both frames.
- yield modifySessionStorage(browser, {test: "modified"});
- yield modifySessionStorage(browser, {test: "modified2"}, {frameIndex: 0});
- yield TabStateFlusher.flush(browser);
-
- ({storage} = JSON.parse(ss.getTabState(tab)));
- is(storage["http://example.com"].test, "modified2",
- "sessionStorage data for example.com has been serialized correctly");
- is(storage["http://mochi.test:8888"].test, "modified",
- "sessionStorage data for mochi.test has been serialized correctly");
-
- // Test that duplicating a tab works.
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2);
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser2);
-
- ({storage} = JSON.parse(ss.getTabState(tab2)));
- is(storage["http://example.com"].test, "modified2",
- "sessionStorage data for example.com has been duplicated correctly");
- is(storage["http://mochi.test:8888"].test, "modified",
- "sessionStorage data for mochi.test has been duplicated correctly");
-
- // Ensure that the content script retains restored data
- // (by e.g. duplicateTab) and sends it along with new data.
- yield modifySessionStorage(browser2, {test: "modified3"});
- yield TabStateFlusher.flush(browser2);
-
- ({storage} = JSON.parse(ss.getTabState(tab2)));
- is(storage["http://example.com"].test, "modified2",
- "sessionStorage data for example.com has been duplicated correctly");
- is(storage["http://mochi.test:8888"].test, "modified3",
- "sessionStorage data for mochi.test has been duplicated correctly");
-
- // Check that loading a new URL discards data.
- browser2.loadURI("http://mochi.test:8888/");
- yield promiseBrowserLoaded(browser2);
- yield TabStateFlusher.flush(browser2);
-
- ({storage} = JSON.parse(ss.getTabState(tab2)));
- is(storage["http://mochi.test:8888"].test, "modified3",
- "navigating retains correct storage data");
- ok(!storage["http://example.com"], "storage data was discarded");
-
- // Check that loading a new URL discards data.
- browser2.loadURI("about:mozilla");
- yield promiseBrowserLoaded(browser2);
- yield TabStateFlusher.flush(browser2);
-
- let state = JSON.parse(ss.getTabState(tab2));
- ok(!state.hasOwnProperty("storage"), "storage data was discarded");
-
- // Clean up.
- yield promiseRemoveTab(tab);
- yield promiseRemoveTab(tab2);
-});
-
-/**
- * This test ensures that purging domain data also purges data from the
- * sessionStorage data collected for tabs.
- */
-add_task(function purge_domain() {
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Purge data for "mochi.test".
- yield purgeDomainData(browser, "mochi.test");
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
-
- let {storage} = JSON.parse(ss.getTabState(tab));
- ok(!storage["http://mochi.test:8888"],
- "sessionStorage data for mochi.test has been purged");
- is(storage["http://example.com"].test, INNER_VALUE,
- "sessionStorage data for example.com has been preserved");
-
- yield promiseRemoveTab(tab);
-});
-
-/**
- * This test ensures that collecting sessionStorage data respects the privacy
- * levels as set by the user.
- */
-add_task(function respect_privacy_level() {
- let tab = gBrowser.addTab(URL + "&secure");
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield promiseRemoveTab(tab);
-
- let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://mochi.test:8888"].test, OUTER_VALUE,
- "http sessionStorage data has been saved");
- is(storage["https://example.com"].test, INNER_VALUE,
- "https sessionStorage data has been saved");
-
- // Disable saving data for encrypted sites.
- Services.prefs.setIntPref("browser.sessionstore.privacy_level", 1);
-
- tab = gBrowser.addTab(URL + "&secure");
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield promiseRemoveTab(tab);
-
- [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://mochi.test:8888"].test, OUTER_VALUE,
- "http sessionStorage data has been saved");
- ok(!storage["https://example.com"],
- "https sessionStorage data has *not* been saved");
-
- // Disable saving data for any site.
- Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2);
-
- // Check that duplicating a tab copies all private data.
- tab = gBrowser.addTab(URL + "&secure");
- yield promiseBrowserLoaded(tab.linkedBrowser);
- let tab2 = gBrowser.duplicateTab(tab);
- yield promiseTabRestored(tab2);
- yield promiseRemoveTab(tab);
-
- // With privacy_level=2 the |tab| shouldn't have any sessionStorage data.
- [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- ok(!storage, "sessionStorage data has *not* been saved");
-
- // Remove all closed tabs before continuing with the next test.
- // As Date.now() isn't monotonic we might sometimes check
- // the wrong closedTabData entry.
- while (ss.getClosedTabCount(window) > 0) {
- ss.forgetClosedTab(window, 0);
- }
-
- // Restore the default privacy level and close the duplicated tab.
- Services.prefs.clearUserPref("browser.sessionstore.privacy_level");
- yield promiseRemoveTab(tab2);
-
- // With privacy_level=0 the duplicated |tab2| should persist all data.
- [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window));
- is(storage["http://mochi.test:8888"].test, OUTER_VALUE,
- "http sessionStorage data has been saved");
- is(storage["https://example.com"].test, INNER_VALUE,
- "https sessionStorage data has been saved");
-});
-
-function purgeDomainData(browser, domain) {
- return sendMessage(browser, "ss-test:purgeDomainData", domain);
-}
diff --git a/browser/components/sessionstore/test/browser_sessionStorage_size.js b/browser/components/sessionstore/test/browser_sessionStorage_size.js
deleted file mode 100644
index d1d894611..000000000
--- a/browser/components/sessionstore/test/browser_sessionStorage_size.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const RAND = Math.random();
-const URL = "http://mochi.test:8888/browser/" +
- "browser/components/sessionstore/test/browser_sessionStorage.html" +
- "?" + RAND;
-
-const OUTER_VALUE = "outer-value-" + RAND;
-
-// Test that we record the size of messages.
-add_task(function* test_telemetry() {
- Services.telemetry.canRecordExtended = true;
- let histogram = Services.telemetry.getHistogramById("FX_SESSION_RESTORE_DOM_STORAGE_SIZE_ESTIMATE_CHARS");
- let snap1 = histogram.snapshot();
-
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
- let snap2 = histogram.snapshot();
-
- Assert.ok(snap2.counts[5] > snap1.counts[5]);
- yield promiseRemoveTab(tab);
- Services.telemetry.canRecordExtended = false;
-});
-
-// Lower the size limit for DOM Storage content. Check that DOM Storage
-// is not updated, but that other things remain updated.
-add_task(function* test_large_content() {
- Services.prefs.setIntPref("browser.sessionstore.dom_storage_limit", 5);
-
- let tab = gBrowser.addTab(URL);
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
-
- // Flush to make sure chrome received all data.
- yield TabStateFlusher.flush(browser);
-
- let state = JSON.parse(ss.getTabState(tab));
- info(JSON.stringify(state, null, "\t"));
- Assert.equal(state.storage, null, "We have no storage for the tab");
- Assert.equal(state.entries[0].title, OUTER_VALUE);
- yield promiseRemoveTab(tab);
-
- Services.prefs.clearUserPref("browser.sessionstore.dom_storage_limit");
-});
diff --git a/browser/components/sessionstore/test/browser_sessionStoreContainer.js b/browser/components/sessionstore/test/browser_sessionStoreContainer.js
deleted file mode 100644
index 1bc9537e2..000000000
--- a/browser/components/sessionstore/test/browser_sessionStoreContainer.js
+++ /dev/null
@@ -1,141 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-add_task(function* () {
- for (let i = 0; i < 3; ++i) {
- let tab = gBrowser.addTab("http://example.com/", { userContextId: i });
- let browser = tab.linkedBrowser;
-
- yield promiseBrowserLoaded(browser);
-
- let tab2 = gBrowser.duplicateTab(tab);
- Assert.equal(tab2.getAttribute("usercontextid"), i);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2)
-
- yield ContentTask.spawn(browser2, { expectedId: i }, function* (args) {
- let loadContext = docShell.QueryInterface(Ci.nsILoadContext);
- Assert.equal(loadContext.originAttributes.userContextId,
- args.expectedId, "The docShell has the correct userContextId");
- });
-
- yield promiseRemoveTab(tab);
- yield promiseRemoveTab(tab2);
- }
-});
-
-add_task(function* () {
- let tab = gBrowser.addTab("http://example.com/", { userContextId: 1 });
- let browser = tab.linkedBrowser;
-
- yield promiseBrowserLoaded(browser);
-
- gBrowser.selectedTab = tab;
-
- let tab2 = gBrowser.duplicateTab(tab);
- let browser2 = tab2.linkedBrowser;
- yield promiseTabRestored(tab2)
-
- yield ContentTask.spawn(browser2, { expectedId: 1 }, function* (args) {
- Assert.equal(docShell.getOriginAttributes().userContextId,
- args.expectedId,
- "The docShell has the correct userContextId");
- });
-
- yield promiseRemoveTab(tab);
- yield promiseRemoveTab(tab2);
-});
-
-add_task(function* () {
- let tab = gBrowser.addTab("http://example.com/", { userContextId: 1 });
- let browser = tab.linkedBrowser;
-
- yield promiseBrowserLoaded(browser);
-
- gBrowser.removeTab(tab);
-
- let tab2 = ss.undoCloseTab(window, 0);
- Assert.equal(tab2.getAttribute("usercontextid"), 1);
- yield promiseTabRestored(tab2);
- yield ContentTask.spawn(tab2.linkedBrowser, { expectedId: 1 }, function* (args) {
- Assert.equal(docShell.getOriginAttributes().userContextId,
- args.expectedId,
- "The docShell has the correct userContextId");
- });
-
- yield promiseRemoveTab(tab2);
-});
-
-// Opens "uri" in a new tab with the provided userContextId and focuses it.
-// Returns the newly opened tab.
-function* openTabInUserContext(userContextId) {
- // Open the tab in the correct userContextId.
- let tab = gBrowser.addTab("http://example.com", { userContextId });
-
- // Select tab and make sure its browser is focused.
- gBrowser.selectedTab = tab;
- tab.ownerGlobal.focus();
-
- let browser = gBrowser.getBrowserForTab(tab);
- yield BrowserTestUtils.browserLoaded(browser);
- return { tab, browser };
-}
-
-function waitForNewCookie() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(subj, topic, data) {
- let cookie = subj.QueryInterface(Ci.nsICookie2);
- if (data == "added") {
- Services.obs.removeObserver(observer, topic);
- resolve();
- }
- }, "cookie-changed", false);
- });
-}
-
-add_task(function* test() {
- const USER_CONTEXTS = [
- "default",
- "personal",
- "work",
- ];
-
- const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
- const { TabStateFlusher } = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
- // Make sure userContext is enabled.
- yield SpecialPowers.pushPrefEnv({
- "set": [ [ "privacy.userContext.enabled", true ] ]
- });
-
- let lastSessionRestore;
- for (let userContextId of Object.keys(USER_CONTEXTS)) {
- // Load the page in 3 different contexts and set a cookie
- // which should only be visible in that context.
- let cookie = USER_CONTEXTS[userContextId];
-
- // Open our tab in the given user context.
- let { tab, browser } = yield* openTabInUserContext(userContextId);
-
- yield Promise.all([
- waitForNewCookie(),
- ContentTask.spawn(browser, cookie, cookie => content.document.cookie = cookie)
- ]);
-
- // Ensure the tab's session history is up-to-date.
- yield TabStateFlusher.flush(browser);
-
- lastSessionRestore = ss.getWindowState(window);
-
- // Remove the tab.
- gBrowser.removeTab(tab);
- }
-
- let state = JSON.parse(lastSessionRestore);
- is(state.windows[0].cookies.length, USER_CONTEXTS.length,
- "session restore should have each container's cookie");
-});
-
diff --git a/browser/components/sessionstore/test/browser_swapDocShells.js b/browser/components/sessionstore/test/browser_swapDocShells.js
deleted file mode 100644
index 839f060e7..000000000
--- a/browser/components/sessionstore/test/browser_swapDocShells.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-add_task(function* () {
- let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla");
- yield promiseBrowserLoaded(gBrowser.selectedBrowser);
-
- let win = gBrowser.replaceTabWithWindow(tab);
- yield promiseDelayedStartupFinished(win);
- yield promiseBrowserHasURL(win.gBrowser.browsers[0], "about:mozilla");
-
- win.duplicateTabIn(win.gBrowser.selectedTab, "tab");
- yield promiseTabRestored(win.gBrowser.tabs[1]);
-
- let browser = win.gBrowser.browsers[1];
- is(browser.currentURI.spec, "about:mozilla", "tab was duplicated");
-
- yield BrowserTestUtils.closeWindow(win);
-});
-
-function promiseDelayedStartupFinished(win) {
- let deferred = Promise.defer();
- whenDelayedStartupFinished(win, deferred.resolve);
- return deferred.promise;
-}
-
-function promiseBrowserHasURL(browser, url) {
- let promise = Promise.resolve();
-
- if (browser.contentDocument.readyState === "complete" &&
- browser.currentURI.spec === url) {
- return promise;
- }
-
- return promise.then(() => promiseBrowserHasURL(browser, url));
-}
diff --git a/browser/components/sessionstore/test/browser_switch_remoteness.js b/browser/components/sessionstore/test/browser_switch_remoteness.js
deleted file mode 100644
index 9eb8c260a..000000000
--- a/browser/components/sessionstore/test/browser_switch_remoteness.js
+++ /dev/null
@@ -1,49 +0,0 @@
-"use strict";
-
-const URL = "http://example.com/browser_switch_remoteness_";
-
-function countHistoryEntries(browser, expected) {
- return ContentTask.spawn(browser, { expected }, function* (args) {
- let Ci = Components.interfaces;
- let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation);
- let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal);
- Assert.equal(history && history.count, args.expected,
- "correct number of shistory entries");
- });
-}
-
-add_task(function* () {
- // Open a new window.
- let win = yield promiseNewWindowLoaded();
-
- // Add a new tab.
- let tab = win.gBrowser.addTab("about:blank");
- let browser = tab.linkedBrowser;
- yield promiseBrowserLoaded(browser);
- ok(browser.isRemoteBrowser, "browser is remote");
-
- // Get the maximum number of preceding entries to save.
- const MAX_BACK = Services.prefs.getIntPref("browser.sessionstore.max_serialize_back");
- ok(MAX_BACK > -1, "check that the default has a value that caps data");
-
- // Load more pages than we would save to disk on a clean shutdown.
- for (let i = 0; i < MAX_BACK + 2; i++) {
- browser.loadURI(URL + i);
- yield promiseBrowserLoaded(browser);
- ok(browser.isRemoteBrowser, "browser is still remote");
- }
-
- // Check we have the right number of shistory entries.
- yield countHistoryEntries(browser, MAX_BACK + 2);
-
- // Load a non-remote page.
- browser.loadURI("about:robots");
- yield promiseTabRestored(tab);
- ok(!browser.isRemoteBrowser, "browser is not remote anymore");
-
- // Check that we didn't lose any shistory entries.
- yield countHistoryEntries(browser, MAX_BACK + 3);
-
- // Cleanup.
- yield BrowserTestUtils.closeWindow(win);
-});
diff --git a/browser/components/sessionstore/test/browser_undoCloseById.js b/browser/components/sessionstore/test/browser_undoCloseById.js
deleted file mode 100644
index f2f0f919c..000000000
--- a/browser/components/sessionstore/test/browser_undoCloseById.js
+++ /dev/null
@@ -1,118 +0,0 @@
-"use strict";
-
-/**
- * This test is for the undoCloseById function.
- */
-
-Cu.import("resource:///modules/sessionstore/SessionStore.jsm");
-
-function openAndCloseTab(window, url) {
- let tab = window.gBrowser.addTab(url);
- yield promiseBrowserLoaded(tab.linkedBrowser, true, url);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- yield promiseRemoveTab(tab);
-}
-
-function* openWindow(url) {
- let win = yield promiseNewWindowLoaded();
- let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY;
- win.gBrowser.selectedBrowser.loadURIWithFlags(url, flags);
- yield promiseBrowserLoaded(win.gBrowser.selectedBrowser, true, url);
- return win;
-}
-
-function closeWindow(win) {
- yield BrowserTestUtils.closeWindow(win);
- // Wait 20 ms to allow SessionStorage a chance to register the closed window.
- yield new Promise(resolve => setTimeout(resolve, 20));
-}
-
-add_task(function* test_undoCloseById() {
- // Clear the lists of closed windows and tabs.
- forgetClosedWindows();
- while (SessionStore.getClosedTabCount(window)) {
- SessionStore.forgetClosedTab(window, 0);
- }
-
- // Open a new window.
- let win = yield openWindow("about:robots");
-
- // Open and close a tab.
- yield openAndCloseTab(win, "about:mozilla");
- is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab");
-
- // Record the first closedId created.
- let initialClosedId = SessionStore.getClosedTabData(win, false)[0].closedId;
-
- // Open and close another window.
- let win2 = yield openWindow("about:mozilla");
- yield closeWindow(win2); // closedId == initialClosedId + 1
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
-
- // Open and close another tab in the first window.
- yield openAndCloseTab(win, "about:robots"); // closedId == initialClosedId + 2
- is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab");
-
- // Undo closing the second tab.
- let tab = SessionStore.undoCloseById(initialClosedId + 2);
- yield promiseBrowserLoaded(tab.linkedBrowser);
- is(tab.linkedBrowser.currentURI.spec, "about:robots", "The expected tab was re-opened");
-
- let notTab = SessionStore.undoCloseById(initialClosedId + 2);
- is(notTab, undefined, "Re-opened tab cannot be unClosed again by closedId");
-
- // Now the last closed object should be a window again.
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
-
- // Undo closing the first tab.
- let tab2 = SessionStore.undoCloseById(initialClosedId);
- yield promiseBrowserLoaded(tab2.linkedBrowser);
- is(tab2.linkedBrowser.currentURI.spec, "about:mozilla", "The expected tab was re-opened");
-
- // Close the two tabs we re-opened.
- yield promiseRemoveTab(tab); // closedId == initialClosedId + 3
- is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab");
- yield promiseRemoveTab(tab2); // closedId == initialClosedId + 4
- is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab");
-
- // Open another new window.
- let win3 = yield openWindow("about:mozilla");
-
- // Close both windows.
- yield closeWindow(win); // closedId == initialClosedId + 5
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
- yield closeWindow(win3); // closedId == initialClosedId + 6
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
-
- // Undo closing the second window.
- win = SessionStore.undoCloseById(initialClosedId + 6);
- yield BrowserTestUtils.waitForEvent(win, "load");
-
- // Make sure we wait until this window is restored.
- yield BrowserTestUtils.waitForEvent(win.gBrowser.tabContainer,
- "SSTabRestored");
-
- is(win.gBrowser.selectedBrowser.currentURI.spec, "about:mozilla", "The expected window was re-opened");
-
- let notWin = SessionStore.undoCloseById(initialClosedId + 6);
- is(notWin, undefined, "Re-opened window cannot be unClosed again by closedId");
-
- // Close the window again.
- yield closeWindow(win);
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
-
- // Undo closing the first window.
- win = SessionStore.undoCloseById(initialClosedId + 5);
-
- yield BrowserTestUtils.waitForEvent(win, "load");
-
- // Make sure we wait until this window is restored.
- yield BrowserTestUtils.waitForEvent(win.gBrowser.tabContainer,
- "SSTabRestored");
-
- is(win.gBrowser.selectedBrowser.currentURI.spec, "about:robots", "The expected window was re-opened");
-
- // Close the window again.
- yield closeWindow(win);
- is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window");
-});
diff --git a/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js b/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js
deleted file mode 100644
index e46348e59..000000000
--- a/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Tests that if we have tabs that are still in the "click to
- * restore" state, that if their browsers crash, that we don't
- * show the crashed state for those tabs (since selecting them
- * should restore them anyway).
- */
-
-const PREF = "browser.sessionstore.restore_on_demand";
-const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page.";
-
-add_task(function* test() {
- yield pushPrefs([PREF, true]);
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: PAGE,
- }, function*(browser) {
- yield TabStateFlusher.flush(browser);
-
- // We'll create a second "pending" tab. This is the one we'll
- // ensure doesn't go to about:tabcrashed. We start it non-remote
- // since this is how SessionStore creates all browsers before
- // they are restored.
- let unrestoredTab = gBrowser.addTab("about:blank", {
- skipAnimation: true,
- forceNotRemote: true,
- });
-
- let state = {
- entries: [{url: PAGE}],
- };
-
- ss.setTabState(unrestoredTab, JSON.stringify(state));
-
- ok(!unrestoredTab.hasAttribute("crashed"), "tab is not crashed");
- ok(unrestoredTab.hasAttribute("pending"), "tab is pending");
-
- // Now crash the selected browser.
- yield BrowserTestUtils.crashBrowser(browser);
-
- ok(!unrestoredTab.hasAttribute("crashed"), "tab is still not crashed");
- ok(unrestoredTab.hasAttribute("pending"), "tab is still pending");
-
- // Selecting the tab should now restore it.
- gBrowser.selectedTab = unrestoredTab;
- yield promiseTabRestored(unrestoredTab);
-
- ok(!unrestoredTab.hasAttribute("crashed"), "tab is still not crashed");
- ok(!unrestoredTab.hasAttribute("pending"), "tab is no longer pending");
-
- // The original tab should still be crashed
- let originalTab = gBrowser.getTabForBrowser(browser);
- ok(originalTab.hasAttribute("crashed"), "original tab is crashed");
- ok(!originalTab.isRemoteBrowser, "Should not be remote");
-
- // We'd better be able to restore it still.
- gBrowser.selectedTab = originalTab;
- SessionStore.reviveCrashedTab(originalTab);
- yield promiseTabRestored(originalTab);
-
- // Clean up.
- yield BrowserTestUtils.removeTab(unrestoredTab);
- });
-});
diff --git a/browser/components/sessionstore/test/browser_upgrade_backup.js b/browser/components/sessionstore/test/browser_upgrade_backup.js
deleted file mode 100644
index 768671051..000000000
--- a/browser/components/sessionstore/test/browser_upgrade_backup.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/Preferences.jsm", this);
-
-const Paths = SessionFile.Paths;
-const PREF_UPGRADE = "browser.sessionstore.upgradeBackup.latestBuildID";
-const PREF_MAX_UPGRADE_BACKUPS = "browser.sessionstore.upgradeBackup.maxUpgradeBackups";
-
-/**
- * Prepares tests by retrieving the current platform's build ID, clearing the
- * build where the last backup was created and creating arbitrary JSON data
- * for a new backup.
- */
-var prepareTest = Task.async(function* () {
- let result = {};
-
- result.buildID = Services.appinfo.platformBuildID;
- Services.prefs.setCharPref(PREF_UPGRADE, "");
- result.contents = JSON.stringify({"browser_upgrade_backup.js": Math.random()});
-
- return result;
-});
-
-/**
- * Retrieves all upgrade backups and returns them in an array.
- */
-var getUpgradeBackups = Task.async(function* () {
- let iterator;
- let backups = [];
- let upgradeBackupPrefix = Paths.upgradeBackupPrefix;
-
- try {
- iterator = new OS.File.DirectoryIterator(Paths.backups);
-
- // iterate over all files in the backup directory
- yield iterator.forEach(function (file) {
- // check the upgradeBackupPrefix
- if (file.path.startsWith(Paths.upgradeBackupPrefix)) {
- // the file is a backup
- backups.push(file.path);
- }
- }, this);
- } finally {
- if (iterator) {
- iterator.close();
- }
- }
-
- // return results
- return backups;
-});
-
-add_task(function* init() {
- // Wait until initialization is complete
- yield SessionStore.promiseInitialized;
- yield SessionFile.wipe();
-});
-
-add_task(function* test_upgrade_backup() {
- let test = yield prepareTest();
- info("Let's check if we create an upgrade backup");
- yield OS.File.writeAtomic(Paths.clean, test.contents);
- yield SessionFile.read(); // First call to read() initializes the SessionWorker
- yield SessionFile.write(""); // First call to write() triggers the backup
-
- is(Services.prefs.getCharPref(PREF_UPGRADE), test.buildID, "upgrade backup should be set");
-
- is((yield OS.File.exists(Paths.upgradeBackup)), true, "upgrade backup file has been created");
-
- let data = yield OS.File.read(Paths.upgradeBackup);
- is(test.contents, (new TextDecoder()).decode(data), "upgrade backup contains the expected contents");
-
- info("Let's check that we don't overwrite this upgrade backup");
- let newContents = JSON.stringify({"something else entirely": Math.random()});
- yield OS.File.writeAtomic(Paths.clean, newContents);
- yield SessionFile.read(); // Reinitialize the SessionWorker
- yield SessionFile.write(""); // Next call to write() shouldn't trigger the backup
- data = yield OS.File.read(Paths.upgradeBackup);
- is(test.contents, (new TextDecoder()).decode(data), "upgrade backup hasn't changed");
-});
-
-add_task(function* test_upgrade_backup_removal() {
- let test = yield prepareTest();
- let maxUpgradeBackups = Preferences.get(PREF_MAX_UPGRADE_BACKUPS, 3);
- info("Let's see if we remove backups if there are too many");
- yield OS.File.writeAtomic(Paths.clean, test.contents);
-
- // if the nextUpgradeBackup already exists (from another test), remove it
- if (OS.File.exists(Paths.nextUpgradeBackup)) {
- yield OS.File.remove(Paths.nextUpgradeBackup);
- }
-
- // create dummy backups
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20080101010101", "");
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20090101010101", "");
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20100101010101", "");
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20110101010101", "");
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20120101010101", "");
- yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20130101010101", "");
-
- // get currently existing backups
- let backups = yield getUpgradeBackups();
-
- // trigger new backup
- yield SessionFile.read(); // First call to read() initializes the SessionWorker
- yield SessionFile.write(""); // First call to write() triggers the backup and the cleanup
-
- // a new backup should have been created (and still exist)
- is(Services.prefs.getCharPref(PREF_UPGRADE), test.buildID, "upgrade backup should be set");
- is((yield OS.File.exists(Paths.upgradeBackup)), true, "upgrade backup file has been created");
-
- // get currently existing backups and check their count
- let newBackups = yield getUpgradeBackups();
- is(newBackups.length, maxUpgradeBackups, "expected number of backups are present after removing old backups");
-
- // find all backups that were created during the last call to `SessionFile.write("");`
- // ie, filter out all the backups that have already been present before the call
- newBackups = newBackups.filter(function (backup) {
- return backups.indexOf(backup) < 0;
- });
-
- // check that exactly one new backup was created
- is(newBackups.length, 1, "one new backup was created that was not removed");
-
- yield SessionFile.write(""); // Second call to write() should not trigger anything
-
- backups = yield getUpgradeBackups();
- is(backups.length, maxUpgradeBackups, "second call to SessionFile.write() didn't create or remove more backups");
-});
-
diff --git a/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js b/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js
deleted file mode 100644
index 781692909..000000000
--- a/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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/. */
-
-// This test checks that closed private windows can't be restored
-
-function test() {
- waitForExplicitFinish();
-
- // Purging the list of closed windows
- forgetClosedWindows();
-
- // Load a private window, then close it
- // and verify it doesn't get remembered for restoring
- whenNewWindowLoaded({private: true}, function (win) {
- info("The private window got loaded");
- win.addEventListener("SSWindowClosing", function onclosing() {
- win.removeEventListener("SSWindowClosing", onclosing, false);
- executeSoon(function () {
- is(ss.getClosedWindowCount(), 0,
- "The private window should not have been stored");
- });
- }, false);
- BrowserTestUtils.closeWindow(win).then(finish);
- });
-}
diff --git a/browser/components/sessionstore/test/browser_windowStateContainer.js b/browser/components/sessionstore/test/browser_windowStateContainer.js
deleted file mode 100644
index beb838088..000000000
--- a/browser/components/sessionstore/test/browser_windowStateContainer.js
+++ /dev/null
@@ -1,122 +0,0 @@
-"use strict";
-
-requestLongerTimeout(2);
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-});
-
-add_task(function* () {
- let win = yield BrowserTestUtils.openNewBrowserWindow();
-
- // Create 4 tabs with different userContextId.
- for (let userContextId = 1; userContextId < 5; userContextId++) {
- let tab = win.gBrowser.addTab("http://example.com/", {userContextId});
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- }
-
- // Move the default tab of window to the end.
- // We want the 1st tab to have non-default userContextId, so later when we
- // restore into win2 we can test restore into an existing tab with different
- // userContextId.
- win.gBrowser.moveTabTo(win.gBrowser.tabs[0], win.gBrowser.tabs.length - 1);
-
- let winState = JSON.parse(ss.getWindowState(win));
-
- for (let i = 0; i < 4; i++) {
- Assert.equal(winState.windows[0].tabs[i].userContextId, i + 1,
- "1st Window: tabs[" + i + "].userContextId should exist.");
- }
-
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- // Create tabs with different userContextId, but this time we create them with
- // fewer tabs and with different order with win.
- for (let userContextId = 3; userContextId > 0; userContextId--) {
- let tab = win2.gBrowser.addTab("http://example.com/", {userContextId});
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
- }
-
- ss.setWindowState(win2, JSON.stringify(winState), true);
-
- for (let i = 0; i < 4; i++) {
- let browser = win2.gBrowser.tabs[i].linkedBrowser;
- yield ContentTask.spawn(browser, { expectedId: i + 1 }, function* (args) {
- Assert.equal(docShell.getOriginAttributes().userContextId,
- args.expectedId,
- "The docShell has the correct userContextId");
-
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId,
- args.expectedId,
- "The document has the correct userContextId");
- });
- }
-
- // Test the last tab, which doesn't have userContextId.
- let browser = win2.gBrowser.tabs[4].linkedBrowser;
- yield ContentTask.spawn(browser, { expectedId: 0 }, function* (args) {
- Assert.equal(docShell.getOriginAttributes().userContextId,
- args.expectedId,
- "The docShell has the correct userContextId");
-
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId,
- args.expectedId,
- "The document has the correct userContextId");
- });
-
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(win2);
-});
-
-add_task(function* () {
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- yield TabStateFlusher.flush(win.gBrowser.selectedBrowser);
-
- let tab = win.gBrowser.addTab("http://example.com/", { userContextId: 1 });
- yield promiseBrowserLoaded(tab.linkedBrowser);
- yield TabStateFlusher.flush(tab.linkedBrowser);
-
- // win should have 1 default tab, and 1 container tab.
- Assert.equal(win.gBrowser.tabs.length, 2, "win should have 2 tabs");
-
- let winState = JSON.parse(ss.getWindowState(win));
-
- for (let i = 0; i < 2; i++) {
- Assert.equal(winState.windows[0].tabs[i].userContextId, i,
- "1st Window: tabs[" + i + "].userContextId should be " + i);
- }
-
- let win2 = yield BrowserTestUtils.openNewBrowserWindow();
-
- let tab2 = win2.gBrowser.addTab("http://example.com/", { userContextId : 1 });
- yield promiseBrowserLoaded(tab2.linkedBrowser);
- yield TabStateFlusher.flush(tab2.linkedBrowser);
-
- // Move the first normal tab to end, so the first tab of win2 will be a
- // container tab.
- win2.gBrowser.moveTabTo(win2.gBrowser.tabs[0], win2.gBrowser.tabs.length - 1);
- yield TabStateFlusher.flush(win2.gBrowser.tabs[0].linkedBrowser);
-
- ss.setWindowState(win2, JSON.stringify(winState), true);
-
- for (let i = 0; i < 2; i++) {
- let browser = win2.gBrowser.tabs[i].linkedBrowser;
- yield ContentTask.spawn(browser, { expectedId: i }, function* (args) {
- Assert.equal(docShell.getOriginAttributes().userContextId,
- args.expectedId,
- "The docShell has the correct userContextId");
-
- Assert.equal(content.document.nodePrincipal.originAttributes.userContextId,
- args.expectedId,
- "The document has the correct userContextId");
- });
- }
-
- yield BrowserTestUtils.closeWindow(win);
- yield BrowserTestUtils.closeWindow(win2);
-});
-
diff --git a/browser/components/sessionstore/test/content-forms.js b/browser/components/sessionstore/test/content-forms.js
deleted file mode 100644
index da7bc9c08..000000000
--- a/browser/components/sessionstore/test/content-forms.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-/**
- * This frame script is only loaded for sessionstore mochitests. It contains
- * a bunch of utility functions used to test form data collection and
- * restoration in remote browsers.
- */
-
-function queryElement(data) {
- let frame = content;
- if (data.hasOwnProperty("frame")) {
- frame = content.frames[data.frame];
- }
-
- let doc = frame.document;
-
- if (data.hasOwnProperty("id")) {
- return doc.getElementById(data.id);
- }
-
- if (data.hasOwnProperty("selector")) {
- return doc.querySelector(data.selector);
- }
-
- if (data.hasOwnProperty("xpath")) {
- let xptype = Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE;
- return doc.evaluate(data.xpath, doc, null, xptype, null).singleNodeValue;
- }
-
- throw new Error("couldn't query element");
-}
-
-function dispatchUIEvent(input, type) {
- let event = input.ownerDocument.createEvent("UIEvents");
- event.initUIEvent(type, true, true, input.ownerGlobal, 0);
- input.dispatchEvent(event);
-}
-
-function defineListener(type, cb) {
- addMessageListener("ss-test:" + type, function ({data}) {
- sendAsyncMessage("ss-test:" + type, cb(data));
- });
-}
-
-defineListener("sendKeyEvent", function (data) {
- let frame = content;
- if (data.hasOwnProperty("frame")) {
- frame = content.frames[data.frame];
- }
-
- let ifreq = frame.QueryInterface(Ci.nsIInterfaceRequestor);
- let utils = ifreq.getInterface(Ci.nsIDOMWindowUtils);
-
- let keyCode = data.key.charCodeAt(0);
- let charCode = Ci.nsIDOMKeyEvent.DOM_VK_A + keyCode - "a".charCodeAt(0);
-
- utils.sendKeyEvent("keydown", keyCode, charCode, null);
- utils.sendKeyEvent("keypress", keyCode, charCode, null);
- utils.sendKeyEvent("keyup", keyCode, charCode, null);
-});
-
-defineListener("getInnerHTML", function (data) {
- return queryElement(data).innerHTML;
-});
-
-defineListener("getTextContent", function (data) {
- return queryElement(data).textContent;
-});
-
-defineListener("getInputValue", function (data) {
- return queryElement(data).value;
-});
-
-defineListener("setInputValue", function (data) {
- let input = queryElement(data);
- input.value = data.value;
- dispatchUIEvent(input, "input");
-});
-
-defineListener("getInputChecked", function (data) {
- return queryElement(data).checked;
-});
-
-defineListener("setInputChecked", function (data) {
- let input = queryElement(data);
- input.checked = data.checked;
- dispatchUIEvent(input, "change");
-});
-
-defineListener("getSelectedIndex", function (data) {
- return queryElement(data).selectedIndex;
-});
-
-defineListener("setSelectedIndex", function (data) {
- let input = queryElement(data);
- input.selectedIndex = data.index;
- dispatchUIEvent(input, "change");
-});
-
-defineListener("getMultipleSelected", function (data) {
- let input = queryElement(data);
- return Array.map(input.options, (opt, idx) => idx)
- .filter(idx => input.options[idx].selected);
-});
-
-defineListener("setMultipleSelected", function (data) {
- let input = queryElement(data);
- Array.forEach(input.options, (opt, idx) => opt.selected = data.indices.indexOf(idx) > -1);
- dispatchUIEvent(input, "change");
-});
-
-defineListener("getFileNameArray", function (data) {
- return queryElement(data).mozGetFileNameArray();
-});
-
-defineListener("setFileNameArray", function (data) {
- let input = queryElement(data);
- input.mozSetFileNameArray(data.names, data.names.length);
- dispatchUIEvent(input, "input");
-});
-
-defineListener("setFormElementValues", function (data) {
- for (let elem of content.document.forms[0].elements) {
- elem.value = data.value;
- dispatchUIEvent(elem, "input");
- }
-});
diff --git a/browser/components/sessionstore/test/content.js b/browser/components/sessionstore/test/content.js
deleted file mode 100644
index e815a6783..000000000
--- a/browser/components/sessionstore/test/content.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var Cu = Components.utils;
-var Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource:///modules/sessionstore/FrameTree.jsm", this);
-var gFrameTree = new FrameTree(this);
-
-function executeSoon(callback) {
- Services.tm.mainThread.dispatch(callback, Components.interfaces.nsIThread.DISPATCH_NORMAL);
-}
-
-gFrameTree.addObserver({
- onFrameTreeReset: function () {
- sendAsyncMessage("ss-test:onFrameTreeReset");
- },
-
- onFrameTreeCollected: function () {
- sendAsyncMessage("ss-test:onFrameTreeCollected");
- }
-});
-
-var historyListener = {
- OnHistoryNewEntry: function () {
- sendAsyncMessage("ss-test:OnHistoryNewEntry");
- },
-
- OnHistoryGoBack: function () {
- sendAsyncMessage("ss-test:OnHistoryGoBack");
- return true;
- },
-
- OnHistoryGoForward: function () {
- sendAsyncMessage("ss-test:OnHistoryGoForward");
- return true;
- },
-
- OnHistoryGotoIndex: function () {
- sendAsyncMessage("ss-test:OnHistoryGotoIndex");
- return true;
- },
-
- OnHistoryPurge: function () {
- sendAsyncMessage("ss-test:OnHistoryPurge");
- return true;
- },
-
- OnHistoryReload: function () {
- sendAsyncMessage("ss-test:OnHistoryReload");
- return true;
- },
-
- OnHistoryReplaceEntry: function () {
- sendAsyncMessage("ss-test:OnHistoryReplaceEntry");
- },
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsISHistoryListener,
- Ci.nsISupportsWeakReference
- ])
-};
-
-var {sessionHistory} = docShell.QueryInterface(Ci.nsIWebNavigation);
-if (sessionHistory) {
- sessionHistory.addSHistoryListener(historyListener);
-}
-
-/**
- * This frame script is only loaded for sessionstore mochitests. It enables us
- * to modify and query docShell data when running with multiple processes.
- */
-
-addEventListener("hashchange", function () {
- sendAsyncMessage("ss-test:hashchange");
-});
-
-addMessageListener("ss-test:purgeDomainData", function ({data: domain}) {
- Services.obs.notifyObservers(null, "browser:purge-domain-data", domain);
- content.setTimeout(() => sendAsyncMessage("ss-test:purgeDomainData"));
-});
-
-addMessageListener("ss-test:getStyleSheets", function (msg) {
- let sheets = content.document.styleSheets;
- let titles = Array.map(sheets, ss => [ss.title, ss.disabled]);
- sendSyncMessage("ss-test:getStyleSheets", titles);
-});
-
-addMessageListener("ss-test:enableStyleSheetsForSet", function (msg) {
- let sheets = content.document.styleSheets;
- let change = false;
- for (let i = 0; i < sheets.length; i++) {
- if (sheets[i].disabled != (msg.data.indexOf(sheets[i].title) == -1)) {
- change = true;
- break;
- }
- }
- function observer() {
- Services.obs.removeObserver(observer, "style-sheet-applicable-state-changed");
-
- // It's possible our observer will run before the one in
- // content-sessionStore.js. Therefore, we run ours a little
- // later.
- executeSoon(() => sendAsyncMessage("ss-test:enableStyleSheetsForSet"));
- }
- if (change) {
- // We don't want to reply until content-sessionStore.js has seen
- // the change.
- Services.obs.addObserver(observer, "style-sheet-applicable-state-changed", false);
-
- content.document.enableStyleSheetsForSet(msg.data);
- } else {
- sendAsyncMessage("ss-test:enableStyleSheetsForSet");
- }
-});
-
-addMessageListener("ss-test:enableSubDocumentStyleSheetsForSet", function (msg) {
- let iframe = content.document.getElementById(msg.data.id);
- iframe.contentDocument.enableStyleSheetsForSet(msg.data.set);
- sendAsyncMessage("ss-test:enableSubDocumentStyleSheetsForSet");
-});
-
-addMessageListener("ss-test:getAuthorStyleDisabled", function (msg) {
- let {authorStyleDisabled} =
- docShell.contentViewer;
- sendSyncMessage("ss-test:getAuthorStyleDisabled", authorStyleDisabled);
-});
-
-addMessageListener("ss-test:setAuthorStyleDisabled", function (msg) {
- let markupDocumentViewer =
- docShell.contentViewer;
- markupDocumentViewer.authorStyleDisabled = msg.data;
- sendSyncMessage("ss-test:setAuthorStyleDisabled");
-});
-
-addMessageListener("ss-test:setUsePrivateBrowsing", function (msg) {
- let loadContext =
- docShell.QueryInterface(Ci.nsILoadContext);
- loadContext.usePrivateBrowsing = msg.data;
- sendAsyncMessage("ss-test:setUsePrivateBrowsing");
-});
-
-addMessageListener("ss-test:getScrollPosition", function (msg) {
- let frame = content;
- if (msg.data.hasOwnProperty("frame")) {
- frame = content.frames[msg.data.frame];
- }
- let {scrollX: x, scrollY: y} = frame;
- sendAsyncMessage("ss-test:getScrollPosition", {x: x, y: y});
-});
-
-addMessageListener("ss-test:setScrollPosition", function (msg) {
- let frame = content;
- let {x, y} = msg.data;
- if (msg.data.hasOwnProperty("frame")) {
- frame = content.frames[msg.data.frame];
- }
- frame.scrollTo(x, y);
-
- frame.addEventListener("scroll", function onScroll(event) {
- if (frame.document == event.target) {
- frame.removeEventListener("scroll", onScroll);
- sendAsyncMessage("ss-test:setScrollPosition");
- }
- });
-});
-
-addMessageListener("ss-test:createDynamicFrames", function ({data}) {
- function createIFrame(rows) {
- let frames = content.document.getElementById(data.id);
- frames.setAttribute("rows", rows);
-
- let frame = content.document.createElement("frame");
- frame.setAttribute("src", data.url);
- frames.appendChild(frame);
- }
-
- addEventListener("DOMContentLoaded", function onContentLoaded(event) {
- if (content.document == event.target) {
- removeEventListener("DOMContentLoaded", onContentLoaded, true);
- // DOMContentLoaded is fired right after we finished parsing the document.
- createIFrame("33%, 33%, 33%");
- }
- }, true);
-
- addEventListener("load", function onLoad(event) {
- if (content.document == event.target) {
- removeEventListener("load", onLoad, true);
-
- // Creating this frame on the same tick as the load event
- // means that it must not be included in the frame tree.
- createIFrame("25%, 25%, 25%, 25%");
- }
- }, true);
-
- sendAsyncMessage("ss-test:createDynamicFrames");
-});
-
-addMessageListener("ss-test:removeLastFrame", function ({data}) {
- let frames = content.document.getElementById(data.id);
- frames.lastElementChild.remove();
- sendAsyncMessage("ss-test:removeLastFrame");
-});
-
-addMessageListener("ss-test:mapFrameTree", function (msg) {
- let result = gFrameTree.map(frame => ({href: frame.location.href}));
- sendAsyncMessage("ss-test:mapFrameTree", result);
-});
-
-addMessageListener("ss-test:click", function ({data}) {
- content.document.getElementById(data.id).click();
- sendAsyncMessage("ss-test:click");
-});
-
-addEventListener("load", function(event) {
- let subframe = event.target != content.document;
- sendAsyncMessage("ss-test:loadEvent", {subframe: subframe, url: event.target.documentURI});
-}, true);
diff --git a/browser/components/sessionstore/test/head.js b/browser/components/sessionstore/test/head.js
deleted file mode 100644
index 5a8c5dbfc..000000000
--- a/browser/components/sessionstore/test/head.js
+++ /dev/null
@@ -1,564 +0,0 @@
-/* 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/. */
-
-const TAB_STATE_NEEDS_RESTORE = 1;
-const TAB_STATE_RESTORING = 2;
-
-const ROOT = getRootDirectory(gTestPath);
-const HTTPROOT = ROOT.replace("chrome://mochitests/content/", "http://example.com/");
-const FRAME_SCRIPTS = [
- ROOT + "content.js",
- ROOT + "content-forms.js"
-];
-
-var mm = Cc["@mozilla.org/globalmessagemanager;1"]
- .getService(Ci.nsIMessageListenerManager);
-
-for (let script of FRAME_SCRIPTS) {
- mm.loadFrameScript(script, true);
-}
-
-registerCleanupFunction(() => {
- for (let script of FRAME_SCRIPTS) {
- mm.removeDelayedFrameScript(script, true);
- }
-});
-
-const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
-const {SessionStore} = Cu.import("resource:///modules/sessionstore/SessionStore.jsm", {});
-const {SessionSaver} = Cu.import("resource:///modules/sessionstore/SessionSaver.jsm", {});
-const {SessionFile} = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {});
-const {TabState} = Cu.import("resource:///modules/sessionstore/TabState.jsm", {});
-const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
-
-const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
-
-// Some tests here assume that all restored tabs are loaded without waiting for
-// the user to bring them to the foreground. We ensure this by resetting the
-// related preference (see the "firefox.js" defaults file for details).
-Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", false);
-registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
-});
-
-// Obtain access to internals
-Services.prefs.setBoolPref("browser.sessionstore.debug", true);
-registerCleanupFunction(function () {
- Services.prefs.clearUserPref("browser.sessionstore.debug");
-});
-
-
-// This kicks off the search service used on about:home and allows the
-// session restore tests to be run standalone without triggering errors.
-Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler).defaultArgs;
-
-function provideWindow(aCallback, aURL, aFeatures) {
- function callbackSoon(aWindow) {
- executeSoon(function executeCallbackSoon() {
- aCallback(aWindow);
- });
- }
-
- let win = openDialog(getBrowserURL(), "", aFeatures || "chrome,all,dialog=no", aURL || "about:blank");
- whenWindowLoaded(win, function onWindowLoaded(aWin) {
- if (!aURL) {
- info("Loaded a blank window.");
- callbackSoon(aWin);
- return;
- }
-
- aWin.gBrowser.selectedBrowser.addEventListener("load", function selectedBrowserLoadListener() {
- aWin.gBrowser.selectedBrowser.removeEventListener("load", selectedBrowserLoadListener, true);
- callbackSoon(aWin);
- }, true);
- });
-}
-
-// This assumes that tests will at least have some state/entries
-function waitForBrowserState(aState, aSetStateCallback) {
- if (typeof aState == "string") {
- aState = JSON.parse(aState);
- }
- if (typeof aState != "object") {
- throw new TypeError("Argument must be an object or a JSON representation of an object");
- }
- let windows = [window];
- let tabsRestored = 0;
- let expectedTabsRestored = 0;
- let expectedWindows = aState.windows.length;
- let windowsOpen = 1;
- let listening = false;
- let windowObserving = false;
- let restoreHiddenTabs = Services.prefs.getBoolPref(
- "browser.sessionstore.restore_hidden_tabs");
-
- aState.windows.forEach(function (winState) {
- winState.tabs.forEach(function (tabState) {
- if (restoreHiddenTabs || !tabState.hidden)
- expectedTabsRestored++;
- });
- });
-
- // There must be only hidden tabs and restoreHiddenTabs = false. We still
- // expect one of them to be restored because it gets shown automatically.
- if (!expectedTabsRestored)
- expectedTabsRestored = 1;
-
- function onSSTabRestored(aEvent) {
- if (++tabsRestored == expectedTabsRestored) {
- // Remove the event listener from each window
- windows.forEach(function(win) {
- win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true);
- });
- listening = false;
- info("running " + aSetStateCallback.name);
- executeSoon(aSetStateCallback);
- }
- }
-
- // Used to add our listener to further windows so we can catch SSTabRestored
- // coming from them when creating a multi-window state.
- function windowObserver(aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- let newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
- newWindow.addEventListener("load", function() {
- newWindow.removeEventListener("load", arguments.callee, false);
-
- if (++windowsOpen == expectedWindows) {
- Services.ww.unregisterNotification(windowObserver);
- windowObserving = false;
- }
-
- // Track this window so we can remove the progress listener later
- windows.push(newWindow);
- // Add the progress listener
- newWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
- }, false);
- }
- }
-
- // We only want to register the notification if we expect more than 1 window
- if (expectedWindows > 1) {
- registerCleanupFunction(function() {
- if (windowObserving) {
- Services.ww.unregisterNotification(windowObserver);
- }
- });
- windowObserving = true;
- Services.ww.registerNotification(windowObserver);
- }
-
- registerCleanupFunction(function() {
- if (listening) {
- windows.forEach(function(win) {
- win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true);
- });
- }
- });
- // Add the event listener for this window as well.
- listening = true;
- gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
-
- // Ensure setBrowserState() doesn't remove the initial tab.
- gBrowser.selectedTab = gBrowser.tabs[0];
-
- // Finally, call setBrowserState
- ss.setBrowserState(JSON.stringify(aState));
-}
-
-function promiseBrowserState(aState) {
- return new Promise(resolve => waitForBrowserState(aState, resolve));
-}
-
-function promiseTabState(tab, state) {
- if (typeof(state) != "string") {
- state = JSON.stringify(state);
- }
-
- let promise = promiseTabRestored(tab);
- ss.setTabState(tab, state);
- return promise;
-}
-
-/**
- * Wait for a content -> chrome message.
- */
-function promiseContentMessage(browser, name) {
- let mm = browser.messageManager;
-
- return new Promise(resolve => {
- function removeListener() {
- mm.removeMessageListener(name, listener);
- }
-
- function listener(msg) {
- removeListener();
- resolve(msg.data);
- }
-
- mm.addMessageListener(name, listener);
- registerCleanupFunction(removeListener);
- });
-}
-
-function waitForTopic(aTopic, aTimeout, aCallback) {
- let observing = false;
- function removeObserver() {
- if (!observing)
- return;
- Services.obs.removeObserver(observer, aTopic);
- observing = false;
- }
-
- let timeout = setTimeout(function () {
- removeObserver();
- aCallback(false);
- }, aTimeout);
-
- function observer(aSubject, aTopic, aData) {
- removeObserver();
- timeout = clearTimeout(timeout);
- executeSoon(() => aCallback(true));
- }
-
- registerCleanupFunction(function() {
- removeObserver();
- if (timeout) {
- clearTimeout(timeout);
- }
- });
-
- observing = true;
- Services.obs.addObserver(observer, aTopic, false);
-}
-
-/**
- * Wait until session restore has finished collecting its data and is
- * has written that data ("sessionstore-state-write-complete").
- *
- * @param {function} aCallback If sessionstore-state-write-complete is sent
- * within buffering interval + 100 ms, the callback is passed |true|,
- * otherwise, it is passed |false|.
- */
-function waitForSaveState(aCallback) {
- let timeout = 100 +
- Services.prefs.getIntPref("browser.sessionstore.interval");
- return waitForTopic("sessionstore-state-write-complete", timeout, aCallback);
-}
-function promiseSaveState() {
- return new Promise(resolve => {
- waitForSaveState(isSuccessful => {
- if (!isSuccessful) {
- throw new Error("timeout");
- }
-
- resolve();
- });
- });
-}
-function forceSaveState() {
- return SessionSaver.run();
-}
-
-function promiseRecoveryFileContents() {
- let promise = forceSaveState();
- return promise.then(function() {
- return OS.File.read(SessionFile.Paths.recovery, { encoding: "utf-8" });
- });
-}
-
-var promiseForEachSessionRestoreFile = Task.async(function*(cb) {
- for (let key of SessionFile.Paths.loadOrder) {
- let data = "";
- try {
- data = yield OS.File.read(SessionFile.Paths[key], { encoding: "utf-8" });
- } catch (ex) {
- // Ignore missing files
- if (!(ex instanceof OS.File.Error && ex.becauseNoSuchFile)) {
- throw ex;
- }
- }
- cb(data, key);
- }
-});
-
-function promiseBrowserLoaded(aBrowser, ignoreSubFrames = true, wantLoad = null) {
- return BrowserTestUtils.browserLoaded(aBrowser, !ignoreSubFrames, wantLoad);
-}
-
-function whenWindowLoaded(aWindow, aCallback = next) {
- aWindow.addEventListener("load", function windowLoadListener() {
- aWindow.removeEventListener("load", windowLoadListener, false);
- executeSoon(function executeWhenWindowLoaded() {
- aCallback(aWindow);
- });
- }, false);
-}
-function promiseWindowLoaded(aWindow) {
- return new Promise(resolve => whenWindowLoaded(aWindow, resolve));
-}
-
-var gUniqueCounter = 0;
-function r() {
- return Date.now() + "-" + (++gUniqueCounter);
-}
-
-function* BrowserWindowIterator() {
- let windowsEnum = Services.wm.getEnumerator("navigator:browser");
- while (windowsEnum.hasMoreElements()) {
- let currentWindow = windowsEnum.getNext();
- if (!currentWindow.closed) {
- yield currentWindow;
- }
- }
-}
-
-var gWebProgressListener = {
- _callback: null,
-
- setCallback: function (aCallback) {
- if (!this._callback) {
- window.gBrowser.addTabsProgressListener(this);
- }
- this._callback = aCallback;
- },
-
- unsetCallback: function () {
- if (this._callback) {
- this._callback = null;
- window.gBrowser.removeTabsProgressListener(this);
- }
- },
-
- onStateChange: function (aBrowser, aWebProgress, aRequest,
- aStateFlags, aStatus) {
- if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
- aStateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) {
- this._callback(aBrowser);
- }
- }
-};
-
-registerCleanupFunction(function () {
- gWebProgressListener.unsetCallback();
-});
-
-var gProgressListener = {
- _callback: null,
-
- setCallback: function (callback) {
- Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false);
- this._callback = callback;
- },
-
- unsetCallback: function () {
- if (this._callback) {
- this._callback = null;
- Services.obs.removeObserver(this, "sessionstore-debug-tab-restored");
- }
- },
-
- observe: function (browser, topic, data) {
- gProgressListener.onRestored(browser);
- },
-
- onRestored: function (browser) {
- if (browser.__SS_restoreState == TAB_STATE_RESTORING) {
- let args = [browser].concat(gProgressListener._countTabs());
- gProgressListener._callback.apply(gProgressListener, args);
- }
- },
-
- _countTabs: function () {
- let needsRestore = 0, isRestoring = 0, wasRestored = 0;
-
- for (let win of BrowserWindowIterator()) {
- for (let i = 0; i < win.gBrowser.tabs.length; i++) {
- let browser = win.gBrowser.tabs[i].linkedBrowser;
- if (!browser.__SS_restoreState)
- wasRestored++;
- else if (browser.__SS_restoreState == TAB_STATE_RESTORING)
- isRestoring++;
- else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE)
- needsRestore++;
- }
- }
- return [needsRestore, isRestoring, wasRestored];
- }
-};
-
-registerCleanupFunction(function () {
- gProgressListener.unsetCallback();
-});
-
-// Close all but our primary window.
-function promiseAllButPrimaryWindowClosed() {
- let windows = [];
- for (let win of BrowserWindowIterator()) {
- if (win != window) {
- windows.push(win);
- }
- }
-
- return Promise.all(windows.map(BrowserTestUtils.closeWindow));
-}
-
-// Forget all closed windows.
-function forgetClosedWindows() {
- while (ss.getClosedWindowCount() > 0) {
- ss.forgetClosedWindow(0);
- }
-}
-
-/**
- * When opening a new window it is not sufficient to wait for its load event.
- * We need to use whenDelayedStartupFinshed() here as the browser window's
- * delayedStartup() routine is executed one tick after the window's load event
- * has been dispatched. browser-delayed-startup-finished might be deferred even
- * further if parts of the window's initialization process take more time than
- * expected (e.g. reading a big session state from disk).
- */
-function whenNewWindowLoaded(aOptions, aCallback) {
- let features = "";
- let url = "about:blank";
-
- if (aOptions && aOptions.private || false) {
- features = ",private";
- url = "about:privatebrowsing";
- }
-
- let win = openDialog(getBrowserURL(), "", "chrome,all,dialog=no" + features, url);
- let delayedStartup = promiseDelayedStartupFinished(win);
-
- let browserLoaded = new Promise(resolve => {
- if (url == "about:blank") {
- resolve();
- return;
- }
-
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- let browser = win.gBrowser.selectedBrowser;
- promiseBrowserLoaded(browser).then(resolve);
- });
- });
-
- Promise.all([delayedStartup, browserLoaded]).then(() => aCallback(win));
-}
-function promiseNewWindowLoaded(aOptions) {
- return new Promise(resolve => whenNewWindowLoaded(aOptions, resolve));
-}
-
-/**
- * This waits for the browser-delayed-startup-finished notification of a given
- * window. It indicates that the windows has loaded completely and is ready to
- * be used for testing.
- */
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- executeSoon(aCallback);
- }
- }, "browser-delayed-startup-finished", false);
-}
-function promiseDelayedStartupFinished(aWindow) {
- return new Promise(resolve => whenDelayedStartupFinished(aWindow, resolve));
-}
-
-function promiseEvent(element, eventType, isCapturing = false) {
- return new Promise(resolve => {
- element.addEventListener(eventType, function listener(event) {
- element.removeEventListener(eventType, listener, isCapturing);
- resolve(event);
- }, isCapturing);
- });
-}
-
-function promiseTabRestored(tab) {
- return promiseEvent(tab, "SSTabRestored");
-}
-
-function promiseTabRestoring(tab) {
- return promiseEvent(tab, "SSTabRestoring");
-}
-
-function sendMessage(browser, name, data = {}) {
- browser.messageManager.sendAsyncMessage(name, data);
- return promiseContentMessage(browser, name);
-}
-
-// This creates list of functions that we will map to their corresponding
-// ss-test:* messages names. Those will be sent to the frame script and
-// be used to read and modify form data.
-const FORM_HELPERS = [
- "getTextContent",
- "getInputValue", "setInputValue",
- "getInputChecked", "setInputChecked",
- "getSelectedIndex", "setSelectedIndex",
- "getMultipleSelected", "setMultipleSelected",
- "getFileNameArray", "setFileNameArray",
-];
-
-for (let name of FORM_HELPERS) {
- let msg = "ss-test:" + name;
- this[name] = (browser, data) => sendMessage(browser, msg, data);
-}
-
-// Removes the given tab immediately and returns a promise that resolves when
-// all pending status updates (messages) of the closing tab have been received.
-function promiseRemoveTab(tab) {
- return BrowserTestUtils.removeTab(tab);
-}
-
-// Write DOMSessionStorage data to the given browser.
-function modifySessionStorage(browser, data, options = {}) {
- return ContentTask.spawn(browser, [data, options], function* ([data, options]) {
- let frame = content;
- if (options && "frameIndex" in options) {
- frame = content.frames[options.frameIndex];
- }
-
- let keys = new Set(Object.keys(data));
- let storage = frame.sessionStorage;
-
- return new Promise(resolve => {
- addEventListener("MozSessionStorageChanged", function onStorageChanged(event) {
- if (event.storageArea == storage) {
- keys.delete(event.key);
- }
-
- if (keys.size == 0) {
- removeEventListener("MozSessionStorageChanged", onStorageChanged, true);
- resolve();
- }
- }, true);
-
- for (let key of keys) {
- frame.sessionStorage[key] = data[key];
- }
- });
- });
-}
-
-function pushPrefs(...aPrefs) {
- return new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
- });
-}
-
-function popPrefs() {
- return new Promise(resolve => {
- SpecialPowers.popPrefEnv(resolve);
- });
-}
-
-function* checkScroll(tab, expected, msg) {
- let browser = tab.linkedBrowser;
- yield TabStateFlusher.flush(browser);
-
- let scroll = JSON.parse(ss.getTabState(tab)).scroll || null;
- is(JSON.stringify(scroll), JSON.stringify(expected), msg);
-}
diff --git a/browser/components/sessionstore/test/restore_redirect_http.html b/browser/components/sessionstore/test/restore_redirect_http.html
deleted file mode 100644
index e69de29bb..000000000
--- a/browser/components/sessionstore/test/restore_redirect_http.html
+++ /dev/null
diff --git a/browser/components/sessionstore/test/restore_redirect_http.html^headers^ b/browser/components/sessionstore/test/restore_redirect_http.html^headers^
deleted file mode 100644
index 533bda36f..000000000
--- a/browser/components/sessionstore/test/restore_redirect_http.html^headers^
+++ /dev/null
@@ -1,2 +0,0 @@
-HTTP 302 Moved Temporarily
-Location: restore_redirect_target.html
diff --git a/browser/components/sessionstore/test/restore_redirect_js.html b/browser/components/sessionstore/test/restore_redirect_js.html
deleted file mode 100644
index 1f5f0e54c..000000000
--- a/browser/components/sessionstore/test/restore_redirect_js.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
-<script>
-var newLocation = window.location.toString().replace("restore_redirect_js.html", "restore_redirect_target.html");
-window.location.replace(newLocation);
-</script>
-</head>
-</html> \ No newline at end of file
diff --git a/browser/components/sessionstore/test/restore_redirect_target.html b/browser/components/sessionstore/test/restore_redirect_target.html
deleted file mode 100644
index 6c8b3aae5..000000000
--- a/browser/components/sessionstore/test/restore_redirect_target.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
-<title>Test page</title>
-</head>
-<body>Test page</body>
-</html>
diff --git a/browser/components/sessionstore/test/unit/.eslintrc.js b/browser/components/sessionstore/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/sessionstore/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json b/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json
deleted file mode 100644
index 928de6a39..000000000
--- a/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json
+++ /dev/null
@@ -1 +0,0 @@
-{"profile-after-change":true,"final-ui-startup":true,"sessionstore-windows-restored":true,"quit-application-granted":true,"quit-application":true,"sessionstore-final-state-write-complete":true,"profile-change-net-teardown":true,"profile-change-teardown":true,"profile-before-change":true} \ No newline at end of file
diff --git a/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js b/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js
deleted file mode 100644
index a8c3ff2ff..000000000
--- a/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "windows": // invalid json
-}
diff --git a/browser/components/sessionstore/test/unit/data/sessionstore_valid.js b/browser/components/sessionstore/test/unit/data/sessionstore_valid.js
deleted file mode 100644
index f9511f29f..000000000
--- a/browser/components/sessionstore/test/unit/data/sessionstore_valid.js
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "windows": []
-} \ No newline at end of file
diff --git a/browser/components/sessionstore/test/unit/head.js b/browser/components/sessionstore/test/unit/head.js
deleted file mode 100644
index b62856012..000000000
--- a/browser/components/sessionstore/test/unit/head.js
+++ /dev/null
@@ -1,32 +0,0 @@
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-// Call a function once initialization of SessionStartup is complete
-function afterSessionStartupInitialization(cb) {
- do_print("Waiting for session startup initialization");
- let observer = function() {
- try {
- do_print("Session startup initialization observed");
- Services.obs.removeObserver(observer, "sessionstore-state-finalized");
- cb();
- } catch (ex) {
- do_throw(ex);
- }
- };
-
- // We need the Crash Monitor initialized for sessionstartup to run
- // successfully.
- Components.utils.import("resource://gre/modules/CrashMonitor.jsm");
- CrashMonitor.init();
-
- // Start sessionstartup initialization.
- let startup = Cc["@mozilla.org/browser/sessionstartup;1"].
- getService(Ci.nsIObserver);
- Services.obs.addObserver(startup, "final-ui-startup", false);
- Services.obs.addObserver(startup, "quit-application", false);
- Services.obs.notifyObservers(null, "final-ui-startup", "");
- Services.obs.addObserver(observer, "sessionstore-state-finalized", false);
-};
diff --git a/browser/components/sessionstore/test/unit/test_backup_once.js b/browser/components/sessionstore/test/unit/test_backup_once.js
deleted file mode 100644
index fff34ad58..000000000
--- a/browser/components/sessionstore/test/unit/test_backup_once.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
-var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
-var {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
-var {SessionWorker} = Cu.import("resource:///modules/sessionstore/SessionWorker.jsm", {});
-
-var File = OS.File;
-var Paths;
-var SessionFile;
-
-// We need a XULAppInfo to initialize SessionFile
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-updateAppInfo({
- name: "SessionRestoreTest",
- ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}",
- version: "1",
- platformVersion: "",
-});
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* init() {
- // Make sure that we have a profile before initializing SessionFile
- let profd = do_get_profile();
- SessionFile = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {}).SessionFile;
- Paths = SessionFile.Paths;
-
-
- let source = do_get_file("data/sessionstore_valid.js");
- source.copyTo(profd, "sessionstore.js");
-
- // Finish initialization of SessionFile
- yield SessionFile.read();
-});
-
-var pathStore;
-var pathBackup;
-var decoder;
-
-function promise_check_exist(path, shouldExist) {
- return Task.spawn(function*() {
- do_print("Ensuring that " + path + (shouldExist?" exists":" does not exist"));
- if ((yield OS.File.exists(path)) != shouldExist) {
- throw new Error("File " + path + " should " + (shouldExist?"exist":"not exist"));
- }
- });
-}
-
-function promise_check_contents(path, expect) {
- return Task.spawn(function*() {
- do_print("Checking whether " + path + " has the right contents");
- let actual = yield OS.File.read(path, { encoding: "utf-8"});
- Assert.deepEqual(JSON.parse(actual), expect, `File ${path} contains the expected data.`);
- });
-}
-
-function generateFileContents(id) {
- let url = `http://example.com/test_backup_once#${id}_${Math.random()}`;
- return {windows: [{tabs: [{entries: [{url}], index: 1}]}]}
-}
-
-// Write to the store, and check that it creates:
-// - $Path.recovery with the new data
-// - $Path.nextUpgradeBackup with the old data
-add_task(function* test_first_write_backup() {
- let initial_content = generateFileContents("initial");
- let new_content = generateFileContents("test_1");
-
- do_print("Before the first write, none of the files should exist");
- yield promise_check_exist(Paths.backups, false);
-
- yield File.makeDir(Paths.backups);
- yield File.writeAtomic(Paths.clean, JSON.stringify(initial_content), { encoding: "utf-8" });
- yield SessionFile.write(new_content);
-
- do_print("After first write, a few files should have been created");
- yield promise_check_exist(Paths.backups, true);
- yield promise_check_exist(Paths.clean, false);
- yield promise_check_exist(Paths.cleanBackup, true);
- yield promise_check_exist(Paths.recovery, true);
- yield promise_check_exist(Paths.recoveryBackup, false);
- yield promise_check_exist(Paths.nextUpgradeBackup, true);
-
- yield promise_check_contents(Paths.recovery, new_content);
- yield promise_check_contents(Paths.nextUpgradeBackup, initial_content);
-});
-
-// Write to the store again, and check that
-// - $Path.clean is not written
-// - $Path.recovery contains the new data
-// - $Path.recoveryBackup contains the previous data
-add_task(function* test_second_write_no_backup() {
- let new_content = generateFileContents("test_2");
- let previous_backup_content = yield File.read(Paths.recovery, { encoding: "utf-8" });
- previous_backup_content = JSON.parse(previous_backup_content);
-
- yield OS.File.remove(Paths.cleanBackup);
-
- yield SessionFile.write(new_content);
-
- yield promise_check_exist(Paths.backups, true);
- yield promise_check_exist(Paths.clean, false);
- yield promise_check_exist(Paths.cleanBackup, false);
- yield promise_check_exist(Paths.recovery, true);
- yield promise_check_exist(Paths.nextUpgradeBackup, true);
-
- yield promise_check_contents(Paths.recovery, new_content);
- yield promise_check_contents(Paths.recoveryBackup, previous_backup_content);
-});
-
-// Make sure that we create $Paths.clean and remove $Paths.recovery*
-// upon shutdown
-add_task(function* test_shutdown() {
- let output = generateFileContents("test_3");
-
- yield File.writeAtomic(Paths.recovery, "I should disappear");
- yield File.writeAtomic(Paths.recoveryBackup, "I should also disappear");
-
- yield SessionWorker.post("write", [output, { isFinalWrite: true, performShutdownCleanup: true}]);
-
- do_check_false((yield File.exists(Paths.recovery)));
- do_check_false((yield File.exists(Paths.recoveryBackup)));
- yield promise_check_contents(Paths.clean, output);
-});
diff --git a/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js b/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js
deleted file mode 100644
index c7d8b03ed..000000000
--- a/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * The primary purpose of this test is to ensure that
- * the sessionstore component records information about
- * corrupted backup files into a histogram.
- */
-
-"use strict";
-Cu.import("resource://gre/modules/osfile.jsm", this);
-
-const Telemetry = Services.telemetry;
-const Path = OS.Path;
-const HistogramId = "FX_SESSION_RESTORE_ALL_FILES_CORRUPT";
-
-// Prepare the session file.
-var profd = do_get_profile();
-Cu.import("resource:///modules/sessionstore/SessionFile.jsm", this);
-
-/**
- * A utility function for resetting the histogram and the contents
- * of the backup directory.
- */
-function reset_session(backups = {}) {
-
- // Reset the histogram.
- Telemetry.getHistogramById(HistogramId).clear();
-
- // Reset the contents of the backups directory
- OS.File.makeDir(SessionFile.Paths.backups);
- for (let key of SessionFile.Paths.loadOrder) {
- if (backups.hasOwnProperty(key)) {
- OS.File.copy(backups[key], SessionFile.Paths[key]);
- } else {
- OS.File.remove(SessionFile.Paths[key]);
- }
- }
-}
-
-/**
- * In order to use FX_SESSION_RESTORE_ALL_FILES_CORRUPT histogram
- * it has to be registered in "toolkit/components/telemetry/Histograms.json".
- * This test ensures that the histogram is registered and empty.
- */
-add_task(function* test_ensure_histogram_exists_and_empty() {
- let s = Telemetry.getHistogramById(HistogramId).snapshot();
- Assert.equal(s.sum, 0, "Initially, the sum of probes is 0");
-});
-
-/**
- * Makes sure that the histogram is negatively updated when no
- * backup files are present.
- */
-add_task(function* test_no_files_exist() {
- // No session files are available to SessionFile.
- reset_session();
-
- yield SessionFile.read();
- // Checking if the histogram is updated negatively
- let h = Telemetry.getHistogramById(HistogramId);
- let s = h.snapshot();
- Assert.equal(s.counts[0], 1, "One probe for the 'false' bucket.");
- Assert.equal(s.counts[1], 0, "No probes in the 'true' bucket.");
-});
-
-/**
- * Makes sure that the histogram is negatively updated when at least one
- * backup file is not corrupted.
- */
-add_task(function* test_one_file_valid() {
- // Corrupting some backup files.
- let invalidSession = "data/sessionstore_invalid.js";
- let validSession = "data/sessionstore_valid.js";
- reset_session({
- clean : invalidSession,
- cleanBackup: validSession,
- recovery: invalidSession,
- recoveryBackup: invalidSession
- });
-
- yield SessionFile.read();
- // Checking if the histogram is updated negatively.
- let h = Telemetry.getHistogramById(HistogramId);
- let s = h.snapshot();
- Assert.equal(s.counts[0], 1, "One probe for the 'false' bucket.");
- Assert.equal(s.counts[1], 0, "No probes in the 'true' bucket.");
-});
-
-/**
- * Makes sure that the histogram is positively updated when all
- * backup files are corrupted.
- */
-add_task(function* test_all_files_corrupt() {
- // Corrupting all backup files.
- let invalidSession = "data/sessionstore_invalid.js";
- reset_session({
- clean : invalidSession,
- cleanBackup: invalidSession,
- recovery: invalidSession,
- recoveryBackup: invalidSession
- });
-
- yield SessionFile.read();
- // Checking if the histogram is positively updated.
- let h = Telemetry.getHistogramById(HistogramId);
- let s = h.snapshot();
- Assert.equal(s.counts[1], 1, "One probe for the 'true' bucket.");
- Assert.equal(s.counts[0], 0, "No probes in the 'false' bucket.");
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js b/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js
deleted file mode 100644
index b99e566e9..000000000
--- a/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js
+++ /dev/null
@@ -1,127 +0,0 @@
-"use strict";
-
-/**
- * This test ensures that we correctly clean up the session state before
- * writing to disk a last time on shutdown. For now it only tests that each
- * tab's shistory is capped to a maximum number of preceding and succeeding
- * entries.
- */
-
-const {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
-const {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
-const {SessionWorker} = Cu.import("resource:///modules/sessionstore/SessionWorker.jsm", {});
-
-const profd = do_get_profile();
-const {SessionFile} = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {});
-const {Paths} = SessionFile;
-
-const {OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
-const {File} = OS;
-
-const MAX_ENTRIES = 9;
-const URL = "http://example.com/#";
-
-// We need a XULAppInfo to initialize SessionFile
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-updateAppInfo({
- name: "SessionRestoreTest",
- ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}",
- version: "1",
- platformVersion: "",
-});
-
-add_task(function* setup() {
- let source = do_get_file("data/sessionstore_valid.js");
- source.copyTo(profd, "sessionstore.js");
-
- // Finish SessionFile initialization.
- yield SessionFile.read();
-
- // Reset prefs on cleanup.
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.sessionstore.max_serialize_back");
- Services.prefs.clearUserPref("browser.sessionstore.max_serialize_forward");
- });
-});
-
-function createSessionState(index) {
- // Generate the tab state entries and set the one-based
- // tab-state index to the middle session history entry.
- let tabState = {entries: [], index};
- for (let i = 0; i < MAX_ENTRIES; i++) {
- tabState.entries.push({url: URL + i});
- }
-
- return {windows: [{tabs: [tabState]}]};
-}
-
-function* setMaxBackForward(back, fwd) {
- Services.prefs.setIntPref("browser.sessionstore.max_serialize_back", back);
- Services.prefs.setIntPref("browser.sessionstore.max_serialize_forward", fwd);
- yield SessionFile.read();
-}
-
-function* writeAndParse(state, path, options = {}) {
- yield SessionWorker.post("write", [state, options]);
- return JSON.parse(yield File.read(path, {encoding: "utf-8"}));
-}
-
-add_task(function* test_shistory_cap_none() {
- let state = createSessionState(5);
-
- // Don't limit the number of shistory entries.
- yield setMaxBackForward(-1, -1);
-
- // Check that no caps are applied.
- let diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true});
- Assert.deepEqual(state, diskState, "no cap applied");
-});
-
-add_task(function* test_shistory_cap_middle() {
- let state = createSessionState(5);
- yield setMaxBackForward(2, 3);
-
- // Cap is only applied on clean shutdown.
- let diskState = yield writeAndParse(state, Paths.recovery);
- Assert.deepEqual(state, diskState, "no cap applied");
-
- // Check that the right number of shistory entries was discarded
- // and the shistory index updated accordingly.
- diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true});
- let tabState = state.windows[0].tabs[0];
- tabState.entries = tabState.entries.slice(2, 8);
- tabState.index = 3;
- Assert.deepEqual(state, diskState, "cap applied");
-});
-
-add_task(function* test_shistory_cap_lower_bound() {
- let state = createSessionState(1);
- yield setMaxBackForward(5, 5);
-
- // Cap is only applied on clean shutdown.
- let diskState = yield writeAndParse(state, Paths.recovery);
- Assert.deepEqual(state, diskState, "no cap applied");
-
- // Check that the right number of shistory entries was discarded.
- diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true});
- let tabState = state.windows[0].tabs[0];
- tabState.entries = tabState.entries.slice(0, 6);
- Assert.deepEqual(state, diskState, "cap applied");
-});
-
-add_task(function* test_shistory_cap_upper_bound() {
- let state = createSessionState(MAX_ENTRIES);
- yield setMaxBackForward(5, 5);
-
- // Cap is only applied on clean shutdown.
- let diskState = yield writeAndParse(state, Paths.recovery);
- Assert.deepEqual(state, diskState, "no cap applied");
-
- // Check that the right number of shistory entries was discarded
- // and the shistory index updated accordingly.
- diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true});
- let tabState = state.windows[0].tabs[0];
- tabState.entries = tabState.entries.slice(3);
- tabState.index = 6;
- Assert.deepEqual(state, diskState, "cap applied");
-});
diff --git a/browser/components/sessionstore/test/unit/test_startup_invalid_session.js b/browser/components/sessionstore/test/unit/test_startup_invalid_session.js
deleted file mode 100644
index 9f6df8585..000000000
--- a/browser/components/sessionstore/test/unit/test_startup_invalid_session.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- let profd = do_get_profile();
-
- let sourceSession = do_get_file("data/sessionstore_invalid.js");
- sourceSession.copyTo(profd, "sessionstore.js");
-
- let sourceCheckpoints = do_get_file("data/sessionCheckpoints_all.json");
- sourceCheckpoints.copyTo(profd, "sessionCheckpoints.json");
-
- do_test_pending();
- let startup = Cc["@mozilla.org/browser/sessionstartup;1"].
- getService(Ci.nsISessionStartup);
-
- afterSessionStartupInitialization(function cb() {
- do_check_eq(startup.sessionType, Ci.nsISessionStartup.NO_SESSION);
- do_test_finished();
- });
-}
diff --git a/browser/components/sessionstore/test/unit/test_startup_nosession_async.js b/browser/components/sessionstore/test/unit/test_startup_nosession_async.js
deleted file mode 100644
index 5185b02d6..000000000
--- a/browser/components/sessionstore/test/unit/test_startup_nosession_async.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-// Test nsISessionStartup.sessionType in the following scenario:
-// - no sessionstore.js;
-// - the session store has been loaded, so no need to go
-// through the synchronous fallback
-
-function run_test() {
- do_get_profile();
- // Initialize the profile (the session startup uses it)
-
- do_test_pending();
- let startup = Cc["@mozilla.org/browser/sessionstartup;1"].
- getService(Ci.nsISessionStartup);
-
- afterSessionStartupInitialization(function cb() {
- do_check_eq(startup.sessionType, Ci.nsISessionStartup.NO_SESSION);
- do_test_finished();
- });
-} \ No newline at end of file
diff --git a/browser/components/sessionstore/test/unit/test_startup_session_async.js b/browser/components/sessionstore/test/unit/test_startup_session_async.js
deleted file mode 100644
index 459acf885..000000000
--- a/browser/components/sessionstore/test/unit/test_startup_session_async.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-// Test nsISessionStartup.sessionType in the following scenario:
-// - valid sessionstore.js;
-// - valid sessionCheckpoints.json with all checkpoints;
-// - the session store has been loaded
-
-function run_test() {
- let profd = do_get_profile();
-
- let sourceSession = do_get_file("data/sessionstore_valid.js");
- sourceSession.copyTo(profd, "sessionstore.js");
-
- let sourceCheckpoints = do_get_file("data/sessionCheckpoints_all.json");
- sourceCheckpoints.copyTo(profd, "sessionCheckpoints.json");
-
- do_test_pending();
- let startup = Cc["@mozilla.org/browser/sessionstartup;1"].
- getService(Ci.nsISessionStartup);
-
- afterSessionStartupInitialization(function cb() {
- do_check_eq(startup.sessionType, Ci.nsISessionStartup.DEFER_SESSION);
- do_test_finished();
- });
-}
diff --git a/browser/components/sessionstore/test/unit/xpcshell.ini b/browser/components/sessionstore/test/unit/xpcshell.ini
deleted file mode 100644
index 09980f877..000000000
--- a/browser/components/sessionstore/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,16 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files =
- data/sessionCheckpoints_all.json
- data/sessionstore_invalid.js
- data/sessionstore_valid.js
-
-[test_backup_once.js]
-[test_histogram_corrupt_files.js]
-[test_shutdown_cleanup.js]
-[test_startup_nosession_async.js]
-[test_startup_session_async.js]
-[test_startup_invalid_session.js]
diff --git a/browser/components/shell/test/.eslintrc.js b/browser/components/shell/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/shell/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/shell/test/browser.ini b/browser/components/shell/test/browser.ini
deleted file mode 100644
index 8f18415c0..000000000
--- a/browser/components/shell/test/browser.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-skip-if = os != "linux"
-
-[browser_420786.js]
-[browser_633221.js]
-
diff --git a/browser/components/shell/test/browser_420786.js b/browser/components/shell/test/browser_420786.js
deleted file mode 100644
index ae4521890..000000000
--- a/browser/components/shell/test/browser_420786.js
+++ /dev/null
@@ -1,88 +0,0 @@
-const DG_BACKGROUND = "/desktop/gnome/background"
-const DG_IMAGE_KEY = DG_BACKGROUND + "/picture_filename";
-const DG_OPTION_KEY = DG_BACKGROUND + "/picture_options";
-const DG_DRAW_BG_KEY = DG_BACKGROUND + "/draw_background";
-
-function onPageLoad() {
- gBrowser.selectedBrowser.removeEventListener("load", onPageLoad, true);
-
- var bs = Cc["@mozilla.org/intl/stringbundle;1"].
- getService(Ci.nsIStringBundleService);
- var brandName = bs.createBundle("chrome://branding/locale/brand.properties").
- GetStringFromName("brandShortName");
-
- var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIDirectoryServiceProvider);
- var homeDir = dirSvc.getFile("Home", {});
-
- var wpFile = homeDir.clone();
- wpFile.append(brandName + "_wallpaper.png");
-
- // Backup the existing wallpaper so that this test doesn't change the user's
- // settings.
- var wpFileBackup = homeDir.clone()
- wpFileBackup.append(brandName + "_wallpaper.png.backup");
-
- if (wpFileBackup.exists())
- wpFileBackup.remove(false);
-
- if (wpFile.exists())
- wpFile.copyTo(null, wpFileBackup.leafName);
-
- var shell = Cc["@mozilla.org/browser/shell-service;1"].
- getService(Ci.nsIShellService);
- var gconf = Cc["@mozilla.org/gnome-gconf-service;1"].
- getService(Ci.nsIGConfService);
-
- var prevImageKey = gconf.getString(DG_IMAGE_KEY);
- var prevOptionKey = gconf.getString(DG_OPTION_KEY);
- var prevDrawBgKey = gconf.getBool(DG_DRAW_BG_KEY);
-
- var image = content.document.images[0];
-
- function checkWallpaper(position, expectedGConfPosition) {
- shell.setDesktopBackground(image, position);
- ok(wpFile.exists(), "Wallpaper was written to disk");
- is(gconf.getString(DG_IMAGE_KEY), wpFile.path,
- "Wallpaper file GConf key is correct");
- is(gconf.getString(DG_OPTION_KEY), expectedGConfPosition,
- "Wallpaper position GConf key is correct");
- }
-
- checkWallpaper(Ci.nsIShellService.BACKGROUND_TILE, "wallpaper");
- checkWallpaper(Ci.nsIShellService.BACKGROUND_STRETCH, "stretched");
- checkWallpaper(Ci.nsIShellService.BACKGROUND_CENTER, "centered");
- checkWallpaper(Ci.nsIShellService.BACKGROUND_FILL, "zoom");
- checkWallpaper(Ci.nsIShellService.BACKGROUND_FIT, "scaled");
-
- // Restore GConf and wallpaper
-
- gconf.setString(DG_IMAGE_KEY, prevImageKey);
- gconf.setString(DG_OPTION_KEY, prevOptionKey);
- gconf.setBool(DG_DRAW_BG_KEY, prevDrawBgKey);
-
- wpFile.remove(false);
- if (wpFileBackup.exists())
- wpFileBackup.moveTo(null, wpFile.leafName);
-
- gBrowser.removeCurrentTab();
- finish();
-}
-
-function test() {
- try {
- // If GSettings is available, then the GConf tests
- // will fail
- Cc["@mozilla.org/gsettings-service;1"].
- getService(Ci.nsIGSettingsService).
- getCollectionForSchema("org.gnome.desktop.background");
- todo(false, "This test doesn't work when GSettings is available");
- return;
- } catch (e) { }
-
- gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.selectedBrowser.addEventListener("load", onPageLoad, true);
- content.location = "about:logo";
-
- waitForExplicitFinish();
-}
diff --git a/browser/components/shell/test/browser_633221.js b/browser/components/shell/test/browser_633221.js
deleted file mode 100644
index 7929e8098..000000000
--- a/browser/components/shell/test/browser_633221.js
+++ /dev/null
@@ -1,7 +0,0 @@
-Components.utils.import("resource:///modules/ShellService.jsm");
-
-function test() {
- ShellService.setDefaultBrowser(true, false);
- ok(ShellService.isDefaultBrowser(true, false), "we got here and are the default browser");
- ok(ShellService.isDefaultBrowser(true, true), "we got here and are the default browser");
-}
diff --git a/browser/components/shell/test/unit/.eslintrc.js b/browser/components/shell/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/shell/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/shell/test/unit/test_421977.js b/browser/components/shell/test/unit/test_421977.js
deleted file mode 100644
index 637db4b91..000000000
--- a/browser/components/shell/test/unit/test_421977.js
+++ /dev/null
@@ -1,123 +0,0 @@
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-const GCONF_BG_COLOR_KEY = "/desktop/gnome/background/primary_color";
-
-var gShell;
-var gGConf;
-
-/**
- * Converts from a rgb numerical color valule (r << 16 | g << 8 | b)
- * into a hex string in #RRGGBB format.
- */
-function colorToHex(aColor) {
- const rMask = 4294901760;
- const gMask = 65280;
- const bMask = 255;
-
- var r = (aColor & rMask) >> 16;
- var g = (aColor & gMask) >> 8;
- var b = (aColor & bMask);
-
- return "#" + [r, g, b].map(aInt =>
- aInt.toString(16).replace(/^(.)$/, "0$1"))
- .join("").toUpperCase();
-}
-
-/**
- * Converts a color string in #RRGGBB format to a rgb numerical color value
- * (r << 16 | g << 8 | b).
- */
-function hexToColor(aString) {
- return parseInt(aString.substring(1, 3), 16) << 16 |
- parseInt(aString.substring(3, 5), 16) << 8 |
- parseInt(aString.substring(5, 7), 16);
-}
-
-/**
- * Checks that setting the GConf background key to aGConfColor will
- * result in the Shell component returning a background color equals
- * to aExpectedShellColor in #RRGGBB format.
- */
-function checkGConfToShellColor(aGConfColor, aExpectedShellColor) {
-
- gGConf.setString(GCONF_BG_COLOR_KEY, aGConfColor);
- var shellColor = colorToHex(gShell.desktopBackgroundColor);
-
- do_check_eq(shellColor, aExpectedShellColor);
-}
-
-/**
- * Checks that setting the background color (in #RRGGBB format) using the Shell
- * component will result in having a GConf key for the background color set to
- * aExpectedGConfColor.
- */
-function checkShellToGConfColor(aShellColor, aExpectedGConfColor) {
-
- gShell.desktopBackgroundColor = hexToColor(aShellColor);
- var gconfColor = gGConf.getString(GCONF_BG_COLOR_KEY);
-
- do_check_eq(gconfColor, aExpectedGConfColor);
-}
-
-function run_test() {
-
- // This test is Linux specific for now
- if (!("@mozilla.org/gnome-gconf-service;1" in Cc))
- return;
-
- try {
- // If GSettings is available, then the GConf tests
- // will fail
- Cc["@mozilla.org/gsettings-service;1"].
- getService(Ci.nsIGSettingsService).
- getCollectionForSchema("org.gnome.desktop.background");
- return;
- } catch (e) { }
-
- gGConf = Cc["@mozilla.org/gnome-gconf-service;1"].
- getService(Ci.nsIGConfService);
-
- gShell = Cc["@mozilla.org/browser/shell-service;1"].
- getService(Ci.nsIShellService);
-
- // Save the original background color so that we can restore it
- // after the test.
- var origGConfColor = gGConf.getString(GCONF_BG_COLOR_KEY);
-
- try {
-
- checkGConfToShellColor("#000", "#000000");
- checkGConfToShellColor("#00f", "#0000FF");
- checkGConfToShellColor("#b2f", "#BB22FF");
- checkGConfToShellColor("#fff", "#FFFFFF");
-
- checkGConfToShellColor("#000000", "#000000");
- checkGConfToShellColor("#0000ff", "#0000FF");
- checkGConfToShellColor("#b002f0", "#B002F0");
- checkGConfToShellColor("#ffffff", "#FFFFFF");
-
- checkGConfToShellColor("#000000000", "#000000");
- checkGConfToShellColor("#00f00f00f", "#000000");
- checkGConfToShellColor("#aaabbbccc", "#AABBCC");
- checkGConfToShellColor("#fffffffff", "#FFFFFF");
-
- checkGConfToShellColor("#000000000000", "#000000");
- checkGConfToShellColor("#000f000f000f", "#000000");
- checkGConfToShellColor("#00ff00ff00ff", "#000000");
- checkGConfToShellColor("#aaaabbbbcccc", "#AABBCC");
- checkGConfToShellColor("#111122223333", "#112233");
- checkGConfToShellColor("#ffffffffffff", "#FFFFFF");
-
- checkShellToGConfColor("#000000", "#000000000000");
- checkShellToGConfColor("#0000FF", "#00000000ffff");
- checkShellToGConfColor("#FFFFFF", "#ffffffffffff");
- checkShellToGConfColor("#0A0B0C", "#0a0a0b0b0c0c");
- checkShellToGConfColor("#A0B0C0", "#a0a0b0b0c0c0");
- checkShellToGConfColor("#AABBCC", "#aaaabbbbcccc");
-
- } finally {
- gGConf.setString(GCONF_BG_COLOR_KEY, origGConfColor);
- }
-}
diff --git a/browser/components/shell/test/unit/xpcshell.ini b/browser/components/shell/test/unit/xpcshell.ini
deleted file mode 100644
index be00037e0..000000000
--- a/browser/components/shell/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-head =
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_421977.js]
diff --git a/browser/components/syncedtabs/test/browser/.eslintrc.js b/browser/components/syncedtabs/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/components/syncedtabs/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/syncedtabs/test/browser/browser.ini b/browser/components/syncedtabs/test/browser/browser.ini
deleted file mode 100644
index 02fa364f1..000000000
--- a/browser/components/syncedtabs/test/browser/browser.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[DEFAULT]
-support-files = head.js
-
-[browser_sidebar_syncedtabslist.js]
diff --git a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
deleted file mode 100644
index afbc00282..000000000
--- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
+++ /dev/null
@@ -1,410 +0,0 @@
-"use strict";
-
-const FIXTURE = [
- {
- "id": "7cqCr77ptzX3",
- "type": "client",
- "name": "zcarter's Nightly on MacBook-Pro-25",
- "isMobile": false,
- "tabs": [
- {
- "type": "tab",
- "title": "Firefox for Android — Mobile Web browser — More ways to customize and protect your privacy — Mozilla",
- "url": "https://www.mozilla.org/en-US/firefox/android/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar",
- "icon": "chrome://mozapps/skin/places/defaultFavicon.png",
- "client": "7cqCr77ptzX3",
- "lastUsed": 1452124677
- }
- ]
- },
- {
- "id": "2xU5h-4bkWqA",
- "type": "client",
- "name": "laptop",
- "isMobile": false,
- "tabs": [
- {
- "type": "tab",
- "title": "Firefox for iOS — Mobile Web browser for your iPhone, iPad and iPod touch — Mozilla",
- "url": "https://www.mozilla.org/en-US/firefox/ios/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar",
- "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico",
- "client": "2xU5h-4bkWqA",
- "lastUsed": 1451519425
- },
- {
- "type": "tab",
- "title": "Firefox Nightly First Run Page",
- "url": "https://www.mozilla.org/en-US/firefox/nightly/firstrun/?oldversion=45.0a1",
- "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon-nightly.560395bbb2e1.png",
- "client": "2xU5h-4bkWqA",
- "lastUsed": 1451519420
- },
- {
- // Should appear first for this client.
- "type": "tab",
- "title": "Mozilla Developer Network",
- "url": "https://developer.mozilla.org/en-US/",
- "icon": "moz-anno:favicon:https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png",
- "client": "2xU5h-4bkWqA",
- "lastUsed": 1451519725
- }
- ]
- },
- {
- "id": "OL3EJCsdb2JD",
- "type": "client",
- "name": "desktop",
- "isMobile": false,
- "tabs": []
- }
-];
-
-let originalSyncedTabsInternal = null;
-
-function* testClean() {
- let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
- let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
- syncedTabsDeckComponent._accountStatus.restore();
- SyncedTabs._internal.getTabClients.restore();
- SyncedTabs._internal = originalSyncedTabsInternal;
-
- yield new Promise(resolve => {
- window.SidebarUI.browser.contentWindow.addEventListener("unload", function listener() {
- window.SidebarUI.browser.contentWindow.removeEventListener("unload", listener);
- resolve();
- });
- SidebarUI.hide();
- });
-}
-
-add_task(function* testSyncedTabsSidebarList() {
- yield SidebarUI.show('viewTabsSidebar');
-
- Assert.equal(SidebarUI.currentID, "viewTabsSidebar", "Sidebar should have SyncedTabs loaded");
-
- let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
- let SyncedTabs = SidebarUI.browser.contentWindow.SyncedTabs;
-
- Assert.ok(syncedTabsDeckComponent, "component exists");
-
- originalSyncedTabsInternal = SyncedTabs._internal;
- SyncedTabs._internal = {
- isConfiguredToSyncTabs: true,
- hasSyncedThisSession: true,
- getTabClients() { return Promise.resolve([]) },
- syncTabs() { return Promise.resolve(); },
- };
-
- sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true));
- sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {})));
-
- yield syncedTabsDeckComponent.updatePanel();
- // This is a hacky way of waiting for the view to render. The view renders
- // after the following promise (a different instance of which is triggered
- // in updatePanel) resolves, so we wait for it here as well
- yield syncedTabsDeckComponent.tabListComponent._store.getData();
-
- Assert.ok(SyncedTabs._internal.getTabClients.called, "get clients called");
-
- let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
-
-
- Assert.ok(selectedPanel.classList.contains("tabs-container"),
- "tabs panel is selected");
-
- Assert.equal(selectedPanel.querySelectorAll(".tab").length, 4,
- "four tabs listed");
- Assert.equal(selectedPanel.querySelectorAll(".client").length, 3,
- "three clients listed");
- Assert.equal(selectedPanel.querySelectorAll(".client")[2].querySelectorAll(".empty").length, 1,
- "third client is empty");
-
- // Verify that the tabs are sorted by last used time.
- var expectedTabIndices = [[0], [2, 0, 1]];
- Array.prototype.forEach.call(selectedPanel.querySelectorAll(".client"), (clientNode, i) => {
- checkItem(clientNode, FIXTURE[i]);
- Array.prototype.forEach.call(clientNode.querySelectorAll(".tab"), (tabNode, j) => {
- let tabIndex = expectedTabIndices[i][j];
- checkItem(tabNode, FIXTURE[i].tabs[tabIndex]);
- });
- });
-
-});
-
-add_task(testClean);
-
-add_task(function* testSyncedTabsSidebarFilteredList() {
- yield SidebarUI.show('viewTabsSidebar');
- let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
- let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
-
- Assert.ok(syncedTabsDeckComponent, "component exists");
-
- originalSyncedTabsInternal = SyncedTabs._internal;
- SyncedTabs._internal = {
- isConfiguredToSyncTabs: true,
- hasSyncedThisSession: true,
- getTabClients() { return Promise.resolve([]) },
- syncTabs() { return Promise.resolve(); },
- };
-
- sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true));
- sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {})));
-
- yield syncedTabsDeckComponent.updatePanel();
- // This is a hacky way of waiting for the view to render. The view renders
- // after the following promise (a different instance of which is triggered
- // in updatePanel) resolves, so we wait for it here as well
- yield syncedTabsDeckComponent.tabListComponent._store.getData();
-
- let filterInput = syncedTabsDeckComponent._window.document.querySelector(".tabsFilter");
- filterInput.value = "filter text";
- filterInput.blur();
-
- yield syncedTabsDeckComponent.tabListComponent._store.getData("filter text");
-
- let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("tabs-container"),
- "tabs panel is selected");
-
- Assert.equal(selectedPanel.querySelectorAll(".tab").length, 4,
- "four tabs listed");
- Assert.equal(selectedPanel.querySelectorAll(".client").length, 0,
- "no clients are listed");
-
- Assert.equal(filterInput.value, "filter text",
- "filter text box has correct value");
-
- // Tabs should not be sorted when filter is active.
- let FIXTURE_TABS = FIXTURE.reduce((prev, client) => prev.concat(client.tabs), []);
-
- Array.prototype.forEach.call(selectedPanel.querySelectorAll(".tab"), (tabNode, i) => {
- checkItem(tabNode, FIXTURE_TABS[i]);
- });
-
- // Removing the filter should resort tabs.
- FIXTURE_TABS.sort((a, b) => b.lastUsed - a.lastUsed);
- yield syncedTabsDeckComponent.tabListComponent._store.getData();
- Array.prototype.forEach.call(selectedPanel.querySelectorAll(".tab"), (tabNode, i) => {
- checkItem(tabNode, FIXTURE_TABS[i]);
- });
-});
-
-add_task(testClean);
-
-add_task(function* testSyncedTabsSidebarStatus() {
- let accountExists = false;
-
- yield SidebarUI.show('viewTabsSidebar');
- let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
- let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
-
- originalSyncedTabsInternal = SyncedTabs._internal;
- SyncedTabs._internal = {
- isConfiguredToSyncTabs: false,
- hasSyncedThisSession: false,
- getTabClients() {},
- syncTabs() { return Promise.resolve(); },
- };
-
- Assert.ok(syncedTabsDeckComponent, "component exists");
-
- sinon.spy(syncedTabsDeckComponent, "updatePanel");
- sinon.spy(syncedTabsDeckComponent, "observe");
-
- sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.reject("Test error"));
- yield syncedTabsDeckComponent.updatePanel();
-
- let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("notAuthedInfo"),
- "not-authed panel is selected on auth error");
-
- syncedTabsDeckComponent._accountStatus.restore();
- sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(accountExists));
- yield syncedTabsDeckComponent.updatePanel();
- selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("notAuthedInfo"),
- "not-authed panel is selected");
-
- accountExists = true;
- yield syncedTabsDeckComponent.updatePanel();
- selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("tabs-disabled"),
- "tabs disabled panel is selected");
-
- SyncedTabs._internal.isConfiguredToSyncTabs = true;
- yield syncedTabsDeckComponent.updatePanel();
- selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("tabs-fetching"),
- "tabs fetch panel is selected");
-
- SyncedTabs._internal.hasSyncedThisSession = true;
- sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve([]));
- yield syncedTabsDeckComponent.updatePanel();
- selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("singleDeviceInfo"),
- "tabs fetch panel is selected");
-
- SyncedTabs._internal.getTabClients.restore();
- sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve([{id: "mock"}]));
- yield syncedTabsDeckComponent.updatePanel();
- selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- Assert.ok(selectedPanel.classList.contains("tabs-container"),
- "tabs panel is selected");
-});
-
-add_task(testClean);
-
-add_task(function* testSyncedTabsSidebarContextMenu() {
- yield SidebarUI.show('viewTabsSidebar');
- let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
- let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
-
- Assert.ok(syncedTabsDeckComponent, "component exists");
-
- originalSyncedTabsInternal = SyncedTabs._internal;
- SyncedTabs._internal = {
- isConfiguredToSyncTabs: true,
- hasSyncedThisSession: true,
- getTabClients() { return Promise.resolve([]) },
- syncTabs() { return Promise.resolve(); },
- };
-
- sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true));
- sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {})));
-
- yield syncedTabsDeckComponent.updatePanel();
- // This is a hacky way of waiting for the view to render. The view renders
- // after the following promise (a different instance of which is triggered
- // in updatePanel) resolves, so we wait for it here as well
- yield syncedTabsDeckComponent.tabListComponent._store.getData();
-
- info("Right-clicking the search box should show text-related actions");
- let filterMenuItems = [
- "menuitem[cmd=cmd_undo]",
- "menuseparator",
- // We don't check whether the commands are enabled due to platform
- // differences. On OS X and Windows, "cut" and "copy" are always enabled
- // for HTML inputs; on Linux, they're only enabled if text is selected.
- "menuitem[cmd=cmd_cut]",
- "menuitem[cmd=cmd_copy]",
- "menuitem[cmd=cmd_paste]",
- "menuitem[cmd=cmd_delete]",
- "menuseparator",
- "menuitem[cmd=cmd_selectAll]",
- "menuseparator",
- "menuitem#syncedTabsRefreshFilter",
- ];
- yield* testContextMenu(syncedTabsDeckComponent,
- "#SyncedTabsSidebarTabsFilterContext",
- ".tabsFilter",
- filterMenuItems);
-
- info("Right-clicking a tab should show additional actions");
- let tabMenuItems = [
- ["menuitem#syncedTabsOpenSelected", { hidden: false }],
- ["menuitem#syncedTabsOpenSelectedInTab", { hidden: false }],
- ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: false }],
- ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: false }],
- ["menuseparator", { hidden: false }],
- ["menuitem#syncedTabsBookmarkSelected", { hidden: false }],
- ["menuitem#syncedTabsCopySelected", { hidden: false }],
- ["menuseparator", { hidden: false }],
- ["menuitem#syncedTabsRefresh", { hidden: false }],
- ];
- yield* testContextMenu(syncedTabsDeckComponent,
- "#SyncedTabsSidebarContext",
- "#tab-7cqCr77ptzX3-0",
- tabMenuItems);
-
- info("Right-clicking a client shouldn't show any actions");
- let sidebarMenuItems = [
- ["menuitem#syncedTabsOpenSelected", { hidden: true }],
- ["menuitem#syncedTabsOpenSelectedInTab", { hidden: true }],
- ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: true }],
- ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: true }],
- ["menuseparator", { hidden: true }],
- ["menuitem#syncedTabsBookmarkSelected", { hidden: true }],
- ["menuitem#syncedTabsCopySelected", { hidden: true }],
- ["menuseparator", { hidden: true }],
- ["menuitem#syncedTabsRefresh", { hidden: false }],
- ];
- yield* testContextMenu(syncedTabsDeckComponent,
- "#SyncedTabsSidebarContext",
- "#item-OL3EJCsdb2JD",
- sidebarMenuItems);
-});
-
-add_task(testClean);
-
-function checkItem(node, item) {
- Assert.ok(node.classList.contains("item"),
- "Node should have .item class");
- if (item.client) {
- // tab items
- Assert.equal(node.querySelector(".item-title").textContent, item.title,
- "Node's title element's text should match item title");
- Assert.ok(node.classList.contains("tab"),
- "Node should have .tab class");
- Assert.equal(node.dataset.url, item.url,
- "Node's URL should match item URL");
- Assert.equal(node.getAttribute("title"), item.title + "\n" + item.url,
- "Tab node should have correct title attribute");
- } else {
- // client items
- Assert.equal(node.querySelector(".item-title").textContent, item.name,
- "Node's title element's text should match client name");
- Assert.ok(node.classList.contains("client"),
- "Node should have .client class");
- Assert.equal(node.dataset.id, item.id,
- "Node's ID should match item ID");
- }
-}
-
-function* testContextMenu(syncedTabsDeckComponent, contextSelector, triggerSelector, menuSelectors) {
- let contextMenu = document.querySelector(contextSelector);
- let triggerElement = syncedTabsDeckComponent._window.document.querySelector(triggerSelector);
- let isClosed = triggerElement.classList.contains("closed");
-
- let promisePopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
-
- let chromeWindow = triggerElement.ownerGlobal.top;
- let rect = triggerElement.getBoundingClientRect();
- let contentRect = chromeWindow.SidebarUI.browser.getBoundingClientRect();
- // The offsets in `rect` are relative to the content window, but
- // `synthesizeMouseAtPoint` calls `nsIDOMWindowUtils.sendMouseEvent`,
- // which interprets the offsets relative to the containing *chrome* window.
- // This means we need to account for the width and height of any elements
- // outside the `browser` element, like `sidebarheader`.
- let offsetX = contentRect.x + rect.x + (rect.width / 2);
- let offsetY = contentRect.y + rect.y + (rect.height / 4);
-
- yield EventUtils.synthesizeMouseAtPoint(offsetX, offsetY, {
- type: "contextmenu",
- button: 2,
- }, chromeWindow);
- yield promisePopupShown;
- is(triggerElement.classList.contains("closed"), isClosed,
- "Showing the context menu shouldn't toggle the tab list");
- checkChildren(contextMenu, menuSelectors);
-
- let promisePopupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- contextMenu.hidePopup();
- yield promisePopupHidden;
-}
-
-function checkChildren(node, selectors) {
- is(node.children.length, selectors.length, "Menu item count doesn't match");
- for (let index = 0; index < node.children.length; index++) {
- let child = node.children[index];
- let [selector, props] = [].concat(selectors[index]);
- ok(selector, `Node at ${index} should have selector`);
- ok(child.matches(selector), `Node ${
- index} should match ${selector}`);
- if (props) {
- Object.keys(props).forEach(prop => {
- is(child[prop], props[prop], `${prop} value at ${index} should match`);
- });
- }
- }
-}
diff --git a/browser/components/syncedtabs/test/browser/head.js b/browser/components/syncedtabs/test/browser/head.js
deleted file mode 100644
index 40e36123e..000000000
--- a/browser/components/syncedtabs/test/browser/head.js
+++ /dev/null
@@ -1,19 +0,0 @@
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-
-// Load mocking/stubbing library, sinon
-// docs: http://sinonjs.org/docs/
-/* global sinon */
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
-loader.loadSubScript("resource://testing-common/sinon-1.16.1.js");
-
-registerCleanupFunction(function*() {
- // Cleanup window or the test runner will throw an error
- delete window.sinon;
- delete window.setImmediate;
- delete window.clearImmediate;
-});
diff --git a/browser/components/syncedtabs/test/xpcshell/.eslintrc.js b/browser/components/syncedtabs/test/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/syncedtabs/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/syncedtabs/test/xpcshell/head.js b/browser/components/syncedtabs/test/xpcshell/head.js
deleted file mode 100644
index 00055231c..000000000
--- a/browser/components/syncedtabs/test/xpcshell/head.js
+++ /dev/null
@@ -1,29 +0,0 @@
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "FxAccountsCommon", function () {
- return Components.utils.import("resource://gre/modules/FxAccountsCommon.js", {});
-});
-
-Cu.import("resource://gre/modules/Timer.jsm");
-
-do_get_profile(); // fxa needs a profile directory for storage.
-
-// Create a window polyfill so sinon can load
-let window = {
- document: {},
- location: {},
- setTimeout: setTimeout,
- setInterval: setInterval,
- clearTimeout: clearTimeout,
- clearinterval: clearInterval
-};
-let self = window;
-
-// Load mocking/stubbing library, sinon
-// docs: http://sinonjs.org/docs/
-/* global sinon */
-let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
-loader.loadSubScript("resource://testing-common/sinon-1.16.1.js");
diff --git a/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js b/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js
deleted file mode 100644
index bc73ac621..000000000
--- a/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-let { EventEmitter } = Cu.import("resource:///modules/syncedtabs/EventEmitter.jsm", {});
-
-add_task(function* testSingleListener() {
- let eventEmitter = new EventEmitter();
- let spy = sinon.spy();
-
- eventEmitter.on("click", spy);
- eventEmitter.emit("click", "foo", "bar");
- Assert.ok(spy.calledOnce);
- Assert.ok(spy.calledWith("foo", "bar"));
-
- eventEmitter.off("click", spy);
- eventEmitter.emit("click");
- Assert.ok(spy.calledOnce);
-});
-
-add_task(function* testMultipleListeners() {
- let eventEmitter = new EventEmitter();
- let spy1 = sinon.spy();
- let spy2 = sinon.spy();
-
- eventEmitter.on("some_event", spy1);
- eventEmitter.on("some_event", spy2);
- eventEmitter.emit("some_event");
- Assert.ok(spy1.calledOnce);
- Assert.ok(spy2.calledOnce);
-
- eventEmitter.off("some_event", spy1);
- eventEmitter.emit("some_event");
- Assert.ok(spy1.calledOnce);
- Assert.ok(spy2.calledTwice);
-});
-
diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js
deleted file mode 100644
index 3d748b33c..000000000
--- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js
+++ /dev/null
@@ -1,218 +0,0 @@
-"use strict";
-
-let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-let { SyncedTabsDeckComponent } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckComponent.js", {});
-let { TabListComponent } = Cu.import("resource:///modules/syncedtabs/TabListComponent.js", {});
-let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {});
-let { SyncedTabsDeckStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckStore.js", {});
-let { TabListView } = Cu.import("resource:///modules/syncedtabs/TabListView.js", {});
-let { DeckView } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckView.js", {});
-
-
-add_task(function* testInitUninit() {
- let deckStore = new SyncedTabsDeckStore();
- let listComponent = {};
-
- let ViewMock = sinon.stub();
- let view = {render: sinon.spy(), destroy: sinon.spy(), container: {}};
- ViewMock.returns(view);
-
- sinon.stub(SyncedTabs, "syncTabs", () => Promise.resolve());
-
- sinon.spy(deckStore, "on");
- sinon.stub(deckStore, "setPanels");
-
- let component = new SyncedTabsDeckComponent({
- window,
- deckStore,
- listComponent,
- SyncedTabs,
- DeckView: ViewMock,
- });
-
- sinon.stub(component, "updatePanel");
-
- component.init();
-
- Assert.ok(SyncedTabs.syncTabs.called);
- SyncedTabs.syncTabs.restore();
-
- Assert.ok(ViewMock.calledWithNew(), "view is instantiated");
- Assert.equal(ViewMock.args[0][0], window);
- Assert.equal(ViewMock.args[0][1], listComponent);
- Assert.ok(ViewMock.args[0][2].onAndroidClick,
- "view is passed onAndroidClick prop");
- Assert.ok(ViewMock.args[0][2].oniOSClick,
- "view is passed oniOSClick prop");
- Assert.ok(ViewMock.args[0][2].onSyncPrefClick,
- "view is passed onSyncPrefClick prop");
-
- Assert.equal(component.container, view.container,
- "component returns view's container");
-
- Assert.ok(deckStore.on.calledOnce, "listener is added to store");
- Assert.equal(deckStore.on.args[0][0], "change");
- // Object.values only in nightly
- let values = Object.keys(component.PANELS).map(k => component.PANELS[k]);
- Assert.ok(deckStore.setPanels.calledWith(values),
- "panels are set on deck store");
-
- Assert.ok(component.updatePanel.called);
-
- deckStore.emit("change", "mock state");
- Assert.ok(view.render.calledWith("mock state"),
- "view.render is called on state change");
-
- component.uninit();
-
- Assert.ok(view.destroy.calledOnce, "view is destroyed on uninit");
-});
-
-
-function waitForObserver() {
- return new Promise((resolve, reject) => {
- Services.obs.addObserver((subject, topic) => {
- resolve();
- }, SyncedTabs.TOPIC_TABS_CHANGED, false);
- });
-}
-
-add_task(function* testObserver() {
- let deckStore = new SyncedTabsDeckStore();
- let listStore = new SyncedTabsListStore(SyncedTabs);
- let listComponent = {};
-
- let ViewMock = sinon.stub();
- let view = {render: sinon.spy(), destroy: sinon.spy(), container: {}};
- ViewMock.returns(view);
-
- sinon.stub(SyncedTabs, "syncTabs", () => Promise.resolve());
-
- sinon.spy(deckStore, "on");
- sinon.stub(deckStore, "setPanels");
-
- sinon.stub(listStore, "getData");
-
- let component = new SyncedTabsDeckComponent({
- window,
- deckStore,
- listStore,
- listComponent,
- SyncedTabs,
- DeckView: ViewMock,
- });
-
- sinon.spy(component, "observe");
- sinon.stub(component, "updatePanel");
-
- component.init();
- SyncedTabs.syncTabs.restore();
- Assert.ok(component.updatePanel.called, "triggers panel update during init");
-
- Services.obs.notifyObservers(null, SyncedTabs.TOPIC_TABS_CHANGED, "");
-
- Assert.ok(component.observe.calledWith(null, SyncedTabs.TOPIC_TABS_CHANGED, ""),
- "component is notified");
-
- Assert.ok(listStore.getData.called, "gets list data");
- Assert.ok(component.updatePanel.calledTwice, "triggers panel update");
-
- Services.obs.notifyObservers(null, FxAccountsCommon.ONLOGIN_NOTIFICATION, "");
-
- Assert.ok(component.observe.calledWith(null, FxAccountsCommon.ONLOGIN_NOTIFICATION, ""),
- "component is notified of login");
- Assert.equal(component.updatePanel.callCount, 3, "triggers panel update again");
-});
-
-add_task(function* testPanelStatus() {
- let deckStore = new SyncedTabsDeckStore();
- let listStore = new SyncedTabsListStore();
- let listComponent = {};
- let fxAccounts = {
- accountStatus() {}
- };
- let SyncedTabsMock = {
- getTabClients() {}
- };
-
- sinon.stub(listStore, "getData");
-
-
- let component = new SyncedTabsDeckComponent({
- fxAccounts,
- deckStore,
- listComponent,
- SyncedTabs: SyncedTabsMock,
- });
-
- let isAuthed = false;
- sinon.stub(fxAccounts, "accountStatus", () => Promise.resolve(isAuthed));
- let result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.NOT_AUTHED_INFO);
-
- isAuthed = true;
-
- SyncedTabsMock.isConfiguredToSyncTabs = false;
- result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.TABS_DISABLED);
-
- SyncedTabsMock.isConfiguredToSyncTabs = true;
-
- SyncedTabsMock.hasSyncedThisSession = false;
- result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.TABS_FETCHING);
-
- SyncedTabsMock.hasSyncedThisSession = true;
-
- let clients = [];
- sinon.stub(SyncedTabsMock, "getTabClients", () => Promise.resolve(clients));
- result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.SINGLE_DEVICE_INFO);
-
- clients = ["mock-client"];
- result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.TABS_CONTAINER);
-
- fxAccounts.accountStatus.restore();
- sinon.stub(fxAccounts, "accountStatus", () => Promise.reject("err"));
- result = yield component.getPanelStatus();
- Assert.equal(result, component.PANELS.NOT_AUTHED_INFO);
-
- sinon.stub(component, "getPanelStatus", () => Promise.resolve("mock-panelId"));
- sinon.spy(deckStore, "selectPanel");
- yield component.updatePanel();
- Assert.ok(deckStore.selectPanel.calledWith("mock-panelId"));
-});
-
-add_task(function* testActions() {
- let windowMock = {
- openUILink() {},
- };
- let chromeWindowMock = {
- gSyncUI: {
- openSetup() {}
- }
- };
- sinon.spy(windowMock, "openUILink");
- sinon.spy(chromeWindowMock.gSyncUI, "openSetup");
-
- let getChromeWindowMock = sinon.stub();
- getChromeWindowMock.returns(chromeWindowMock);
-
- let component = new SyncedTabsDeckComponent({
- window: windowMock,
- getChromeWindowMock
- });
-
- let href = Services.prefs.getCharPref("identity.mobilepromo.android") + "synced-tabs-sidebar";
- component.openAndroidLink("mock-event");
- Assert.ok(windowMock.openUILink.calledWith(href, "mock-event"));
-
- href = Services.prefs.getCharPref("identity.mobilepromo.ios") + "synced-tabs-sidebar";
- component.openiOSLink("mock-event");
- Assert.ok(windowMock.openUILink.calledWith(href, "mock-event"));
-
- component.openSyncPrefs();
- Assert.ok(getChromeWindowMock.calledWith(windowMock));
- Assert.ok(chromeWindowMock.gSyncUI.openSetup.called);
-});
diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js
deleted file mode 100644
index 69abb4024..000000000
--- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js
+++ /dev/null
@@ -1,64 +0,0 @@
-"use strict";
-
-let { SyncedTabsDeckStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckStore.js", {});
-
-add_task(function* testSelectUnkownPanel() {
- let deckStore = new SyncedTabsDeckStore();
- let spy = sinon.spy();
-
- deckStore.on("change", spy);
- deckStore.selectPanel("foo");
-
- Assert.ok(!spy.called);
-});
-
-add_task(function* testSetPanels() {
- let deckStore = new SyncedTabsDeckStore();
- let spy = sinon.spy();
-
- deckStore.on("change", spy);
- deckStore.setPanels(["panel1", "panel2"]);
-
- Assert.ok(spy.calledWith({
- panels: [
- { id: "panel1", selected: false },
- { id: "panel2", selected: false },
- ],
- isUpdatable: false
- }));
-});
-
-add_task(function* testSelectPanel() {
- let deckStore = new SyncedTabsDeckStore();
- let spy = sinon.spy();
-
- deckStore.setPanels(["panel1", "panel2"]);
-
- deckStore.on("change", spy);
- deckStore.selectPanel("panel2");
-
- Assert.ok(spy.calledWith({
- panels: [
- { id: "panel1", selected: false },
- { id: "panel2", selected: true },
- ],
- isUpdatable: true
- }));
-
- deckStore.selectPanel("panel2");
- Assert.ok(spy.calledOnce, "doesn't trigger unless panel changes");
-});
-
-add_task(function* testSetPanelsSameArray() {
- let deckStore = new SyncedTabsDeckStore();
- let spy = sinon.spy();
- deckStore.on("change", spy);
-
- let panels = ["panel1", "panel2"];
-
- deckStore.setPanels(panels);
- deckStore.setPanels(panels);
-
- Assert.ok(spy.calledOnce, "doesn't trigger unless set of panels changes");
-});
-
diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js
deleted file mode 100644
index 51580235f..000000000
--- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js
+++ /dev/null
@@ -1,266 +0,0 @@
-"use strict";
-
-let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {});
-
-const FIXTURE = [
- {
- "id": "2xU5h-4bkWqA",
- "type": "client",
- "name": "laptop",
- "isMobile": false,
- "tabs": [
- {
- "type": "tab",
- "title": "Firefox for iOS — Mobile Web browser for your iPhone, iPad and iPod touch — Mozilla",
- "url": "https://www.mozilla.org/en-US/firefox/ios/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar",
- "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico",
- "client": "2xU5h-4bkWqA",
- "lastUsed": 1451519425
- },
- {
- "type": "tab",
- "title": "Firefox Nightly First Run Page",
- "url": "https://www.mozilla.org/en-US/firefox/nightly/firstrun/?oldversion=45.0a1",
- "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon-nightly.560395bbb2e1.png",
- "client": "2xU5h-4bkWqA",
- "lastUsed": 1451519420
- }
- ]
- },
- {
- "id": "OL3EJCsdb2JD",
- "type": "client",
- "name": "desktop",
- "isMobile": false,
- "tabs": []
- }
-];
-
-add_task(function* testGetDataEmpty() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve([]);
- });
- store.on("change", spy);
-
- yield store.getData();
-
- Assert.ok(SyncedTabs.getTabClients.calledWith(""));
- Assert.ok(spy.calledWith({
- clients: [],
- canUpdateAll: false,
- canUpdateInput: false,
- filter: "",
- inputFocused: false
- }));
-
- yield store.getData("filter");
-
- Assert.ok(SyncedTabs.getTabClients.calledWith("filter"));
- Assert.ok(spy.calledWith({
- clients: [],
- canUpdateAll: false,
- canUpdateInput: true,
- filter: "filter",
- inputFocused: false
- }));
-
- SyncedTabs.getTabClients.restore();
-});
-
-add_task(function* testRowSelectionWithoutFilter() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve(FIXTURE);
- });
-
- yield store.getData();
- SyncedTabs.getTabClients.restore();
-
- store.on("change", spy);
-
- store.selectRow(0, -1);
- Assert.ok(spy.args[0][0].canUpdateAll, "can update the whole view");
- Assert.ok(spy.args[0][0].clients[0].selected, "first client is selected");
-
- store.moveSelectionUp();
- Assert.ok(spy.calledOnce,
- "can't move up past first client, no change triggered");
-
- store.selectRow(0, 0);
- Assert.ok(spy.args[1][0].clients[0].tabs[0].selected,
- "first tab of first client is selected");
-
- store.selectRow(0, 0);
- Assert.ok(spy.calledTwice, "selecting same row doesn't trigger change");
-
- store.selectRow(0, 1);
- Assert.ok(spy.args[2][0].clients[0].tabs[1].selected,
- "second tab of first client is selected");
-
- store.selectRow(1);
- Assert.ok(spy.args[3][0].clients[1].selected, "second client is selected");
-
- store.moveSelectionDown();
- Assert.equal(spy.callCount, 4,
- "can't move selection down past last client, no change triggered");
-
- store.moveSelectionUp();
- Assert.equal(spy.callCount, 5,
- "changed");
- Assert.ok(spy.args[4][0].clients[0].tabs[FIXTURE[0].tabs.length - 1].selected,
- "move selection up from client selects last tab of previous client");
-
- store.moveSelectionUp();
- Assert.ok(spy.args[5][0].clients[0].tabs[FIXTURE[0].tabs.length - 2].selected,
- "move selection up from tab selects previous tab of client");
-});
-
-
-add_task(function* testToggleBranches() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve(FIXTURE);
- });
-
- yield store.getData();
- SyncedTabs.getTabClients.restore();
-
- store.selectRow(0);
- store.on("change", spy);
-
- let clientId = FIXTURE[0].id;
- store.closeBranch(clientId);
- Assert.ok(spy.args[0][0].clients[0].closed, "first client is closed");
-
- store.openBranch(clientId);
- Assert.ok(!spy.args[1][0].clients[0].closed, "first client is open");
-
- store.toggleBranch(clientId);
- Assert.ok(spy.args[2][0].clients[0].closed, "first client is toggled closed");
-
- store.moveSelectionDown();
- Assert.ok(spy.args[3][0].clients[1].selected,
- "selection skips tabs if client is closed");
-
- store.moveSelectionUp();
- Assert.ok(spy.args[4][0].clients[0].selected,
- "selection skips tabs if client is closed");
-});
-
-
-add_task(function* testRowSelectionWithFilter() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve(FIXTURE);
- });
-
- yield store.getData("filter");
- SyncedTabs.getTabClients.restore();
-
- store.on("change", spy);
-
- store.selectRow(0);
- Assert.ok(spy.args[0][0].clients[0].tabs[0].selected, "first tab is selected");
-
- store.moveSelectionUp();
- Assert.ok(spy.calledOnce,
- "can't move up past first tab, no change triggered");
-
- store.moveSelectionDown();
- Assert.ok(spy.args[1][0].clients[0].tabs[1].selected,
- "selection skips tabs if client is closed");
-
- store.moveSelectionDown();
- Assert.equal(spy.callCount, 2,
- "can't move selection down past last tab, no change triggered");
-
- store.selectRow(1);
- Assert.equal(spy.callCount, 2,
- "doesn't trigger change if same row selected");
-
-});
-
-
-add_task(function* testFilterAndClearFilter() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve(FIXTURE);
- });
- store.on("change", spy);
-
- yield store.getData("filter");
-
- Assert.ok(SyncedTabs.getTabClients.calledWith("filter"));
- Assert.ok(!spy.args[0][0].canUpdateAll, "can't update all");
- Assert.ok(spy.args[0][0].canUpdateInput, "can update just input");
-
- store.selectRow(0);
-
- Assert.equal(spy.args[1][0].filter, "filter");
- Assert.ok(spy.args[1][0].clients[0].tabs[0].selected,
- "tab is selected");
-
- yield store.clearFilter();
-
- Assert.ok(SyncedTabs.getTabClients.calledWith(""));
- Assert.ok(!spy.args[2][0].canUpdateAll, "can't update all");
- Assert.ok(!spy.args[2][0].canUpdateInput, "can't just update input");
-
- Assert.equal(spy.args[2][0].filter, "");
- Assert.ok(!spy.args[2][0].clients[0].tabs[0].selected,
- "tab is no longer selected");
-
- SyncedTabs.getTabClients.restore();
-});
-
-add_task(function* testFocusBlurInput() {
- let store = new SyncedTabsListStore(SyncedTabs);
- let spy = sinon.spy();
-
- sinon.stub(SyncedTabs, "getTabClients", () => {
- return Promise.resolve(FIXTURE);
- });
- store.on("change", spy);
-
- yield store.getData();
- SyncedTabs.getTabClients.restore();
-
- Assert.ok(!spy.args[0][0].canUpdateAll, "must rerender all");
-
- store.selectRow(0);
- Assert.ok(!spy.args[1][0].inputFocused,
- "input is not focused");
- Assert.ok(spy.args[1][0].clients[0].selected,
- "client is selected");
- Assert.ok(spy.args[1][0].clients[0].focused,
- "client is focused");
-
- store.focusInput();
- Assert.ok(spy.args[2][0].inputFocused,
- "input is focused");
- Assert.ok(spy.args[2][0].clients[0].selected,
- "client is still selected");
- Assert.ok(!spy.args[2][0].clients[0].focused,
- "client is no longer focused");
-
- store.blurInput();
- Assert.ok(!spy.args[3][0].inputFocused,
- "input is not focused");
- Assert.ok(spy.args[3][0].clients[0].selected,
- "client is selected");
- Assert.ok(spy.args[3][0].clients[0].focused,
- "client is focused");
-});
-
diff --git a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js b/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
deleted file mode 100644
index 0b0665a1b..000000000
--- a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
+++ /dev/null
@@ -1,155 +0,0 @@
-"use strict";
-
-let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-let { TabListComponent } = Cu.import("resource:///modules/syncedtabs/TabListComponent.js", {});
-let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {});
-let { View } = Cu.import("resource:///modules/syncedtabs/TabListView.js", {});
-
-const ACTION_METHODS = [
- "onSelectRow",
- "onOpenTab",
- "onOpenTabs",
- "onMoveSelectionDown",
- "onMoveSelectionUp",
- "onToggleBranch",
- "onBookmarkTab",
- "onSyncRefresh",
- "onFilter",
- "onClearFilter",
- "onFilterFocus",
- "onFilterBlur",
-];
-
-add_task(function* testInitUninit() {
- let store = new SyncedTabsListStore();
- let ViewMock = sinon.stub();
- let view = {render() {}, destroy() {}};
-
- ViewMock.returns(view);
-
- sinon.spy(view, 'render');
- sinon.spy(view, 'destroy');
-
- sinon.spy(store, "on");
- sinon.stub(store, "getData");
- sinon.stub(store, "focusInput");
-
- let component = new TabListComponent({window, store, View: ViewMock, SyncedTabs});
-
- for (let action of ACTION_METHODS) {
- sinon.stub(component, action);
- }
-
- component.init();
-
- Assert.ok(ViewMock.calledWithNew(), "view is instantiated");
- Assert.ok(store.on.calledOnce, "listener is added to store");
- Assert.equal(store.on.args[0][0], "change");
- Assert.ok(view.render.calledWith({clients: []}),
- "render is called on view instance");
- Assert.ok(store.getData.calledOnce, "store gets initial data");
- Assert.ok(store.focusInput.calledOnce, "input field is focused");
-
- for (let method of ACTION_METHODS) {
- let action = ViewMock.args[0][1][method];
- Assert.ok(action, method + " action is passed to View");
- action("foo", "bar");
- Assert.ok(component[method].calledWith("foo", "bar"),
- method + " action passed to View triggers the component method with args");
- }
-
- store.emit("change", "mock state");
- Assert.ok(view.render.secondCall.calledWith("mock state"),
- "view.render is called on state change");
-
- component.uninit();
- Assert.ok(view.destroy.calledOnce, "view is destroyed on uninit");
-});
-
-add_task(function* testActions() {
- let store = new SyncedTabsListStore();
- let chromeWindowMock = {
- gBrowser: {
- loadTabs() {},
- },
- };
- let getChromeWindowMock = sinon.stub();
- getChromeWindowMock.returns(chromeWindowMock);
- let clipboardHelperMock = {
- copyString() {},
- };
- let windowMock = {
- top: {
- PlacesCommandHook: {
- bookmarkLink() { return Promise.resolve(); }
- },
- PlacesUtils: { bookmarksMenuFolderId: "id" }
- },
- getBrowserURL() {},
- openDialog() {},
- openUILinkIn() {}
- };
- let component = new TabListComponent({
- window: windowMock, store, View: null, SyncedTabs,
- clipboardHelper: clipboardHelperMock,
- getChromeWindow: getChromeWindowMock });
-
- sinon.stub(store, "getData");
- component.onFilter("query");
- Assert.ok(store.getData.calledWith("query"));
-
- sinon.stub(store, "clearFilter");
- component.onClearFilter();
- Assert.ok(store.clearFilter.called);
-
- sinon.stub(store, "focusInput");
- component.onFilterFocus();
- Assert.ok(store.focusInput.called);
-
- sinon.stub(store, "blurInput");
- component.onFilterBlur();
- Assert.ok(store.blurInput.called);
-
- sinon.stub(store, "selectRow");
- component.onSelectRow([-1, -1]);
- Assert.ok(store.selectRow.calledWith(-1, -1));
-
- sinon.stub(store, "moveSelectionDown");
- component.onMoveSelectionDown();
- Assert.ok(store.moveSelectionDown.called);
-
- sinon.stub(store, "moveSelectionUp");
- component.onMoveSelectionUp();
- Assert.ok(store.moveSelectionUp.called);
-
- sinon.stub(store, "toggleBranch");
- component.onToggleBranch("foo-id");
- Assert.ok(store.toggleBranch.calledWith("foo-id"));
-
- sinon.spy(windowMock.top.PlacesCommandHook, "bookmarkLink");
- component.onBookmarkTab("uri", "title");
- Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][1], "uri");
- Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][2], "title");
-
- sinon.spy(windowMock, "openUILinkIn");
- component.onOpenTab("uri", "where", "params");
- Assert.ok(windowMock.openUILinkIn.calledWith("uri", "where", "params"));
-
- sinon.spy(chromeWindowMock.gBrowser, "loadTabs");
- let tabsToOpen = ["uri1", "uri2"];
- component.onOpenTabs(tabsToOpen, "where");
- Assert.ok(getChromeWindowMock.calledWith(windowMock));
- Assert.ok(chromeWindowMock.gBrowser.loadTabs.calledWith(tabsToOpen, false, false));
- component.onOpenTabs(tabsToOpen, "tabshifted");
- Assert.ok(chromeWindowMock.gBrowser.loadTabs.calledWith(tabsToOpen, true, false));
-
- sinon.spy(clipboardHelperMock, "copyString");
- component.onCopyTabLocation("uri");
- Assert.ok(clipboardHelperMock.copyString.calledWith("uri"));
-
- sinon.stub(SyncedTabs, "syncTabs");
- component.onSyncRefresh();
- Assert.ok(SyncedTabs.syncTabs.calledWith(true));
- SyncedTabs.syncTabs.restore();
-});
-
diff --git a/browser/components/syncedtabs/test/xpcshell/xpcshell.ini b/browser/components/syncedtabs/test/xpcshell/xpcshell.ini
deleted file mode 100644
index 1cb8dcb7a..000000000
--- a/browser/components/syncedtabs/test/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-
-[test_EventEmitter.js]
-[test_SyncedTabsDeckStore.js]
-[test_SyncedTabsListStore.js]
-[test_SyncedTabsDeckComponent.js]
-[test_TabListComponent.js]
diff --git a/browser/components/tests/browser/.eslintrc.js b/browser/components/tests/browser/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/tests/browser/browser.ini b/browser/components/tests/browser/browser.ini
deleted file mode 100644
index 6d00b69fa..000000000
--- a/browser/components/tests/browser/browser.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[DEFAULT]
-
-[browser_bug538331.js]
-[browser_contentpermissionprompt.js]
diff --git a/browser/components/tests/browser/browser_bug538331.js b/browser/components/tests/browser/browser_bug538331.js
deleted file mode 100644
index fce3790a0..000000000
--- a/browser/components/tests/browser/browser_bug538331.js
+++ /dev/null
@@ -1,426 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const PREF_POSTUPDATE = "app.update.postupdate";
-const PREF_MSTONE = "browser.startup.homepage_override.mstone";
-const PREF_OVERRIDE_URL = "startup.homepage_override_url";
-
-const DEFAULT_PREF_URL = "http://pref.example.com/";
-const DEFAULT_UPDATE_URL = "http://example.com/";
-
-const XML_EMPTY = "<?xml version=\"1.0\"?><updates xmlns=" +
- "\"http://www.mozilla.org/2005/app-update\"></updates>";
-
-const XML_PREFIX = "<updates xmlns=\"http://www.mozilla.org/2005/app-update\"" +
- "><update appVersion=\"1.0\" buildID=\"20080811053724\" " +
- "channel=\"nightly\" displayVersion=\"Version 1.0\" " +
- "extensionVersion=\"1.0\" installDate=\"1238441400314\" " +
- "isCompleteUpdate=\"true\" name=\"Update Test 1.0\" " +
- "serviceURL=\"https://example.com/\" showNeverForVersion=" +
- "\"false\" showPrompt=\"false\" type=" +
- "\"minor\" version=\"version 1.0\" detailsURL=" +
- "\"http://example.com/\" previousAppVersion=\"1.0\" " +
- "statusText=\"The Update was successfully installed\" " +
- "foregroundDownload=\"true\"";
-
-const XML_SUFFIX = "><patch type=\"complete\" URL=\"http://example.com/\" " +
- "hashFunction=\"MD5\" hashValue=" +
- "\"6232cd43a1c77e30191c53a329a3f99d\" size=\"775\" " +
- "selected=\"true\" state=\"succeeded\"/></update></updates>";
-
-// nsBrowserContentHandler.js defaultArgs tests
-const BCH_TESTS = [
- {
- description: "no mstone change and no update",
- noPostUpdatePref: true,
- noMstoneChange: true
- }, {
- description: "mstone changed and no update",
- noPostUpdatePref: true,
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "no mstone change and update with 'showURL' for actions",
- actions: "showURL",
- noMstoneChange: true
- }, {
- description: "update without actions",
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "update with 'showURL' for actions",
- actions: "showURL",
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "update with 'showURL' for actions and openURL",
- actions: "showURL",
- openURL: DEFAULT_UPDATE_URL
- }, {
- description: "update with 'showURL showAlert' for actions",
- actions: "showAlert showURL",
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "update with 'showAlert showURL' for actions and openURL",
- actions: "showAlert showURL",
- openURL: DEFAULT_UPDATE_URL
- }, {
- description: "update with 'showURL showNotification' for actions",
- actions: "showURL showNotification",
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "update with 'showNotification showURL' for actions and " +
- "openURL",
- actions: "showNotification showURL",
- openURL: DEFAULT_UPDATE_URL
- }, {
- description: "update with 'showAlert showURL showNotification' for actions",
- actions: "showAlert showURL showNotification",
- prefURL: DEFAULT_PREF_URL
- }, {
- description: "update with 'showNotification showURL showAlert' for " +
- "actions and openURL",
- actions: "showNotification showURL showAlert",
- openURL: DEFAULT_UPDATE_URL
- }, {
- description: "update with 'showAlert' for actions",
- actions: "showAlert"
- }, {
- description: "update with 'showAlert showNotification' for actions",
- actions: "showAlert showNotification"
- }, {
- description: "update with 'showNotification' for actions",
- actions: "showNotification"
- }, {
- description: "update with 'showNotification showAlert' for actions",
- actions: "showNotification showAlert"
- }, {
- description: "update with 'silent' for actions",
- actions: "silent"
- }, {
- description: "update with 'silent showURL showAlert showNotification' " +
- "for actions and openURL",
- actions: "silent showURL showAlert showNotification"
- }
-];
-
-var gOriginalMStone;
-var gOriginalOverrideURL;
-
-this.__defineGetter__("gBG", function() {
- delete this.gBG;
- return this.gBG = Cc["@mozilla.org/browser/browserglue;1"].
- getService(Ci.nsIObserver);
-});
-
-function test()
-{
- waitForExplicitFinish();
-
- // Reset the startup page pref since it may have been set by other tests
- // and we will assume it is default.
- Services.prefs.clearUserPref('browser.startup.page');
-
- if (gPrefService.prefHasUserValue(PREF_MSTONE)) {
- gOriginalMStone = gPrefService.getCharPref(PREF_MSTONE);
- }
-
- if (gPrefService.prefHasUserValue(PREF_OVERRIDE_URL)) {
- gOriginalOverrideURL = gPrefService.getCharPref(PREF_OVERRIDE_URL);
- }
-
- testDefaultArgs();
-}
-
-var gWindowCatcher = {
- windowsOpen: 0,
- finishCalled: false,
- start: function() {
- Services.ww.registerNotification(this);
- },
-
- finish: function(aFunc) {
- Services.ww.unregisterNotification(this);
- this.finishFunc = aFunc;
- if (this.windowsOpen > 0)
- return;
-
- this.finishFunc();
- },
-
- closeWindow: function (win) {
- info("window catcher closing window: " + win.document.documentURI);
- win.close();
- this.windowsOpen--;
- if (this.finishFunc) {
- this.finish(this.finishFunc);
- }
- },
-
- windowLoad: function (win) {
- executeSoon(this.closeWindow.bind(this, win));
- },
-
- observe: function(subject, topic, data) {
- if (topic != "domwindowopened")
- return;
-
- this.windowsOpen++;
- let win = subject.QueryInterface(Ci.nsIDOMWindow);
- info("window catcher caught window opening: " + win.document.documentURI);
- win.addEventListener("load", function () {
- win.removeEventListener("load", arguments.callee, false);
- gWindowCatcher.windowLoad(win);
- }, false);
- }
-};
-
-function finish_test()
-{
- // Reset browser.startup.homepage_override.mstone to the original value or
- // clear it if it didn't exist.
- if (gOriginalMStone) {
- gPrefService.setCharPref(PREF_MSTONE, gOriginalMStone);
- } else if (gPrefService.prefHasUserValue(PREF_MSTONE)) {
- gPrefService.clearUserPref(PREF_MSTONE);
- }
-
- // Reset startup.homepage_override_url to the original value or clear it if
- // it didn't exist.
- if (gOriginalOverrideURL) {
- gPrefService.setCharPref(PREF_OVERRIDE_URL, gOriginalOverrideURL);
- } else if (gPrefService.prefHasUserValue(PREF_OVERRIDE_URL)) {
- gPrefService.clearUserPref(PREF_OVERRIDE_URL);
- }
-
- writeUpdatesToXMLFile(XML_EMPTY);
- reloadUpdateManagerData();
-
- finish();
-}
-
-// Test the defaultArgs returned by nsBrowserContentHandler after an update
-function testDefaultArgs()
-{
- // Clear any pre-existing override in defaultArgs that are hanging around.
- // This will also set the browser.startup.homepage_override.mstone preference
- // if it isn't already set.
- Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler).defaultArgs;
-
- let originalMstone = gPrefService.getCharPref(PREF_MSTONE);
-
- gPrefService.setCharPref(PREF_OVERRIDE_URL, DEFAULT_PREF_URL);
-
- writeUpdatesToXMLFile(XML_EMPTY);
- reloadUpdateManagerData();
-
- for (let i = 0; i < BCH_TESTS.length; i++) {
- let test = BCH_TESTS[i];
- ok(true, "Test nsBrowserContentHandler " + (i + 1) + ": " + test.description);
-
- if (test.actions) {
- let actionsXML = " actions=\"" + test.actions + "\"";
- if (test.openURL) {
- actionsXML += " openURL=\"" + test.openURL + "\"";
- }
- writeUpdatesToXMLFile(XML_PREFIX + actionsXML + XML_SUFFIX);
- } else {
- writeUpdatesToXMLFile(XML_EMPTY);
- }
-
- reloadUpdateManagerData();
-
- let noOverrideArgs = Cc["@mozilla.org/browser/clh;1"].
- getService(Ci.nsIBrowserHandler).defaultArgs;
-
- let overrideArgs = "";
- if (test.prefURL) {
- overrideArgs = test.prefURL;
- } else if (test.openURL) {
- overrideArgs = test.openURL;
- }
-
- if (overrideArgs == "" && noOverrideArgs) {
- overrideArgs = noOverrideArgs;
- } else if (noOverrideArgs) {
- overrideArgs += "|" + noOverrideArgs;
- }
-
- if (test.noMstoneChange === undefined) {
- gPrefService.setCharPref(PREF_MSTONE, "PreviousMilestone");
- }
-
- if (test.noPostUpdatePref == undefined) {
- gPrefService.setBoolPref(PREF_POSTUPDATE, true);
- }
-
- let defaultArgs = Cc["@mozilla.org/browser/clh;1"].
- getService(Ci.nsIBrowserHandler).defaultArgs;
- is(defaultArgs, overrideArgs, "correct value returned by defaultArgs");
-
- if (test.noMstoneChange === undefined || test.noMstoneChange != true) {
- let newMstone = gPrefService.getCharPref(PREF_MSTONE);
- is(originalMstone, newMstone, "preference " + PREF_MSTONE +
- " should have been updated");
- }
-
- if (gPrefService.prefHasUserValue(PREF_POSTUPDATE)) {
- gPrefService.clearUserPref(PREF_POSTUPDATE);
- }
- }
-
- testShowNotification();
-}
-
-// nsBrowserGlue.js _showUpdateNotification notification tests
-const BG_NOTIFY_TESTS = [
- {
- description: "'silent showNotification' actions should not display a notification",
- actions: "silent showNotification"
- }, {
- description: "'showNotification' for actions should display a notification",
- actions: "showNotification"
- }, {
- description: "no actions and empty updates.xml",
- }, {
- description: "'showAlert' for actions should not display a notification",
- actions: "showAlert"
- }, {
- // This test MUST be the last test in the array to test opening the url
- // provided by the updates.xml.
- description: "'showNotification' for actions with custom notification " +
- "attributes should display a notification",
- actions: "showNotification",
- notificationText: "notification text",
- notificationURL: DEFAULT_UPDATE_URL,
- notificationButtonLabel: "button label",
- notificationButtonAccessKey: "b"
- }
-];
-
-// Test showing a notification after an update
-// _showUpdateNotification in nsBrowserGlue.js
-function testShowNotification()
-{
- let notifyBox = document.getElementById("high-priority-global-notificationbox");
-
- // Catches any windows opened by these tests (e.g. alert windows) and closes
- // them
- gWindowCatcher.start();
-
- for (let i = 0; i < BG_NOTIFY_TESTS.length; i++) {
- let test = BG_NOTIFY_TESTS[i];
- ok(true, "Test showNotification " + (i + 1) + ": " + test.description);
-
- if (test.actions) {
- let actionsXML = " actions=\"" + test.actions + "\"";
- if (test.notificationText) {
- actionsXML += " notificationText=\"" + test.notificationText + "\"";
- }
- if (test.notificationURL) {
- actionsXML += " notificationURL=\"" + test.notificationURL + "\"";
- }
- if (test.notificationButtonLabel) {
- actionsXML += " notificationButtonLabel=\"" + test.notificationButtonLabel + "\"";
- }
- if (test.notificationButtonAccessKey) {
- actionsXML += " notificationButtonAccessKey=\"" + test.notificationButtonAccessKey + "\"";
- }
- writeUpdatesToXMLFile(XML_PREFIX + actionsXML + XML_SUFFIX);
- } else {
- writeUpdatesToXMLFile(XML_EMPTY);
- }
-
- reloadUpdateManagerData();
- gPrefService.setBoolPref(PREF_POSTUPDATE, true);
-
- gBG.observe(null, "browser-glue-test", "post-update-notification");
-
- let updateBox = notifyBox.getNotificationWithValue("post-update-notification");
- if (test.actions && test.actions.indexOf("showNotification") != -1 &&
- test.actions.indexOf("silent") == -1) {
- ok(updateBox, "Update notification box should have been displayed");
- if (updateBox) {
- if (test.notificationText) {
- is(updateBox.label, test.notificationText, "Update notification box " +
- "should have the label provided by the update");
- }
- if (test.notificationButtonLabel) {
- var button = updateBox.getElementsByTagName("button").item(0);
- is(button.label, test.notificationButtonLabel, "Update notification " +
- "box button should have the label provided by the update");
- if (test.notificationButtonAccessKey) {
- let accessKey = button.getAttribute("accesskey");
- is(accessKey, test.notificationButtonAccessKey, "Update " +
- "notification box button should have the accesskey " +
- "provided by the update");
- }
- }
- // The last test opens an url and verifies the url from the updates.xml
- // is correct.
- if (i == (BG_NOTIFY_TESTS.length - 1)) {
- // Wait for any windows caught by the windowcatcher to close
- gWindowCatcher.finish(function () {
- BrowserTestUtils.waitForNewTab(gBrowser).then(testNotificationURL);
- button.click();
- });
- } else {
- notifyBox.removeAllNotifications(true);
- }
- } else if (i == (BG_NOTIFY_TESTS.length - 1)) {
- // If updateBox is null the test has already reported errors so bail
- finish_test();
- }
- } else {
- ok(!updateBox, "Update notification box should not have been displayed");
- }
-
- let prefHasUserValue = gPrefService.prefHasUserValue(PREF_POSTUPDATE);
- is(prefHasUserValue, false, "preference " + PREF_POSTUPDATE +
- " shouldn't have a user value");
- }
-}
-
-// Test opening the url provided by the updates.xml in the last test
-function testNotificationURL()
-{
- ok(true, "Test testNotificationURL: clicking the notification button " +
- "opened the url specified by the update");
- let href = gBrowser.currentURI.spec;
- let expectedURL = BG_NOTIFY_TESTS[BG_NOTIFY_TESTS.length - 1].notificationURL;
- is(href, expectedURL, "The url opened from the notification should be the " +
- "url provided by the update");
- gBrowser.removeCurrentTab();
- window.focus();
- finish_test();
-}
-
-/* Reloads the update metadata from disk */
-function reloadUpdateManagerData()
-{
- Cc["@mozilla.org/updates/update-manager;1"].getService(Ci.nsIUpdateManager).
- QueryInterface(Ci.nsIObserver).observe(null, "um-reload-update-data", "");
-}
-
-
-function writeUpdatesToXMLFile(aText)
-{
- const PERMS_FILE = 0o644;
-
- const MODE_WRONLY = 0x02;
- const MODE_CREATE = 0x08;
- const MODE_TRUNCATE = 0x20;
-
- let file = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties).
- get("UpdRootD", Ci.nsIFile);
- file.append("updates.xml");
- let fos = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- if (!file.exists()) {
- file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
- }
- fos.init(file, MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE, PERMS_FILE, 0);
- fos.write(aText, aText.length);
- fos.close();
-}
diff --git a/browser/components/tests/browser/browser_contentpermissionprompt.js b/browser/components/tests/browser/browser_contentpermissionprompt.js
deleted file mode 100644
index 054aa22e8..000000000
--- a/browser/components/tests/browser/browser_contentpermissionprompt.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * These tests test nsBrowserGlue's nsIContentPermissionPrompt
- * implementation behaviour with various types of
- * nsIContentPermissionRequests.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Integration.jsm", this);
-
-XPCOMUtils.defineLazyServiceGetter(this, "ContentPermissionPrompt",
- "@mozilla.org/content-permission/prompt;1",
- "nsIContentPermissionPrompt");
-
-/**
- * This is a partial implementation of nsIContentPermissionType.
- *
- * @param {string} type
- * The string defining what type of permission is being requested.
- * Example: "geo", "desktop-notification".
- * @return nsIContentPermissionType implementation.
- */
-function MockContentPermissionType(type) {
- this.type = type;
-}
-
-MockContentPermissionType.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionType]),
- // We expose the wrappedJSObject so that we can be sure
- // in some of our tests that we're passing the right
- // nsIContentPermissionType around.
- wrappedJSObject: this,
-};
-
-/**
- * This is a partial implementation of nsIContentPermissionRequest.
- *
- * @param {Array<nsIContentPermissionType>} typesArray
- * The types to assign to this nsIContentPermissionRequest,
- * in order. You probably want to use MockContentPermissionType.
- * @return nsIContentPermissionRequest implementation.
- */
-function MockContentPermissionRequest(typesArray) {
- this.types = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
- for (let type of typesArray) {
- this.types.appendElement(type, false);
- }
-}
-
-MockContentPermissionRequest.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionRequest]),
- // We expose the wrappedJSObject so that we can be sure
- // in some of our tests that we're passing the right
- // nsIContentPermissionRequest around.
- wrappedJSObject: this,
- // For some of our tests, we want to make sure that the
- // request is cancelled, so we add some instrumentation here
- // to check that cancel() is called.
- cancel() {
- this.cancelled = true;
- },
- cancelled: false,
-};
-
-/**
- * Tests that if the nsIContentPermissionRequest has an empty
- * types array, that NS_ERROR_UNEXPECTED is thrown, and the
- * request is cancelled.
- */
-add_task(function* test_empty_types() {
- let mockRequest = new MockContentPermissionRequest([]);
- Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); },
- /NS_ERROR_UNEXPECTED/,
- "Should have thrown NS_ERROR_UNEXPECTED.");
- Assert.ok(mockRequest.cancelled, "Should have cancelled the request.");
-});
-
-/**
- * Tests that if the nsIContentPermissionRequest has more than
- * one type, that NS_ERROR_UNEXPECTED is thrown, and the request
- * is cancelled.
- */
-add_task(function* test_multiple_types() {
- let mockRequest = new MockContentPermissionRequest([
- new MockContentPermissionType("test1"),
- new MockContentPermissionType("test2"),
- ]);
-
- Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); },
- /NS_ERROR_UNEXPECTED/);
- Assert.ok(mockRequest.cancelled, "Should have cancelled the request.");
-});
-
-/**
- * Tests that if the nsIContentPermissionRequest has a type that
- * does not implement nsIContentPermissionType that NS_NOINTERFACE
- * is thrown, and the request is cancelled.
- */
-add_task(function* test_not_permission_type() {
- let mockRequest = new MockContentPermissionRequest([
- { QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports]) },
- ]);
-
- Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); },
- /NS_NOINTERFACE/);
- Assert.ok(mockRequest.cancelled, "Should have cancelled the request.");
-});
-
-/**
- * Tests that if the nsIContentPermissionRequest is for a type
- * that is not recognized, that NS_ERROR_FAILURE is thrown and
- * the request is cancelled.
- */
-add_task(function* test_unrecognized_type() {
- let mockRequest = new MockContentPermissionRequest([
- new MockContentPermissionType("test1"),
- ]);
-
- Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); },
- /NS_ERROR_FAILURE/);
- Assert.ok(mockRequest.cancelled, "Should have cancelled the request.");
-});
-
-/**
- * Tests that if we meet the minimal requirements for a
- * nsIContentPermissionRequest, that it will be passed to
- * ContentPermissionIntegration's createPermissionPrompt
- * method.
- */
-add_task(function* test_working_request() {
- let mockType = new MockContentPermissionType("test-permission-type");
- let mockRequest = new MockContentPermissionRequest([mockType]);
-
- // mockPermissionPrompt is what createPermissionPrompt
- // will return. Returning some kind of object should be
- // enough to convince nsBrowserGlue that everything went
- // okay.
- let didPrompt = false;
- let mockPermissionPrompt = {
- prompt() {
- didPrompt = true;
- }
- };
-
- let integration = (base) => ({
- createPermissionPrompt(type, request) {
- Assert.equal(type, "test-permission-type");
- Assert.ok(Object.is(request.wrappedJSObject, mockRequest.wrappedJSObject));
- return mockPermissionPrompt;
- },
- });
-
- // Register an integration so that we can capture the
- // calls into ContentPermissionIntegration.
- try {
- Integration.contentPermission.register(integration);
-
- ContentPermissionPrompt.prompt(mockRequest);
- Assert.ok(!mockRequest.cancelled,
- "Should not have cancelled the request.");
- Assert.ok(didPrompt, "Should have tried to show the prompt");
- } finally {
- Integration.contentPermission.unregister(integration);
- }
-});
diff --git a/browser/components/tests/unit/.eslintrc.js b/browser/components/tests/unit/.eslintrc.js
deleted file mode 100644
index fee088c17..000000000
--- a/browser/components/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/tests/unit/data/engine-de-DE.xml b/browser/components/tests/unit/data/engine-de-DE.xml
deleted file mode 100644
index b9fa0a464..000000000
--- a/browser/components/tests/unit/data/engine-de-DE.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>Google</ShortName>
-<Description>override-de-DE</Description>
-<InputEncoding>UTF-8</InputEncoding>
-<Url type="text/html" method="GET" template="http://searchtest.local">
- <Param name="search" value="{searchTerms}"/>
-</Url>
-</SearchPlugin>
diff --git a/browser/components/tests/unit/distribution.ini b/browser/components/tests/unit/distribution.ini
deleted file mode 100644
index d7d298808..000000000
--- a/browser/components/tests/unit/distribution.ini
+++ /dev/null
@@ -1,58 +0,0 @@
-# Distribution Configuration File
-# Test of distribution preferences
-
-[Global]
-id=disttest
-version=1.0
-about=Test distribution file
-about.en-US=Tèƨƭ δïƨƭřïβúƭïôñ ƒïℓè
-
-[Preferences]
-distribution.test.string="Test String"
-distribution.test.string.noquotes=Test String
-distribution.test.int=777
-distribution.test.bool.true=true
-distribution.test.bool.false=false
-distribution.test.empty=
-
-distribution.test.pref.locale="%LOCALE%"
-distribution.test.pref.language.reset="Preference Set"
-distribution.test.pref.locale.reset="Preference Set"
-distribution.test.pref.locale.set="Preference Set"
-distribution.test.pref.language.set="Preference Set"
-
-[Preferences-en]
-distribution.test.pref.language.en="en"
-distribution.test.pref.language.reset=
-distribution.test.pref.language.set="Language Set"
-distribution.test.pref.locale.set="Language Set"
-
-[Preferences-en-US]
-distribution.test.pref.locale.en-US="en-US"
-distribution.test.pref.locale.reset=
-distribution.test.pref.locale.set="Locale Set"
-
-
-[Preferences-de]
-distribution.test.pref.language.de="de"
-
-[LocalizablePreferences]
-distribution.test.locale="%LOCALE%"
-distribution.test.language.reset="Preference Set"
-distribution.test.locale.reset="Preference Set"
-distribution.test.locale.set="Preference Set"
-distribution.test.language.set="Preference Set"
-
-[LocalizablePreferences-en]
-distribution.test.language.en="en"
-distribution.test.language.reset=
-distribution.test.language.set="Language Set"
-distribution.test.locale.set="Language Set"
-
-[LocalizablePreferences-en-US]
-distribution.test.locale.en-US="en-US"
-distribution.test.locale.reset=
-distribution.test.locale.set="Locale Set"
-
-[LocalizablePreferences-de]
-distribution.test.language.de="de"
diff --git a/browser/components/tests/unit/head.js b/browser/components/tests/unit/head.js
deleted file mode 100644
index 3d4e23452..000000000
--- a/browser/components/tests/unit/head.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/* 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/. */
-
-const {interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-var gProfD = do_get_profile().QueryInterface(Ci.nsILocalFile);
diff --git a/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js b/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js
deleted file mode 100644
index a68503db3..000000000
--- a/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js
+++ /dev/null
@@ -1,32 +0,0 @@
-const UI_VERSION = 41;
-const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
-const TOPICDATA_BROWSERGLUE_TEST = "force-ui-migration";
-
-var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"]
- .getService(Ci.nsIObserver);
-
-Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1);
-
-add_task(function* test_check_cleanup_loop_prefs() {
- Services.prefs.setBoolPref("loop.createdRoom", true);
- Services.prefs.setBoolPref("loop1.createdRoom", true);
- Services.prefs.setBoolPref("loo.createdRoom", true);
-
- // Simulate a migration.
- gBrowserGlue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_BROWSERGLUE_TEST);
-
- Assert.throws(() => Services.prefs.getBoolPref("loop.createdRoom"),
- /NS_ERROR_UNEXPECTED/,
- "should have cleared old loop preference 'loop.createdRoom'");
- Assert.ok(Services.prefs.getBoolPref("loop1.createdRoom"),
- "should have left non-loop pref 'loop1.createdRoom' untouched");
- Assert.ok(Services.prefs.getBoolPref("loo.createdRoom"),
- "should have left non-loop pref 'loo.createdRoom' untouched");
-});
-
-do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.migration.version");
- Services.prefs.clearUserPref("loop.createdRoom");
- Services.prefs.clearUserPref("loop1.createdRoom");
- Services.prefs.clearUserPref("loo.createdRoom");
-});
diff --git a/browser/components/tests/unit/test_distribution.js b/browser/components/tests/unit/test_distribution.js
deleted file mode 100644
index 183ab85d6..000000000
--- a/browser/components/tests/unit/test_distribution.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that preferences are properly set by distribution.ini
- */
-
-Cu.import("resource://gre/modules/LoadContextInfo.jsm");
-
-// Import common head.
-var commonFile = do_get_file("../../../../toolkit/components/places/tests/head_common.js", false);
-/* import-globals-from ../../../../toolkit/components/places/tests/head_common.js */
-if (commonFile) {
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-const TOPICDATA_DISTRIBUTION_CUSTOMIZATION = "force-distribution-customization";
-const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
-
-/**
- * Copy the engine-distribution.xml engine to a fake distribution
- * created in the profile, and registered with the directory service.
- * Create an empty en-US directory to make sure it isn't used.
- */
-function installDistributionEngine() {
- const XRE_APP_DISTRIBUTION_DIR = "XREAppDist";
-
- let dir = gProfD.clone();
- dir.append("distribution");
- let distDir = dir.clone();
-
- dir.append("searchplugins");
- dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- dir.append("locale");
- dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
- let localeDir = dir.clone();
-
- dir.append("en-US");
- dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- localeDir.append("de-DE");
- localeDir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
-
- do_get_file("data/engine-de-DE.xml").copyTo(localeDir, "engine-de-DE.xml");
-
- Services.dirsvc.registerProvider({
- getFile: function(aProp, aPersistent) {
- aPersistent.value = true;
- if (aProp == XRE_APP_DISTRIBUTION_DIR)
- return distDir.clone();
- return null;
- }
- });
-}
-
-function run_test() {
- // Set special pref to load distribution.ini from the profile folder.
- Services.prefs.setBoolPref("distribution.testing.loadFromProfile", true);
-
- // Copy distribution.ini file to the profile dir.
- let distroDir = gProfD.clone();
- distroDir.leafName = "distribution";
- let iniFile = distroDir.clone();
- iniFile.append("distribution.ini");
- if (iniFile.exists()) {
- iniFile.remove(false);
- print("distribution.ini already exists, did some test forget to cleanup?");
- }
-
- let testDistributionFile = gTestDir.clone();
- testDistributionFile.append("distribution.ini");
- testDistributionFile.copyTo(distroDir, "distribution.ini");
- Assert.ok(testDistributionFile.exists());
-
- installDistributionEngine();
-
- run_next_test();
-}
-
-do_register_cleanup(function () {
- // Remove the distribution dir, even if the test failed, otherwise all
- // next tests will use it.
- let distDir = gProfD.clone();
- distDir.append("distribution");
- distDir.remove(true);
- Assert.ok(!distDir.exists());
-});
-
-add_task(function* () {
- // Force distribution.
- let glue = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver)
- glue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_DISTRIBUTION_CUSTOMIZATION);
-
- var defaultBranch = Services.prefs.getDefaultBranch(null);
-
- Assert.equal(defaultBranch.getCharPref("distribution.id"), "disttest");
- Assert.equal(defaultBranch.getCharPref("distribution.version"), "1.0");
- Assert.equal(defaultBranch.getComplexValue("distribution.about", Ci.nsISupportsString).data, "Tèƨƭ δïƨƭřïβúƭïôñ ƒïℓè");
-
- Assert.equal(defaultBranch.getCharPref("distribution.test.string"), "Test String");
- Assert.equal(defaultBranch.getCharPref("distribution.test.string.noquotes"), "Test String");
- Assert.equal(defaultBranch.getIntPref("distribution.test.int"), 777);
- Assert.equal(defaultBranch.getBoolPref("distribution.test.bool.true"), true);
- Assert.equal(defaultBranch.getBoolPref("distribution.test.bool.false"), false);
-
- Assert.throws(() => defaultBranch.getCharPref("distribution.test.empty"));
- Assert.throws(() => defaultBranch.getIntPref("distribution.test.empty"));
- Assert.throws(() => defaultBranch.getBoolPref("distribution.test.empty"));
-
- Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale"), "en-US");
- Assert.equal(defaultBranch.getCharPref("distribution.test.pref.language.en"), "en");
- Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale.en-US"), "en-US");
- Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.language.de"));
- // This value was never set because of the empty language specific pref
- Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.language.reset"));
- // This value was never set because of the empty locale specific pref
- Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.locale.reset"));
- // This value was overridden by a locale specific setting
- Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale.set"), "Locale Set");
- // This value was overridden by a language specific setting
- Assert.equal(defaultBranch.getCharPref("distribution.test.pref.language.set"), "Language Set");
- // Language should not override locale
- Assert.notEqual(defaultBranch.getCharPref("distribution.test.pref.locale.set"), "Language Set");
-
- Assert.equal(defaultBranch.getComplexValue("distribution.test.locale", Ci.nsIPrefLocalizedString).data, "en-US");
- Assert.equal(defaultBranch.getComplexValue("distribution.test.language.en", Ci.nsIPrefLocalizedString).data, "en");
- Assert.equal(defaultBranch.getComplexValue("distribution.test.locale.en-US", Ci.nsIPrefLocalizedString).data, "en-US");
- Assert.throws(() => defaultBranch.getComplexValue("distribution.test.language.de", Ci.nsIPrefLocalizedString));
- // This value was never set because of the empty language specific pref
- Assert.throws(() => defaultBranch.getComplexValue("distribution.test.language.reset", Ci.nsIPrefLocalizedString));
- // This value was never set because of the empty locale specific pref
- Assert.throws(() => defaultBranch.getComplexValue("distribution.test.locale.reset", Ci.nsIPrefLocalizedString));
- // This value was overridden by a locale specific setting
- Assert.equal(defaultBranch.getComplexValue("distribution.test.locale.set", Ci.nsIPrefLocalizedString).data, "Locale Set");
- // This value was overridden by a language specific setting
- Assert.equal(defaultBranch.getComplexValue("distribution.test.language.set", Ci.nsIPrefLocalizedString).data, "Language Set");
- // Language should not override locale
- Assert.notEqual(defaultBranch.getComplexValue("distribution.test.locale.set", Ci.nsIPrefLocalizedString).data, "Language Set");
-
- do_test_pending();
-
- Services.prefs.setCharPref("distribution.searchplugins.defaultLocale", "de-DE");
-
- Services.search.init(function() {
- Assert.equal(Services.search.isInitialized, true);
- var engine = Services.search.getEngineByName("Google");
- Assert.equal(engine.description, "override-de-DE");
- do_test_finished();
- });
-});
diff --git a/browser/components/tests/unit/xpcshell.ini b/browser/components/tests/unit/xpcshell.ini
deleted file mode 100644
index c2f461966..000000000
--- a/browser/components/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-head = head.js
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files =
- distribution.ini
- data/engine-de-DE.xml
-
-[test_distribution.js]
-[test_browserGlue_migration_loop_cleanup.js]
diff --git a/browser/components/translation/test/.eslintrc.js b/browser/components/translation/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/translation/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/translation/test/bing.sjs b/browser/components/translation/test/bing.sjs
deleted file mode 100644
index ce3b96855..000000000
--- a/browser/components/translation/test/bing.sjs
+++ /dev/null
@@ -1,234 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, Constructor: CC} = Components;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(req, res) {
- try {
- reallyHandleRequest(req, res);
- } catch (ex) {
- res.setStatusLine("1.0", 200, "AlmostOK");
- let msg = "Error handling request: " + ex + "\n" + ex.stack;
- log(msg);
- res.write(msg);
- }
-}
-
-function log(msg) {
- // dump("BING-SERVER-MOCK: " + msg + "\n");
-}
-
-const statusCodes = {
- 400: "Bad Request",
- 401: "Unauthorized",
- 403: "Forbidden",
- 404: "Not Found",
- 405: "Method Not Allowed",
- 500: "Internal Server Error",
- 501: "Not Implemented",
- 503: "Service Unavailable"
-};
-
-function HTTPError(code = 500, message) {
- this.code = code;
- this.name = statusCodes[code] || "HTTPError";
- this.message = message || this.name;
-}
-HTTPError.prototype = new Error();
-HTTPError.prototype.constructor = HTTPError;
-
-function sendError(res, err) {
- if (!(err instanceof HTTPError)) {
- err = new HTTPError(typeof err == "number" ? err : 500,
- err.message || typeof err == "string" ? err : "");
- }
- res.setStatusLine("1.1", err.code, err.name);
- res.write(err.message);
-}
-
-function parseQuery(query) {
- let ret = {};
- for (let param of query.replace(/^[?&]/, "").split("&")) {
- param = param.split("=");
- if (!param[0])
- continue;
- ret[unescape(param[0])] = unescape(param[1]);
- }
- return ret;
-}
-
-function getRequestBody(req) {
- let avail;
- let bytes = [];
- let body = new BinaryInputStream(req.bodyInputStream);
-
- while ((avail = body.available()) > 0)
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
-
- return String.fromCharCode.apply(null, bytes);
-}
-
-function sha1(str) {
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- // `result` is an out parameter, `result.value` will contain the array length.
- let result = {};
- // `data` is an array of bytes.
- let data = converter.convertToByteArray(str, result);
- let ch = Cc["@mozilla.org/security/hash;1"]
- .createInstance(Ci.nsICryptoHash);
- ch.init(ch.SHA1);
- ch.update(data, data.length);
- let hash = ch.finish(false);
-
- // Return the two-digit hexadecimal code for a byte.
- function toHexString(charCode) {
- return ("0" + charCode.toString(16)).slice(-2);
- }
-
- // Convert the binary hash data to a hex string.
- return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join("");
-}
-
-function parseXml(body) {
- let DOMParser = Cc["@mozilla.org/xmlextras/domparser;1"]
- .createInstance(Ci.nsIDOMParser);
- let xml = DOMParser.parseFromString(body, "text/xml");
- if (xml.documentElement.localName == "parsererror")
- throw new Error("Invalid XML");
- return xml;
-}
-
-function getInputStream(path) {
- let file = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("CurWorkD", Ci.nsILocalFile);
- for (let part of path.split("/"))
- file.append(part);
- let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- fileStream.init(file, 1, 0, false);
- return fileStream;
-}
-
-function checkAuth(req) {
- let err = new Error("Authorization failed");
- err.code = 401;
-
- if (!req.hasHeader("Authorization"))
- throw new HTTPError(401, "No Authorization header provided.");
-
- let auth = req.getHeader("Authorization");
- if (!auth.startsWith("Bearer "))
- throw new HTTPError(401, "Invalid Authorization header content: '" + auth + "'");
-
- // Rejecting inactive subscriptions.
- if (auth.includes("inactive")) {
- const INACTIVE_STATE_RESPONSE = "<html><body><h1>TranslateApiException</h1><p>Method: TranslateArray()</p><p>Message: The Azure Market Place Translator Subscription associated with the request credentials is not in an active state.</p><code></code><p>message id=5641.V2_Rest.TranslateArray.48CC6470</p></body></html>";
- throw new HTTPError(401, INACTIVE_STATE_RESPONSE);
- }
-
-}
-
-function reallyHandleRequest(req, res) {
- log("method: " + req.method);
- if (req.method != "POST") {
- sendError(res, "Bing only deals with POST requests, not '" + req.method + "'.");
- return;
- }
-
- let body = getRequestBody(req);
- log("body: " + body);
-
- // First, we'll see if we're dealing with an XML body:
- let contentType = req.hasHeader("Content-Type") ? req.getHeader("Content-Type") : null;
- log("contentType: " + contentType);
-
- if (contentType.startsWith("text/xml")) {
- try {
- // For all these requests the client needs to supply the correct
- // authentication headers.
- checkAuth(req);
-
- let xml = parseXml(body);
- let method = xml.documentElement.localName;
- log("invoking method: " + method);
- // If the requested method is supported, delegate it to its handler.
- if (methodHandlers[method])
- methodHandlers[method](res, xml);
- else
- throw new HTTPError(501);
- } catch (ex) {
- sendError(res, ex, ex.code);
- }
- } else {
- // Not XML, so it must be a query-string.
- let params = parseQuery(body);
-
- // Delegate an authentication request to the correct handler.
- if ("grant_type" in params && params.grant_type == "client_credentials")
- methodHandlers.authenticate(res, params);
- else
- sendError(res, 501);
- }
-}
-
-const methodHandlers = {
- authenticate: function(res, params) {
- // Validate a few required parameters.
- if (params.scope != "http://api.microsofttranslator.com") {
- sendError(res, "Invalid scope.");
- return;
- }
- if (!params.client_id) {
- sendError(res, "Missing client_id param.");
- return;
- }
- if (!params.client_secret) {
- sendError(res, "Missing client_secret param.");
- return;
- }
-
- // Defines the tokens for certain client ids.
- const TOKEN_MAP = {
- 'testInactive' : 'inactive',
- 'testClient' : 'test'
- };
- let token = 'test'; // Default token.
- if((params.client_id in TOKEN_MAP)){
- token = TOKEN_MAP[params.client_id];
- }
- let content = JSON.stringify({
- access_token: token,
- expires_in: 600
- });
-
- res.setStatusLine("1.1", 200, "OK");
- res.setHeader("Content-Length", String(content.length));
- res.setHeader("Content-Type", "application/json");
- res.write(content);
- },
-
- TranslateArrayRequest: function(res, xml, body) {
- let from = xml.querySelector("From").firstChild.nodeValue;
- let to = xml.querySelector("To").firstChild.nodeValue
- log("translating from '" + from + "' to '" + to + "'");
-
- res.setStatusLine("1.1", 200, "OK");
- res.setHeader("Content-Type", "text/xml");
-
- let hash = sha1(body).substr(0, 10);
- log("SHA1 hash of content: " + hash);
- let inputStream = getInputStream(
- "browser/browser/components/translation/test/fixtures/result-" + hash + ".txt");
- res.bodyOutputStream.writeFrom(inputStream, inputStream.available());
- inputStream.close();
- }
-};
diff --git a/browser/components/translation/test/browser.ini b/browser/components/translation/test/browser.ini
deleted file mode 100644
index 59e481855..000000000
--- a/browser/components/translation/test/browser.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-support-files =
- bing.sjs
- yandex.sjs
- fixtures/bug1022725-fr.html
- fixtures/result-da39a3ee5e.txt
- fixtures/result-yandex-d448894848.json
-
-[browser_translation_bing.js]
-[browser_translation_yandex.js]
-[browser_translation_telemetry.js]
-[browser_translation_infobar.js]
-[browser_translation_exceptions.js]
diff --git a/browser/components/translation/test/browser_translation_bing.js b/browser/components/translation/test/browser_translation_bing.js
deleted file mode 100644
index 399a67022..000000000
--- a/browser/components/translation/test/browser_translation_bing.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* 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/. */
-
-// Test the Bing Translator client against a mock Bing service, bing.sjs.
-
-"use strict";
-
-const kClientIdPref = "browser.translation.bing.clientIdOverride";
-const kClientSecretPref = "browser.translation.bing.apiKeyOverride";
-
-const {BingTranslator} = Cu.import("resource:///modules/translation/BingTranslator.jsm", {});
-const {TranslationDocument} = Cu.import("resource:///modules/translation/TranslationDocument.jsm", {});
-const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
-
-add_task(function* setup() {
- Services.prefs.setCharPref(kClientIdPref, "testClient");
- Services.prefs.setCharPref(kClientSecretPref, "testSecret");
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(kClientIdPref);
- Services.prefs.clearUserPref(kClientSecretPref);
- });
-});
-
-/**
- * Checks if the translation is happening.
- */
-add_task(function* test_bing_translation() {
-
- // Ensure the correct client id is used for authentication.
- Services.prefs.setCharPref(kClientIdPref, "testClient");
-
- // Loading the fixture page.
- let url = constructFixtureURL("bug1022725-fr.html");
- let tab = yield promiseTestPageLoad(url);
-
- // Translating the contents of the loaded tab.
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- yield ContentTask.spawn(browser, null, function*() {
- Cu.import("resource:///modules/translation/BingTranslator.jsm");
- Cu.import("resource:///modules/translation/TranslationDocument.jsm");
-
- let client = new BingTranslator(
- new TranslationDocument(content.document), "fr", "en");
- let result = yield client.translate();
-
- // XXXmikedeboer; here you would continue the test/ content inspection.
- Assert.ok(result, "There should be a result");
- });
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensures that the BingTranslator handles out-of-valid-key response
- * correctly. Sometimes Bing Translate replies with
- * "request credentials is not in an active state" error. BingTranslator
- * should catch this error and classify it as Service Unavailable.
- *
- */
-add_task(function* test_handling_out_of_valid_key_error() {
-
- // Simulating request from inactive subscription.
- Services.prefs.setCharPref(kClientIdPref, "testInactive");
-
- // Loading the fixture page.
- let url = constructFixtureURL("bug1022725-fr.html");
- let tab = yield promiseTestPageLoad(url);
-
- // Translating the contents of the loaded tab.
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- yield ContentTask.spawn(browser, null, function*() {
- Cu.import("resource:///modules/translation/BingTranslator.jsm");
- Cu.import("resource:///modules/translation/TranslationDocument.jsm");
-
- let client = new BingTranslator(
- new TranslationDocument(content.document), "fr", "en");
- client._resetToken();
- try {
- yield client.translate();
- } catch (ex) {
- // It is alright that the translation fails.
- }
- client._resetToken();
-
- // Checking if the client detected service and unavailable.
- Assert.ok(client._serviceUnavailable, "Service should be detected unavailable.");
- });
-
- // Cleaning up.
- Services.prefs.setCharPref(kClientIdPref, "testClient");
- gBrowser.removeTab(tab);
-});
-
-/**
- * A helper function for constructing a URL to a page stored in the
- * local fixture folder.
- *
- * @param filename Name of a fixture file.
- */
-function constructFixtureURL(filename) {
- // Deduce the Mochitest server address in use from a pref that was pre-processed.
- let server = Services.prefs.getCharPref("browser.translation.bing.authURL")
- .replace("http://", "");
- server = server.substr(0, server.indexOf("/"));
- let url = "http://" + server +
- "/browser/browser/components/translation/test/fixtures/" + filename;
- return url;
-}
-
-/**
- * A helper function to open a new tab and wait for its content to load.
- *
- * @param String url A URL to be loaded in the new tab.
- */
-function promiseTestPageLoad(url) {
- let deferred = Promise.defer();
- let tab = gBrowser.selectedTab = gBrowser.addTab(url);
- let browser = gBrowser.selectedBrowser;
- browser.addEventListener("load", function listener() {
- if (browser.currentURI.spec == "about:blank")
- return;
- info("Page loaded: " + browser.currentURI.spec);
- browser.removeEventListener("load", listener, true);
- deferred.resolve(tab);
- }, true);
- return deferred.promise;
-}
diff --git a/browser/components/translation/test/browser_translation_exceptions.js b/browser/components/translation/test/browser_translation_exceptions.js
deleted file mode 100644
index bf6875768..000000000
--- a/browser/components/translation/test/browser_translation_exceptions.js
+++ /dev/null
@@ -1,327 +0,0 @@
-/* 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/. */
-
-// tests the translation infobar, using a fake 'Translation' implementation.
-
-var tmp = {};
-Cu.import("resource:///modules/translation/Translation.jsm", tmp);
-Cu.import("resource://gre/modules/Promise.jsm", tmp);
-var {Translation, Promise} = tmp;
-
-const kLanguagesPref = "browser.translation.neverForLanguages";
-const kShowUIPref = "browser.translation.ui.show";
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref(kShowUIPref, true);
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- registerCleanupFunction(function () {
- gBrowser.removeTab(tab);
- Services.prefs.clearUserPref(kShowUIPref);
- });
- tab.linkedBrowser.addEventListener("load", function onload() {
- tab.linkedBrowser.removeEventListener("load", onload, true);
- Task.spawn(function* () {
- for (let test of gTests) {
- info(test.desc);
- yield test.run();
- }
- }).then(finish, ex => {
- ok(false, "Unexpected Exception: " + ex);
- finish();
- });
- }, true);
-
- content.location = "http://example.com/";
-}
-
-function getLanguageExceptions() {
- let langs = Services.prefs.getCharPref(kLanguagesPref);
- return langs ? langs.split(",") : [];
-}
-
-function getDomainExceptions() {
- let results = [];
- let enumerator = Services.perms.enumerator;
- while (enumerator.hasMoreElements()) {
- let perm = enumerator.getNext().QueryInterface(Ci.nsIPermission);
-
- if (perm.type == "translate" &&
- perm.capability == Services.perms.DENY_ACTION)
- results.push(perm.principal);
- }
-
- return results;
-}
-
-function getInfoBar() {
- let deferred = Promise.defer();
- let infobar =
- gBrowser.getNotificationBox().getNotificationWithValue("translation");
-
- if (!infobar) {
- deferred.resolve();
- } else {
- // Wait for all animations to finish
- Promise.all(infobar.getAnimations().map(animation => animation.finished))
- .then(() => deferred.resolve(infobar));
- }
-
- return deferred.promise;
-}
-
-function openPopup(aPopup) {
- let deferred = Promise.defer();
-
- aPopup.addEventListener("popupshown", function popupShown() {
- aPopup.removeEventListener("popupshown", popupShown);
- deferred.resolve();
- });
-
- aPopup.focus();
- // One down event to open the popup.
- EventUtils.synthesizeKey("VK_DOWN",
- { altKey: !navigator.platform.includes("Mac") });
-
- return deferred.promise;
-}
-
-function waitForWindowLoad(aWin) {
- let deferred = Promise.defer();
-
- aWin.addEventListener("load", function onload() {
- aWin.removeEventListener("load", onload, true);
- deferred.resolve();
- }, true);
-
- return deferred.promise;
-}
-
-
-var gTests = [
-
-{
- desc: "clean exception lists at startup",
- run: function checkNeverForLanguage() {
- is(getLanguageExceptions().length, 0,
- "we start with an empty list of languages to never translate");
- is(getDomainExceptions().length, 0,
- "we start with an empty list of sites to never translate");
- }
-},
-
-{
- desc: "never for language",
- run: function* checkNeverForLanguage() {
- // Show the infobar for example.com and fr.
- Translation.documentStateReceived(gBrowser.selectedBrowser,
- {state: Translation.STATE_OFFER,
- originalShown: true,
- detectedLanguage: "fr"});
- let notif = yield getInfoBar();
- ok(notif, "the infobar is visible");
- let ui = gBrowser.selectedBrowser.translationUI;
- let uri = gBrowser.selectedBrowser.currentURI;
- ok(ui.shouldShowInfoBar(uri, "fr"),
- "check shouldShowInfoBar initially returns true");
-
- // Open the "options" drop down.
- yield openPopup(notif._getAnonElt("options"));
- ok(notif._getAnonElt("options").getAttribute("open"),
- "the options menu is open");
-
- // Check that the item is not disabled.
- ok(!notif._getAnonElt("neverForLanguage").disabled,
- "The 'Never translate <language>' item isn't disabled");
-
- // Click the 'Never for French' item.
- notif._getAnonElt("neverForLanguage").click();
- notif = yield getInfoBar();
- ok(!notif, "infobar hidden");
-
- // Check this has been saved to the exceptions list.
- let langs = getLanguageExceptions();
- is(langs.length, 1, "one language in the exception list");
- is(langs[0], "fr", "correct language in the exception list");
- ok(!ui.shouldShowInfoBar(uri, "fr"),
- "the infobar wouldn't be shown anymore");
-
- // Reopen the infobar.
- PopupNotifications.getNotification("translate").anchorElement.click();
- notif = yield getInfoBar();
- // Open the "options" drop down.
- yield openPopup(notif._getAnonElt("options"));
- ok(notif._getAnonElt("neverForLanguage").disabled,
- "The 'Never translate French' item is disabled");
-
- // Cleanup.
- Services.prefs.setCharPref(kLanguagesPref, "");
- notif.close();
- }
-},
-
-{
- desc: "never for site",
- run: function* checkNeverForSite() {
- // Show the infobar for example.com and fr.
- Translation.documentStateReceived(gBrowser.selectedBrowser,
- {state: Translation.STATE_OFFER,
- originalShown: true,
- detectedLanguage: "fr"});
- let notif = yield getInfoBar();
- ok(notif, "the infobar is visible");
- let ui = gBrowser.selectedBrowser.translationUI;
- let uri = gBrowser.selectedBrowser.currentURI;
- ok(ui.shouldShowInfoBar(uri, "fr"),
- "check shouldShowInfoBar initially returns true");
-
- // Open the "options" drop down.
- yield openPopup(notif._getAnonElt("options"));
- ok(notif._getAnonElt("options").getAttribute("open"),
- "the options menu is open");
-
- // Check that the item is not disabled.
- ok(!notif._getAnonElt("neverForSite").disabled,
- "The 'Never translate site' item isn't disabled");
-
- // Click the 'Never for French' item.
- notif._getAnonElt("neverForSite").click();
- notif = yield getInfoBar();
- ok(!notif, "infobar hidden");
-
- // Check this has been saved to the exceptions list.
- let sites = getDomainExceptions();
- is(sites.length, 1, "one site in the exception list");
- is(sites[0].origin, "http://example.com", "correct site in the exception list");
- ok(!ui.shouldShowInfoBar(uri, "fr"),
- "the infobar wouldn't be shown anymore");
-
- // Reopen the infobar.
- PopupNotifications.getNotification("translate").anchorElement.click();
- notif = yield getInfoBar();
- // Open the "options" drop down.
- yield openPopup(notif._getAnonElt("options"));
- ok(notif._getAnonElt("neverForSite").disabled,
- "The 'Never translate French' item is disabled");
-
- // Cleanup.
- Services.perms.remove(makeURI("http://example.com"), "translate");
- notif.close();
- }
-},
-
-{
- desc: "language exception list",
- run: function* checkLanguageExceptions() {
- // Put 2 languages in the pref before opening the window to check
- // the list is displayed on load.
- Services.prefs.setCharPref(kLanguagesPref, "fr,de");
-
- // Open the translation exceptions dialog.
- let win = openDialog("chrome://browser/content/preferences/translation.xul",
- "Browser:TranslationExceptions",
- "", null);
- yield waitForWindowLoad(win);
-
- // Check that the list of language exceptions is loaded.
- let getById = win.document.getElementById.bind(win.document);
- let tree = getById("languagesTree");
- let remove = getById("removeLanguage");
- let removeAll = getById("removeAllLanguages");
- is(tree.view.rowCount, 2, "The language exceptions list has 2 items");
- ok(remove.disabled, "The 'Remove Language' button is disabled");
- ok(!removeAll.disabled, "The 'Remove All Languages' button is enabled");
-
- // Select the first item.
- tree.view.selection.select(0);
- ok(!remove.disabled, "The 'Remove Language' button is enabled");
-
- // Click the 'Remove' button.
- remove.click();
- is(tree.view.rowCount, 1, "The language exceptions now contains 1 item");
- is(getLanguageExceptions().length, 1, "One exception in the pref");
-
- // Clear the pref, and check the last item is removed from the display.
- Services.prefs.setCharPref(kLanguagesPref, "");
- is(tree.view.rowCount, 0, "The language exceptions list is empty");
- ok(remove.disabled, "The 'Remove Language' button is disabled");
- ok(removeAll.disabled, "The 'Remove All Languages' button is disabled");
-
- // Add an item and check it appears.
- Services.prefs.setCharPref(kLanguagesPref, "fr");
- is(tree.view.rowCount, 1, "The language exceptions list has 1 item");
- ok(remove.disabled, "The 'Remove Language' button is disabled");
- ok(!removeAll.disabled, "The 'Remove All Languages' button is enabled");
-
- // Click the 'Remove All' button.
- removeAll.click();
- is(tree.view.rowCount, 0, "The language exceptions list is empty");
- ok(remove.disabled, "The 'Remove Language' button is disabled");
- ok(removeAll.disabled, "The 'Remove All Languages' button is disabled");
- is(Services.prefs.getCharPref(kLanguagesPref), "", "The pref is empty");
-
- win.close();
- }
-},
-
-{
- desc: "domains exception list",
- run: function* checkDomainExceptions() {
- // Put 2 exceptions before opening the window to check the list is
- // displayed on load.
- let perms = Services.perms;
- perms.add(makeURI("http://example.org"), "translate", perms.DENY_ACTION);
- perms.add(makeURI("http://example.com"), "translate", perms.DENY_ACTION);
-
- // Open the translation exceptions dialog.
- let win = openDialog("chrome://browser/content/preferences/translation.xul",
- "Browser:TranslationExceptions",
- "", null);
- yield waitForWindowLoad(win);
-
- // Check that the list of language exceptions is loaded.
- let getById = win.document.getElementById.bind(win.document);
- let tree = getById("sitesTree");
- let remove = getById("removeSite");
- let removeAll = getById("removeAllSites");
- is(tree.view.rowCount, 2, "The sites exceptions list has 2 items");
- ok(remove.disabled, "The 'Remove Site' button is disabled");
- ok(!removeAll.disabled, "The 'Remove All Sites' button is enabled");
-
- // Select the first item.
- tree.view.selection.select(0);
- ok(!remove.disabled, "The 'Remove Site' button is enabled");
-
- // Click the 'Remove' button.
- remove.click();
- is(tree.view.rowCount, 1, "The site exceptions now contains 1 item");
- is(getDomainExceptions().length, 1, "One exception in the permissions");
-
- // Clear the permissions, and check the last item is removed from the display.
- perms.remove(makeURI("http://example.org"), "translate");
- perms.remove(makeURI("http://example.com"), "translate");
- is(tree.view.rowCount, 0, "The site exceptions list is empty");
- ok(remove.disabled, "The 'Remove Site' button is disabled");
- ok(removeAll.disabled, "The 'Remove All Site' button is disabled");
-
- // Add an item and check it appears.
- perms.add(makeURI("http://example.com"), "translate", perms.DENY_ACTION);
- is(tree.view.rowCount, 1, "The site exceptions list has 1 item");
- ok(remove.disabled, "The 'Remove Site' button is disabled");
- ok(!removeAll.disabled, "The 'Remove All Sites' button is enabled");
-
- // Click the 'Remove All' button.
- removeAll.click();
- is(tree.view.rowCount, 0, "The site exceptions list is empty");
- ok(remove.disabled, "The 'Remove Site' button is disabled");
- ok(removeAll.disabled, "The 'Remove All Sites' button is disabled");
- is(getDomainExceptions().length, 0, "No exceptions in the permissions");
-
- win.close();
- }
-}
-
-];
diff --git a/browser/components/translation/test/browser_translation_infobar.js b/browser/components/translation/test/browser_translation_infobar.js
deleted file mode 100644
index c16b3939c..000000000
--- a/browser/components/translation/test/browser_translation_infobar.js
+++ /dev/null
@@ -1,216 +0,0 @@
-/* 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/. */
-
-// tests the translation infobar, using a fake 'Translation' implementation.
-
-var tmp = {};
-Cu.import("resource:///modules/translation/Translation.jsm", tmp);
-var {Translation} = tmp;
-
-const kShowUIPref = "browser.translation.ui.show";
-
-function waitForCondition(condition, nextTest, errorMsg) {
- var tries = 0;
- var interval = setInterval(function() {
- if (tries >= 30) {
- ok(false, errorMsg);
- moveOn();
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, 100);
- var moveOn = function() { clearInterval(interval); nextTest(); };
-}
-
-var TranslationStub = {
- translate: function(aFrom, aTo) {
- this.state = Translation.STATE_TRANSLATING;
- this.translatedFrom = aFrom;
- this.translatedTo = aTo;
- },
-
- _reset: function() {
- this.translatedFrom = "";
- this.translatedTo = "";
- },
-
- failTranslation: function() {
- this.state = Translation.STATE_ERROR;
- this._reset();
- },
-
- finishTranslation: function() {
- this.showTranslatedContent();
- this.state = Translation.STATE_TRANSLATED;
- this._reset();
- }
-};
-
-function showTranslationUI(aDetectedLanguage) {
- let browser = gBrowser.selectedBrowser;
- Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER,
- originalShown: true,
- detectedLanguage: aDetectedLanguage});
- let ui = browser.translationUI;
- for (let name of ["translate", "_reset", "failTranslation", "finishTranslation"])
- ui[name] = TranslationStub[name];
- return ui.notificationBox.getNotificationWithValue("translation");
-}
-
-function hasTranslationInfoBar() {
- return !!gBrowser.getNotificationBox().getNotificationWithValue("translation");
-}
-
-function test() {
- waitForExplicitFinish();
-
- Services.prefs.setBoolPref(kShowUIPref, true);
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.addEventListener("load", function onload() {
- tab.linkedBrowser.removeEventListener("load", onload, true);
- TranslationStub.browser = gBrowser.selectedBrowser;
- registerCleanupFunction(function () {
- gBrowser.removeTab(tab);
- Services.prefs.clearUserPref(kShowUIPref);
- });
- run_tests(() => {
- finish();
- });
- }, true);
-
- content.location = "data:text/plain,test page";
-}
-
-function checkURLBarIcon(aExpectTranslated = false) {
- is(!PopupNotifications.getNotification("translate"), aExpectTranslated,
- "translate icon " + (aExpectTranslated ? "not " : "") + "shown");
- is(!!PopupNotifications.getNotification("translated"), aExpectTranslated,
- "translated icon " + (aExpectTranslated ? "" : "not ") + "shown");
-}
-
-function run_tests(aFinishCallback) {
- info("Show an info bar saying the current page is in French");
- let notif = showTranslationUI("fr");
- is(notif.state, Translation.STATE_OFFER, "the infobar is offering translation");
- is(notif._getAnonElt("detectedLanguage").value, "fr", "The detected language is displayed");
- checkURLBarIcon();
-
- info("Click the 'Translate' button");
- notif._getAnonElt("translate").click();
- is(notif.state, Translation.STATE_TRANSLATING, "the infobar is in the translating state");
- ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
- is(notif.translation.translatedFrom, "fr", "from language correct");
- is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "from language correct");
- checkURLBarIcon();
-
- info("Make the translation fail and check we are in the error state.");
- notif.translation.failTranslation();
- is(notif.state, Translation.STATE_ERROR, "infobar in the error state");
- checkURLBarIcon();
-
- info("Click the try again button");
- notif._getAnonElt("tryAgain").click();
- is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state");
- ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
- is(notif.translation.translatedFrom, "fr", "from language correct");
- is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "from language correct");
- checkURLBarIcon();
-
- info("Make the translation succeed and check we are in the 'translated' state.");
- notif.translation.finishTranslation();
- is(notif.state, Translation.STATE_TRANSLATED, "infobar in the translated state");
- checkURLBarIcon(true);
-
- info("Test 'Show original' / 'Show Translation' buttons.");
- // First check 'Show Original' is visible and 'Show Translation' is hidden.
- ok(!notif._getAnonElt("showOriginal").hidden, "'Show Original' button visible");
- ok(notif._getAnonElt("showTranslation").hidden, "'Show Translation' button hidden");
- // Click the button.
- notif._getAnonElt("showOriginal").click();
- // Check that the url bar icon shows the original content is displayed.
- checkURLBarIcon();
- // And the 'Show Translation' button is now visible.
- ok(notif._getAnonElt("showOriginal").hidden, "'Show Original' button hidden");
- ok(!notif._getAnonElt("showTranslation").hidden, "'Show Translation' button visible");
- // Click the 'Show Translation' button
- notif._getAnonElt("showTranslation").click();
- // Check that the url bar icon shows the page is translated.
- checkURLBarIcon(true);
- // Check that the 'Show Original' button is visible again.
- ok(!notif._getAnonElt("showOriginal").hidden, "'Show Original' button visible");
- ok(notif._getAnonElt("showTranslation").hidden, "'Show Translation' button hidden");
-
- info("Check that changing the source language causes a re-translation");
- let from = notif._getAnonElt("fromLanguage");
- from.value = "es";
- from.doCommand();
- is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state");
- ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
- is(notif.translation.translatedFrom, "es", "from language correct");
- is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "to language correct");
- // We want to show the 'translated' icon while re-translating,
- // because we are still displaying the previous translation.
- checkURLBarIcon(true);
- notif.translation.finishTranslation();
- checkURLBarIcon(true);
-
- info("Check that changing the target language causes a re-translation");
- let to = notif._getAnonElt("toLanguage");
- to.value = "pl";
- to.doCommand();
- is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state");
- ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
- is(notif.translation.translatedFrom, "es", "from language correct");
- is(notif.translation.translatedTo, "pl", "to language correct");
- checkURLBarIcon(true);
- notif.translation.finishTranslation();
- checkURLBarIcon(true);
-
- // Cleanup.
- notif.close();
-
- info("Reopen the info bar to check that it's possible to override the detected language.");
- notif = showTranslationUI("fr");
- is(notif.state, Translation.STATE_OFFER, "the infobar is offering translation");
- is(notif._getAnonElt("detectedLanguage").value, "fr", "The detected language is displayed");
- // Change the language and click 'Translate'
- notif._getAnonElt("detectedLanguage").value = "ja";
- notif._getAnonElt("translate").click();
- is(notif.state, Translation.STATE_TRANSLATING, "the infobar is in the translating state");
- ok(!!notif.translation.translatedFrom, "Translation.translate has been called");
- is(notif.translation.translatedFrom, "ja", "from language correct");
- notif.close();
-
- info("Reopen to check the 'Not Now' button closes the notification.");
- notif = showTranslationUI("fr");
- is(hasTranslationInfoBar(), true, "there's a 'translate' notification");
- notif._getAnonElt("notNow").click();
- is(hasTranslationInfoBar(), false, "no 'translate' notification after clicking 'not now'");
-
- info("Reopen to check the url bar icon closes the notification.");
- notif = showTranslationUI("fr");
- is(hasTranslationInfoBar(), true, "there's a 'translate' notification");
- PopupNotifications.getNotification("translate").anchorElement.click();
- is(hasTranslationInfoBar(), false, "no 'translate' notification after clicking the url bar icon");
-
- info("Check that clicking the url bar icon reopens the info bar");
- checkURLBarIcon();
- // Clicking the anchor element causes a 'showing' event to be sent
- // asynchronously to our callback that will then show the infobar.
- PopupNotifications.getNotification("translate").anchorElement.click();
- waitForCondition(hasTranslationInfoBar, () => {
- ok(hasTranslationInfoBar(), "there's a 'translate' notification");
- aFinishCallback();
- }, "timeout waiting for the info bar to reappear");
-}
diff --git a/browser/components/translation/test/browser_translation_telemetry.js b/browser/components/translation/test/browser_translation_telemetry.js
deleted file mode 100644
index e60bc17ef..000000000
--- a/browser/components/translation/test/browser_translation_telemetry.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var tmp = {};
-Cu.import("resource:///modules/translation/Translation.jsm", tmp);
-var {Translation, TranslationTelemetry} = tmp;
-const Telemetry = Services.telemetry;
-
-var MetricsChecker = {
- HISTOGRAMS: {
- OPPORTUNITIES : Services.telemetry.getHistogramById("TRANSLATION_OPPORTUNITIES"),
- OPPORTUNITIES_BY_LANG : Services.telemetry.getKeyedHistogramById("TRANSLATION_OPPORTUNITIES_BY_LANGUAGE"),
- PAGES : Services.telemetry.getHistogramById("TRANSLATED_PAGES"),
- PAGES_BY_LANG : Services.telemetry.getKeyedHistogramById("TRANSLATED_PAGES_BY_LANGUAGE"),
- CHARACTERS : Services.telemetry.getHistogramById("TRANSLATED_CHARACTERS"),
- DENIED : Services.telemetry.getHistogramById("DENIED_TRANSLATION_OFFERS"),
- AUTO_REJECTED : Services.telemetry.getHistogramById("AUTO_REJECTED_TRANSLATION_OFFERS"),
- SHOW_ORIGINAL : Services.telemetry.getHistogramById("REQUESTS_OF_ORIGINAL_CONTENT"),
- TARGET_CHANGES : Services.telemetry.getHistogramById("CHANGES_OF_TARGET_LANGUAGE"),
- DETECTION_CHANGES : Services.telemetry.getHistogramById("CHANGES_OF_DETECTED_LANGUAGE"),
- SHOW_UI : Services.telemetry.getHistogramById("SHOULD_TRANSLATION_UI_APPEAR"),
- DETECT_LANG : Services.telemetry.getHistogramById("SHOULD_AUTO_DETECT_LANGUAGE"),
- },
-
- reset: function() {
- for (let i of Object.keys(this.HISTOGRAMS)) {
- this.HISTOGRAMS[i].clear();
- }
- this.updateMetrics();
- },
-
- updateMetrics: function () {
- this._metrics = {
- opportunitiesCount: this.HISTOGRAMS.OPPORTUNITIES.snapshot().sum || 0,
- pageCount: this.HISTOGRAMS.PAGES.snapshot().sum || 0,
- charCount: this.HISTOGRAMS.CHARACTERS.snapshot().sum || 0,
- deniedOffers: this.HISTOGRAMS.DENIED.snapshot().sum || 0,
- autoRejectedOffers: this.HISTOGRAMS.AUTO_REJECTED.snapshot().sum || 0,
- showOriginal: this.HISTOGRAMS.SHOW_ORIGINAL.snapshot().sum || 0,
- detectedLanguageChangedBefore: this.HISTOGRAMS.DETECTION_CHANGES.snapshot().counts[1] || 0,
- detectedLanguageChangeAfter: this.HISTOGRAMS.DETECTION_CHANGES.snapshot().counts[0] || 0,
- targetLanguageChanged: this.HISTOGRAMS.TARGET_CHANGES.snapshot().sum || 0,
- showUI: this.HISTOGRAMS.SHOW_UI.snapshot().sum || 0,
- detectLang: this.HISTOGRAMS.DETECT_LANG.snapshot().sum || 0,
- // Metrics for Keyed histograms are estimated below.
- opportunitiesCountByLang: {},
- pageCountByLang: {}
- };
-
- let opportunities = this.HISTOGRAMS.OPPORTUNITIES_BY_LANG.snapshot();
- let pages = this.HISTOGRAMS.PAGES_BY_LANG.snapshot();
- for (let source of Translation.supportedSourceLanguages) {
- this._metrics.opportunitiesCountByLang[source] = opportunities[source] ?
- opportunities[source].sum : 0;
- for (let target of Translation.supportedTargetLanguages) {
- if (source === target) continue;
- let key = source + " -> " + target;
- this._metrics.pageCountByLang[key] = pages[key] ? pages[key].sum : 0;
- }
- }
- },
-
- /**
- * A recurrent loop for making assertions about collected metrics.
- */
- _assertionLoop: function (prevMetrics, metrics, additions) {
- for (let metric of Object.keys(additions)) {
- let addition = additions[metric];
- // Allows nesting metrics. Useful for keyed histograms.
- if (typeof addition === 'object') {
- this._assertionLoop(prevMetrics[metric], metrics[metric], addition);
- continue;
- }
- Assert.equal(prevMetrics[metric] + addition, metrics[metric]);
- }
- },
-
- checkAdditions: function (additions) {
- let prevMetrics = this._metrics;
- this.updateMetrics();
- this._assertionLoop(prevMetrics, this._metrics, additions);
- }
-
-};
-
-function getInfobarElement(browser, anonid) {
- let notif = browser.translationUI
- .notificationBox.getNotificationWithValue("translation");
- return notif._getAnonElt(anonid);
-}
-
-var offerTranslationFor = Task.async(function*(text, from) {
- // Create some content to translate.
- const dataUrl = "data:text/html;charset=utf-8," + text;
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, dataUrl);
-
- let browser = gBrowser.getBrowserForTab(tab);
-
- // Send a translation offer.
- Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER,
- originalShown: true,
- detectedLanguage: from});
-
- return tab;
-});
-
-var acceptTranslationOffer = Task.async(function*(tab) {
- let browser = tab.linkedBrowser;
- getInfobarElement(browser, "translate").doCommand();
- yield waitForMessage(browser, "Translation:Finished");
-});
-
-var translate = Task.async(function*(text, from, closeTab = true) {
- let tab = yield offerTranslationFor(text, from);
- yield acceptTranslationOffer(tab);
- if (closeTab) {
- gBrowser.removeTab(tab);
- return null;
- }
- return tab;
-});
-
-function waitForMessage({messageManager}, name) {
- return new Promise(resolve => {
- messageManager.addMessageListener(name, function onMessage() {
- messageManager.removeMessageListener(name, onMessage);
- resolve();
- });
- });
-}
-
-function simulateUserSelectInMenulist(menulist, value) {
- menulist.value = value;
- menulist.doCommand();
-}
-
-add_task(function* setup() {
- const setupPrefs = prefs => {
- let prefsBackup = {};
- for (let p of prefs) {
- prefsBackup[p] = Services.prefs.setBoolPref;
- Services.prefs.setBoolPref(p, true);
- }
- return prefsBackup;
- };
-
- const restorePrefs = (prefs, backup) => {
- for (let p of prefs) {
- Services.prefs.setBoolPref(p, backup[p]);
- }
- };
-
- const prefs = [
- "toolkit.telemetry.enabled",
- "browser.translation.detectLanguage",
- "browser.translation.ui.show"
- ];
-
- let prefsBackup = setupPrefs(prefs);
-
- let oldCanRecord = Telemetry.canRecordExtended;
- Telemetry.canRecordExtended = true;
-
- registerCleanupFunction(() => {
- restorePrefs(prefs, prefsBackup);
- Telemetry.canRecordExtended = oldCanRecord;
- });
-
- // Reset histogram metrics.
- MetricsChecker.reset();
-});
-
-add_task(function* test_telemetry() {
- // Translate a page.
- yield translate("<h1>Привет, мир!</h1>", "ru");
-
- // Translate another page.
- yield translate("<h1>Hallo Welt!</h1><h1>Bratwurst!</h1>", "de");
- yield MetricsChecker.checkAdditions({
- opportunitiesCount: 2,
- opportunitiesCountByLang: { "ru" : 1, "de" : 1 },
- pageCount: 1,
- pageCountByLang: { "de -> en" : 1 },
- charCount: 21,
- deniedOffers: 0
- });
-});
-
-add_task(function* test_deny_translation_metric() {
- function* offerAndDeny(elementAnonid) {
- let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "de", "en");
- getInfobarElement(tab.linkedBrowser, elementAnonid).doCommand();
- yield MetricsChecker.checkAdditions({ deniedOffers: 1 });
- gBrowser.removeTab(tab);
- }
-
- yield offerAndDeny("notNow");
- yield offerAndDeny("neverForSite");
- yield offerAndDeny("neverForLanguage");
- yield offerAndDeny("closeButton");
-
- // Test that the close button doesn't record a denied translation if
- // the infobar is not in its "offer" state.
- let tab = yield translate("<h1>Hallo Welt!</h1>", "de", false);
- yield MetricsChecker.checkAdditions({ deniedOffers: 0 });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_show_original() {
- let tab =
- yield translate("<h1>Hallo Welt!</h1><h1>Bratwurst!</h1>", "de", false);
- yield MetricsChecker.checkAdditions({ pageCount: 1, showOriginal: 0 });
- getInfobarElement(tab.linkedBrowser, "showOriginal").doCommand();
- yield MetricsChecker.checkAdditions({ pageCount: 0, showOriginal: 1 });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_language_change() {
- // This is run 4 times, the total additions are checked afterwards.
- for (let i of Array(4)) { // eslint-disable-line no-unused-vars
- let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "fr");
- let browser = tab.linkedBrowser;
- // In the offer state, translation is executed by the Translate button,
- // so we expect just a single recoding.
- let detectedLangMenulist = getInfobarElement(browser, "detectedLanguage");
- simulateUserSelectInMenulist(detectedLangMenulist, "de");
- simulateUserSelectInMenulist(detectedLangMenulist, "it");
- simulateUserSelectInMenulist(detectedLangMenulist, "de");
- yield acceptTranslationOffer(tab);
-
- // In the translated state, a change in the form or to menulists
- // triggers re-translation right away.
- let fromLangMenulist = getInfobarElement(browser, "fromLanguage");
- simulateUserSelectInMenulist(fromLangMenulist, "it");
- simulateUserSelectInMenulist(fromLangMenulist, "de");
-
- // Selecting the same item shouldn't count.
- simulateUserSelectInMenulist(fromLangMenulist, "de");
-
- let toLangMenulist = getInfobarElement(browser, "toLanguage");
- simulateUserSelectInMenulist(toLangMenulist, "fr");
- simulateUserSelectInMenulist(toLangMenulist, "en");
- simulateUserSelectInMenulist(toLangMenulist, "it");
-
- // Selecting the same item shouldn't count.
- simulateUserSelectInMenulist(toLangMenulist, "it");
-
- // Setting the target language to the source language is a no-op,
- // so it shouldn't count.
- simulateUserSelectInMenulist(toLangMenulist, "de");
-
- gBrowser.removeTab(tab);
- }
- yield MetricsChecker.checkAdditions({
- detectedLanguageChangedBefore: 4,
- detectedLanguageChangeAfter: 8,
- targetLanguageChanged: 12
- });
-});
-
-add_task(function* test_never_offer_translation() {
- Services.prefs.setCharPref("browser.translation.neverForLanguages", "fr");
-
- let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "fr");
-
- yield MetricsChecker.checkAdditions({
- autoRejectedOffers: 1,
- });
-
- gBrowser.removeTab(tab);
- Services.prefs.clearUserPref("browser.translation.neverForLanguages");
-});
-
-add_task(function* test_translation_preferences() {
-
- let preferenceChecks = {
- "browser.translation.ui.show" : [
- {value: false, expected: {showUI: 0}},
- {value: true, expected: {showUI: 1}}
- ],
- "browser.translation.detectLanguage" : [
- {value: false, expected: {detectLang: 0}},
- {value: true, expected: {detectLang: 1}}
- ],
- };
-
- for (let preference of Object.keys(preferenceChecks)) {
- for (let check of preferenceChecks[preference]) {
- MetricsChecker.reset();
- Services.prefs.setBoolPref(preference, check.value);
- // Preference metrics are collected once when the provider is initialized.
- TranslationTelemetry.init();
- yield MetricsChecker.checkAdditions(check.expected);
- }
- Services.prefs.clearUserPref(preference);
- }
-
-});
diff --git a/browser/components/translation/test/browser_translation_yandex.js b/browser/components/translation/test/browser_translation_yandex.js
deleted file mode 100644
index 6e0af18e6..000000000
--- a/browser/components/translation/test/browser_translation_yandex.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/* 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/. */
-
-// Test the Yandex Translator client against a mock Yandex service, yandex.sjs.
-
-"use strict";
-
-const kEnginePref = "browser.translation.engine";
-const kApiKeyPref = "browser.translation.yandex.apiKeyOverride";
-const kShowUIPref = "browser.translation.ui.show";
-
-const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
-const {Translation} = Cu.import("resource:///modules/translation/Translation.jsm", {});
-
-add_task(function* setup() {
- Services.prefs.setCharPref(kEnginePref, "yandex");
- Services.prefs.setCharPref(kApiKeyPref, "yandexValidKey");
- Services.prefs.setBoolPref(kShowUIPref, true);
-
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(kEnginePref);
- Services.prefs.clearUserPref(kApiKeyPref);
- Services.prefs.clearUserPref(kShowUIPref);
- });
-});
-
-/**
- * Ensure that the translation engine behaives as expected when translating
- * a sample page.
- */
-add_task(function* test_yandex_translation() {
-
- // Loading the fixture page.
- let url = constructFixtureURL("bug1022725-fr.html");
- let tab = yield promiseTestPageLoad(url);
-
- // Translating the contents of the loaded tab.
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
-
- yield ContentTask.spawn(browser, null, function*() {
- Cu.import("resource:///modules/translation/TranslationDocument.jsm");
- Cu.import("resource:///modules/translation/YandexTranslator.jsm");
-
- let client = new YandexTranslator(
- new TranslationDocument(content.document), "fr", "en");
- let result = yield client.translate();
-
- Assert.ok(result, "There should be a result.");
- });
-
- gBrowser.removeTab(tab);
-});
-
-/**
- * Ensure that Yandex.Translate is propertly attributed.
- */
-add_task(function* test_yandex_attribution() {
- // Loading the fixture page.
- let url = constructFixtureURL("bug1022725-fr.html");
- let tab = yield promiseTestPageLoad(url);
-
- info("Show an info bar saying the current page is in French");
- let notif = showTranslationUI(tab, "fr");
- let attribution = notif._getAnonElt("translationEngine").selectedIndex;
- Assert.equal(attribution, 1, "Yandex attribution should be shown.");
-
- gBrowser.removeTab(tab);
-});
-
-
-add_task(function* test_preference_attribution() {
-
- let prefUrl = "about:preferences#content";
- let tab = yield promiseTestPageLoad(prefUrl);
-
- let browser = gBrowser.getBrowserForTab(tab);
- let win = browser.contentWindow;
- let bingAttribution = win.document.getElementById("bingAttribution");
- ok(bingAttribution, "Bing attribution should exist.");
- ok(bingAttribution.hidden, "Bing attribution should be hidden.");
-
- gBrowser.removeTab(tab);
-
-});
-
-/**
- * A helper function for constructing a URL to a page stored in the
- * local fixture folder.
- *
- * @param filename Name of a fixture file.
- */
-function constructFixtureURL(filename) {
- // Deduce the Mochitest server address in use from a pref that was pre-processed.
- let server = Services.prefs.getCharPref("browser.translation.yandex.translateURLOverride")
- .replace("http://", "");
- server = server.substr(0, server.indexOf("/"));
- let url = "http://" + server +
- "/browser/browser/components/translation/test/fixtures/" + filename;
- return url;
-}
-
-/**
- * A helper function to open a new tab and wait for its content to load.
- *
- * @param String url A URL to be loaded in the new tab.
- */
-function promiseTestPageLoad(url) {
- let deferred = Promise.defer();
- let tab = gBrowser.selectedTab = gBrowser.addTab(url);
- let browser = gBrowser.selectedBrowser;
- browser.addEventListener("load", function listener() {
- if (browser.currentURI.spec == "about:blank")
- return;
- info("Page loaded: " + browser.currentURI.spec);
- browser.removeEventListener("load", listener, true);
- deferred.resolve(tab);
- }, true);
- return deferred.promise;
-}
-
-function showTranslationUI(tab, aDetectedLanguage) {
- let browser = gBrowser.selectedBrowser;
- Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER,
- originalShown: true,
- detectedLanguage: aDetectedLanguage});
- let ui = browser.translationUI;
- return ui.notificationBox.getNotificationWithValue("translation");
-}
diff --git a/browser/components/translation/test/fixtures/bug1022725-fr.html b/browser/components/translation/test/fixtures/bug1022725-fr.html
deleted file mode 100644
index f30edf52e..000000000
--- a/browser/components/translation/test/fixtures/bug1022725-fr.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!doctype html>
-<html lang="fr">
- <head>
- <!--
- - Text retrieved from http://fr.wikipedia.org/wiki/Coupe_du_monde_de_football_de_2014
- - at 06/13/2014, Creative Commons Attribution-ShareAlike License.
- -->
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>test</title>
- </head>
- <body>
- <h1>Coupe du monde de football de 2014</h1>
- <div>La Coupe du monde de football de 2014 est la 20e édition de la Coupe du monde de football, compétition organisée par la FIFA et qui réunit les trente-deux meilleures sélections nationales. Sa phase finale a lieu à l'été 2014 au Brésil. Avec le pays organisateur, toutes les équipes championnes du monde depuis 1930 (Uruguay, Italie, Allemagne, Angleterre, Argentine, France et Espagne) se sont qualifiées pour cette compétition. Elle est aussi la première compétition internationale de la Bosnie-Herzégovine.</div>
- </body>
-</html>
diff --git a/browser/components/translation/test/fixtures/result-da39a3ee5e.txt b/browser/components/translation/test/fixtures/result-da39a3ee5e.txt
deleted file mode 100644
index d2d14c788..000000000
--- a/browser/components/translation/test/fixtures/result-da39a3ee5e.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-<ArrayOfTranslateArrayResponse xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
- <TranslateArrayResponse>
- <From>fr</From>
- <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
- <a:int>34</a:int>
- </OriginalTextSentenceLengths>
- <TranslatedText>Football's 2014 World Cup</TranslatedText>
- <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
- <a:int>25</a:int>
- </TranslatedTextSentenceLengths>
- </TranslateArrayResponse>
- <TranslateArrayResponse>
- <From>fr</From>
- <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
- <a:int>508</a:int>
- </OriginalTextSentenceLengths>
- <TranslatedText>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus diam sem, porttitor eget neque sit amet, ultricies posuere metus. Cras placerat rutrum risus, nec dignissim magna dictum vitae. Fusce eleifend fermentum lacinia. Nulla sagittis cursus nibh. Praesent adipiscing, elit at pulvinar dapibus, neque massa tincidunt sapien, eu consectetur lectus metus sit amet odio. Proin blandit consequat porttitor. Pellentesque vehicula justo sed luctus vestibulum. Donec metus.</TranslatedText>
- <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
- <a:int>475</a:int>
- </TranslatedTextSentenceLengths>
- </TranslateArrayResponse>
-</ArrayOfTranslateArrayResponse>
diff --git a/browser/components/translation/test/fixtures/result-yandex-d448894848.json b/browser/components/translation/test/fixtures/result-yandex-d448894848.json
deleted file mode 100644
index de2f5650e..000000000
--- a/browser/components/translation/test/fixtures/result-yandex-d448894848.json
+++ /dev/null
@@ -1 +0,0 @@
-{"code":200,"lang":"fr-en","text":["Football's 2014 World Cup","Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus diam sem, porttitor eget neque sit amet, ultricies posuere metus. Cras placerat rutrum risus, nec dignissim magna dictum vitae. Fusce eleifend fermentum lacinia. Nulla sagittis cursus nibh. Praesent adipiscing, elit at pulvinar dapibus, neque massa tincidunt sapien, eu consectetur lectus metus sit amet odio. Proin blandit consequat porttitor. Pellentesque vehicula justo sed luctus vestibulum. Donec metus."]}
diff --git a/browser/components/translation/test/unit/.eslintrc.js b/browser/components/translation/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/components/translation/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/components/translation/test/unit/test_cld2.js b/browser/components/translation/test/unit/test_cld2.js
deleted file mode 100644
index 9ebc4d766..000000000
--- a/browser/components/translation/test/unit/test_cld2.js
+++ /dev/null
@@ -1,463 +0,0 @@
-// Copyright 2013 Google Inc. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//
-// Author: dsites@google.com (Dick Sites)
-//
-// Unit test compact language detector, CLD2
-//
-
-// Test strings.
-const kTeststr_en =
- "confiscation of goods is assigned as the penalty part most of the courts " +
- "consist of members and when it is necessary to bring public cases before a " +
- "jury of members two courts combine for the purpose the most important cases " +
- "of all are brought jurors or";
-
-const kTeststr_aa_Latn = " nagay tanito nagay tanto nagayna naharsi nahrur nake nala nammay nammay haytu nanu narig ne ni num numu o obare obe obe obisse oggole ogli olloyta ongorowe orbise othoga r rabe rade ra e rage rakub rasitte rasu reyta rog ruddi ruga s sa al bada sa ala";
-const kTeststr_ab_Cyrl = " а зуа абзиара дақәшәоит ан лыбзиабара ахә амаӡам ауаҩы игәы иҭоу ихы иҿы ианубаалоит Ð°Ò§Ò³Ó™Ñ‹Ñ Ò§ÑˆÓ¡Ð° ахацәа лышьҭоуп аҿааÑҭа лара дрышьҭоуп";
-const kTeststr_af_Latn = " aam skukuza die naam beteken hy wat skoonvee of hy wat alles onderstebo keer wysig bosveldkampe boskampe is kleiner afgeleë ruskampe wat oor min fasiliteite beskik daar is geen restaurante of winkels nie en slegs oornagbesoekers word toegelaat bateleur";
-const kTeststr_ak_Latn = "Wɔwoo Hilla Limann Mumu-Ɔpɛnimba 12 afe 1934. Wɔwoo no wɔ Gwollu wɔ Sisala Mantaw mu Nna ne maame yɛ Mma Hayawah. Ne papa so nna ɔyɛ Babini Yomu. Ɔwarr Fulera Limann ? Ne mba yɛ esuon-- Lariba Montia [wɔwoo no Limann]; Baba Limann; Sibi Andan [wɔwoo no Limann]; Lida Limann; Danni Limann; Zilla Limann na Salma Limann. Ɔtenaa ase kɔpemm Sanda-Kwakwa da ɛtɔ so 23 wɔ afe 1998 wɔ ?.";
-const kTeststr_am_Ethi = " ለመጠይቅ ወደ እስክንድርያ ላኩዋቸá‹áŠ“ የእስክንድርያ ጳጳስ አቴናስዮስ áሬáˆáŠ•áŒ¦áˆµáŠ• እራሳቸá‹áŠ• ሾመዠáˆáŠ¨á‹‹áˆ ከዚያ እስከ á‹“ ሠድረስ የኢትዮጵያ አቡáŠ";
-const kTeststr_ar_Arab = "احتيالية بيع أي حساب";
-const kTeststr_as_Beng = "অঞà§à¦šà¦² নতà§à¦¨ সদসà§à¦¯à¦¬à§ƒà¦¨à§à¦¦ সকলোৱে ভৰà§à¦¤à¦¿ হব পাৰে মà§à¦² পৃষà§à¦ à¦¾ জন লেখক গà§à¦— ল দল সাৰাংশ ই পতà§à§° টা বাৰà§à¦¤à¦¾ à¦à¦œà¦¨";
-const kTeststr_ay_Latn = " aru wijar aru ispañula ukaran aru witanam aru kurti aru kalis aru warani aru malta aru yatiyawi niya jakitanaka isluwiñ aru lmir phuran aru masirunan aru purtukal aru kruwat aru jakira urtu aru inklisa pirsan aru suyku aru malay aru jisk aptayma thaya";
-const kTeststr_az_Arab = " آذربایجان دا انسان حاقلاری ائوی آچیلاجاق ب Ù… ت ائلچيسي برمه موخاليÙتي نين ليدئري ايله گؤروشه بيليب ترس شوونيسم Ùارس از آزادي ملتهاي تورکمن";
-const kTeststr_az_Latn = " a az qalıb breyn rinq intellektual oyunu üzrə yarışın zona mərhələləri keçirilib miq un qalıqlarının dənizdən çıxarılması davam edir məhəmməd peyğəmbərin karikaturalarını çap edən qəzetin baş redaktoru iş otağında ölüb";
-const kTeststr_ba_Cyrl = " арналђан бындай ђилми Ñш тіркињлњ тњјге тапєыр нњшер ителњ ғинуар бєхет именлектє етешлектє ауыл ўќмерџєре хеџмєт юлын ћайлаѓанда";
-const kTeststr_be_Cyrl = " а друкаваць Ñ–Ñ… не было Ñ‚Ñхнічна магчыма бліжÑй за вільню тым Ñамым чаÑам нÑмецкае кіраўніцтва прапаноўвала апроч ўвÑÐ´Ð·ÐµÐ½Ð½Ñ Ð»Ð°Ñ†Ñ–Ð½ÐºÑ– Ñе";
-const kTeststr_bg_Cyrl = " а дума попада в ÑÑŠÑтоÑние на изпитание ключовите думи Ñ Ð¿Ñ€ÐµÐ´Ñказана малко под то изиÑкване на Ñтраниците за Ñ‚ÑŠÑ€Ñене в";
-// From 10% testing part of new lang=bh scrape
-const kTeststr_bh_Deva = "काल में उनका हमला से बचे खाती à¤à¤¹à¤¿à¤œà¤¾ भाग के अइले आ भोजपà¥à¤° नाम से नगर बसवले. à¤à¤•à¤°à¤¾ बारे में विसà¥à¤¤à¤¾à¤° से जानकारी नीचे दीहल गइल बा. बाकिर आशà¥à¤šà¤°à¥à¤¯à¤œà¤¨à¤• रूप से मालवा के राजा भोज के बिहार आवे आ भोजपà¥à¤° नगर बसावे आ चाहे भोजपà¥à¤°à¥€ के साथे उनकर कवनो संबंध होखे के कवनो जानकारी भोपाल के भोज संसà¥à¤¥à¤¾à¤¨ आ चाहे मधà¥à¤¯ पà¥à¤°à¤¦à¥‡à¤¶ के इतिहासकार लोगन के तनिको नइखे. हालांकि ऊ सब लोग à¤à¤¹ बात के मानत बा कि à¤à¤•à¤°à¤¾ बारे में अबहीं तकले मूरà¥à¤¤à¤¿ बनवइलें. राजा भोज के जवना जगहा पऽ वागà¥à¤¦à¥‡à¤µà¥€ के दरà¥à¤¶à¤¨ भइल रहे, ओही सà¥à¤¥à¤¾à¤¨ पऽ à¤à¤¹ मूरà¥à¤¤à¤¿ के सà¥à¤¥à¤¾à¤ªà¤¨à¤¾ कइल गइल. अब अगर à¤à¤¹ मंदिर के à¤à¤¹ शिलालेख के तसà¥à¤µà¥€à¤° (पृषà¥à¤  संखà¥à¤¯à¤¾ 33 पऽ पà¥à¤°à¤•à¤¾à¤¶à¤¿à¤¤) रउआ धेयान से देखीं तऽ à¤à¤•à¤°à¤¾ पऽ कैथी लिपि में -सीताराम- लिखल साफ लउकत बा. कैथी भोजपà¥à¤°à¥€ के बहà¥à¤¤ पà¥à¤°à¤šà¤²à¤¿à¤¤ लिपि रहल बिया. à¤à¤•à¤°à¤¾ बारे में कवनो शंका संदेह बिहार-यूपी के जानकार लोगन में नइखे. à¤à¤². à¤à¤¸. à¤à¤¸. वो माले के लिखल पढ़ीं ";
-
-const kTeststr_bi_Latn = " king wantaem nomo hem i sakem setan mo ol rabis enjel blong hem oli aot long heven oli kamdaon long wol taswe ol samting oli kam nogud olgeta long wol ya stat long revelesen ol faet kakae i sot ol sik mo fasin blong brekem loa oli kam antap olgeta samting";
-const kTeststr_blu_Latn = " Kuv hlub koj txawm lub ntuj yuav si ntshi nphaus los kuv tsis ua siab nkaug txawm ntiab teb yuav si ntshi nphaus los kuv tseem ua lon tsaug vim kuv hlub koj tag lub siab";
-const kTeststr_blu_Latn2 = "Kuv hnov Txhiaj Xeeb Vaj, co-owner of Hmong Village Shopping Center, hais ua hnub ua hmo tias kom Hmoob yuav tsum txhawb Hmoob thiab listed cov mini-shops uas nyob rau hauv nws lub MALL txhua txhua kom sawv daws mus txhawb, tiam sis uas cas zaum twg twb pom nws mus kav kiav hauv taj laj qhabmeem (Sun Foods) xwb tiag. Nag hmo kuv pom nws mus shopping nrog nws poj niam hauv Sun Foods. Thaum tawm mus txog nraum parking lot kuv thiaj txhob txwm mus ze ze seb ua li nws mus yuav dab tsi tiag, thiab seb tej uas nws yuav ntawd puas muaj nyob ntawm tej kiab khw Hmoob. Surprised!!! Vuag.... txhua yam nws yuav hauv Sun Foods peb Hmoob cov khw yeej muaj tag nrho. Peb niaj hnub nqua hu kom Hmoob yuav tsum pab Hmoob yog pab li no lod?";
-// From 10% testing part of new lang=bn scrape
-const kTeststr_bn_Beng = "গà§à¦¯à¦¾à¦²à¦¾à¦°à¦¿à¦° ৩৮ বছর পূরà§à¦¤à¦¿à¦¤à§‡ মূলà§à¦¯à¦›à¦¾à§œ অরà§à¦¥à¦¨à§€à¦¤à¦¿ বিà¦à¦¨à¦ªà¦¿à¦° ওয়াক আউট তপন চৌধà§à¦°à§€ হারবাল অà§à¦¯à¦¾à¦¸à§‹à¦¸à¦¿à§Ÿà§‡à¦¶à¦¨à§‡à¦° সভাপতি আনà§à¦¤à¦°à§à¦œà¦¾à¦¤à¦¿à¦• পরামরà§à¦¶à¦• বোরà§à¦¡ দিয়ে শরিয়াহৠইননà§à¦¡à§‡à¦•à§à¦¸ করবে সিà¦à¦¸à¦‡ মালিকপকà§à¦·à§‡à¦° কানà§à¦¨à¦¾, শà§à¦°à¦®à¦¿à¦•à§‡à¦° অনিশà§à¦šà§Ÿà¦¤à¦¾ মতিà¦à¦¿à¦²à§‡ সমাবেশ নিষিদà§à¦§: à¦à¦«à¦¬à¦¿à¦¸à¦¿à¦¸à¦¿à¦†à¦‡à§Ÿà§‡à¦° ধনà§à¦¯à¦¬à¦¾à¦¦ বিনোদন বিশেষ পà§à¦°à¦¤à¦¿à¦¬à§‡à¦¦à¦¨ বাংলালিংকের গà§à¦°à§à¦¯à¦¾à¦¨à§à¦¡à¦®à¦¾à¦¸à§à¦Ÿà¦¾à¦° সিজন-৩ বà§à¦°à¦¾à¦œà¦¿à¦²à§‡ বিশà§à¦¬à¦•à¦¾à¦ª ফà§à¦Ÿà¦¬à¦² আয়োজনবিরোধী বিকà§à¦·à§‹à¦­ দেশের নিরাপতà§à¦¤à¦¾à¦° চেয়ে অনেক বেশি সচেতন । পà§à¦°à¦¾à¦°à§à¦¥à§€à¦¦à§‡à¦° দকà§à¦·à¦¤à¦¾ ও যোগà§à¦¯à¦¤à¦¾à¦° পাশাপাশি তারা জাতীয় ইসà§à¦¯à§à¦—à§à¦²à§‹à¦¤à§‡ পà§à¦°à¦¾à¦§à¦¾à¦¨à§à¦¯ দিয়েছেন । †পাà¦à¦šà¦Ÿà¦¿ সিটিতে ২০ লাখ ভোটারদের দিয়ে জাতীয় নিরà§à¦¬à¦¾à¦šà¦¨à§‡ ৮ কোটি ভোটারদের সঙà§à¦—ে তà§à¦²à¦¨à¦¾ করা যাবে কি à¦à¦•à¦œà¦¨ দরà§à¦¶à¦•à§‡à¦° à¦à¦®à¦¨ পà§à¦°à¦¶à§à¦¨à§‡ জবাবে আবà§à¦¦à§à¦²à§à¦²à¦¾à¦¹ আল নোমান বলেন , “ à¦à¦‡ পাà¦à¦šà¦Ÿà¦¿ সিটি করà§à¦ªà§‹à¦°à§‡à¦¶à¦¨ নিরà§à¦¬à¦¾à¦šà¦¨ দেশের পাà¦à¦šà¦Ÿà¦¿ বড় বিভাগের পà§à¦°à¦¤à¦¿à¦¨à¦¿à¦§à¦¿à¦¤à§à¦¬ করছে । à¦à¦›à¦¾à§œà¦¾ à¦à¦–ানকার ভোটার রা সবাই সচেতন । তারা";
-
-// From 10% testing part of new lang=bo scrape
-const kTeststr_bo_Tibt = " ་གྱིས་à½à¼‹à½†à½ºà½ à½²à¼‹à½•à¾±à½‚་འཚལ་à½à½„་ཞིག་བཤིག་སྲིད་པ༠ཡར་ཀླུང་གཙང་པོར་ཆ ུ་མཛོང་བརྒྱག་རྒྱུའི་ལས་འཆར་ལ་རྒྱ་གར་གྱི་སེམས་ཚབས༠རྒྱ་གརགྱི་མཚོ་འོག་དམག་གྲུར་སྦར་གས་བྱུང་བ༠པ་ཀི་སི་à½à½“་གྱིས་རྒྱ་གར་ལ་མི་སེར་བསད་པའི་སà¾à¾±à½¼à½“་འཛུགས་བྱས་པ༠རྩོམ་ཡིག་མང་བ༠འབྲེལ་མà½à½´à½‘་བརྒྱུད་ལམ༠à½à½¼à½“་སà¾à¾±à½ºà½‘་དང་སྲི་ཞུ༠་à½à½¼à½‚་དེབ་བཞི་ དཔར་འགྲེམས་གནང་ཡོད་པ་དང་བོད་ཡིག་དྲ་ཚིགས་à½à½‚་ནང་ལ་ཡང་རྩོམ་ཡང་ཡང་བྲིས་གནང་མà½à½“་རེད༠ལེ་ཚན་à½à½‚ ལེ་ཚན་à½à½‚ འབྲེལ་ཡོད༠འགྲེམ་སྟོན༠རྒྱུད་ལམ་སྣ་མང་ཡིག་མཛོད༠བཀོལ་སྤྱོད་པའི་འཇོག་ཡུལ་དྲ་ངོས༠སྔོན་མ༠རྗེས་མ༠བསྟན་འཛིན་བདེ་སà¾à¾±à½²à½‘༠ཚེ་རིང་རྣམ་རྒྱལ༠བསྟན་འཛིན་ངག་དབང་༠ཡོལ་གདོང་ཚེ་རིང་ལྷག་པ༠་དབང་ ཕྱུག་གཉིས་ཀྱིས་བརྗོད་གཞི་བྱེ་བྲག་པ་ཞིག་ལ་བགྲོ་གླེང་གà½à½²à½„་ཟབ་བྱེད་པའི་གཟའ་ འà½à½¼à½¢à¼‹à½‚ཉིས་རེའི་མཚམས་ཀྱི་ལེ་ཚན་ཞིག་ཡིན༠དཔྱད་ཞིབ་ཀྱིས་རྒྱ་ནག་ནང་à½à½´à½£à¼‹à½‚ྱི་འགྱུར་ལྡོག་དང༌༠རྒྱ་ནག་དང་རྒྱལ་སྤྱིའི་འབྲེལ་བར་དམིགས་སུ་བཀར་ནས་བགྲོ་གླེང་བྱེད་ཀྱི་ཡོདà¼à¼ རྒྱང་སྲིང་དུས་ཚོདà¼";
-
-const kTeststr_br_Latn = " a chom met leuskel a ra e blas da jack irons dilabour hag aet kuit eus what is this dibab a reont da c houde michael beinhorn evit produiñ an trede pladenn kavet e vez ar ganaouennoù buhan ha buhan ganto setu stummet ar bladenn adkavet e vez enni funk";
-const kTeststr_bs_Cyrl = "иÑторија боÑне књ иÑторија боÑне књ иÑторија боÑне књ иÑторија боÑне књ ";
-// From 10% testing part of new lang=bs scrape
-const kTeststr_bs_Latn = "Novi predsjednik MeÅ¡ihata Islamske zajednice u Srbiji (IZuS) i muftija dr. Mevlud ef. Dudić izjavio je u intervjuu za Anadolu Agency (AA) kako je uvjeren da će doći do vraćanja jedinstva meÄ‘u muslimanima i unutar Islamske zajednice na prostoru Sandžaka, te da je njegova ruka pružena za povratak svih u okrilje Islamske zajednice u Srbiji nakon skoro sedam godina podjela u tom dijelu Srbije. Dudić je za predsjednika MeÅ¡ihata IZ u Srbiji izabran 4. januara, a zvaniÄna inauguracija će biti obavljena u prvoj polovini februara. Kako se oÄekuje, prisustvovat će joj i reisu-l-ulema Islamske zajednice u Srbiji Husein ef. Kavazović koji će i zvaniÄno promovirati Dudića u novog prvog Äovjeka IZ u Srbiji. Dudić će danas boraviti u prvoj zvaniÄnoj posjeti reisu Kavazoviću, Å¡to je njegov privi simboliÄni potez nakon imenovanja. ";
-
-const kTeststr_ca_Latn = "al final en un únic lloc nhorabona l correu electrònic està concebut com a eina de productivitat aleshores per què perdre el temps arxivant missatges per després intentar recordar on els veu desar i per què heu d eliminar missatges importants per l";
-const kTeststr_ceb_Latn = "Ang Sugbo usa sa mga labing ugmad nga lalawigan sa nasod. Kini ang sentro sa komersyo, edukasyon ug industriya sa sentral ug habagatang dapit sa kapupod-an. Ang mipadayag sa Sugbo isip ikapito nga labing nindot nga pulo sa , ang nag-inusarang pulo sa Pilipinas nga napasidunggan sa maong magasin sukad pa sa tuig";
-const kTeststr_ceb_Latn2 = "Ang mga komyun sa Pransiya duol-duol sa inkorporadong mga lungsod ug mga dakbayan sa Estados Unidos. Wala kini susamang istruktura sa Hiniusang Gingharian (UK) tungod kay ang estado niini taliwala sa di-metropolitan nga distrito ug sa sibil nga parokya. Wala usab kini susamang istruktura sa Pilipinas.";
-const kTeststr_chr_Cher = "ᎠᎢáᎩ ᎠáŸáŽ¶áá— á¥á„áá›áŽ© ᎦᎫáá›á…Ꭿ ᎾᎥᎢ";
-const kTeststr_co_Latn = " a prupusitu di risultati for utilizà a scatula per ricercà ind issi risultati servore errore u servore ha incuntratu una errore pruvisoria é ùn ha pussutu compie a vostra dumanda per piacè acimenta dinò ind una minuta tuttu listessu ligami truvà i";
-const kTeststr_crs_Latn = "Sesel ou menm nou sel patri. Kot nou viv dan larmoni. Lazwa, lanmour ek lape. Nou remersye Bondye. Preserv labote nou pei. Larises nou losean. En leritaz byen presye. Pour boner nou zanfan. Reste touzour dan linite. Fer monte nou paviyon. Ansanm pou tou leternite. Koste Seselwa!";
-const kTeststr_cs_Latn = " a akci opakujte film uložen vykreslit gmail tokio smazat obsah adresáře nelze naÄíst systémový profil jednotky smoot okud používáte pro urÄení polokoule znaÄky z západ nebo v východ používejte nezáporné hodnoty zemÄ›pisné délky nelze";
-const kTeststr_cy_Latn = " a chofrestru eich cyfrif ymwelwch a unwaith i chi greu eich cyfrif mi fydd yn cael ei hysbysu o ch cyfeiriad ebost newydd fel eich bod yn gallu cadw mewn cysylltiad drwy gmail os nad ydych chi wedi clywed yn barod am gmail mae n gwasanaeth gwebost";
-const kTeststr_da_Latn = " a z tallene og punktummer der er tilladte log ud angiv den ønskede adgangskode igen november gem personlige oplysninger kontrolspørgsmål det sidste tegn i dit brugernavn skal være et bogstav a z eller tal skriv de tegn du kan se i billedet nedenfor";
-const kTeststr_de_Latn = " abschnitt ordner aktivieren werden die ordnereinstellungen im farbabschnitt deaktiviert öchten sie wirklich fortfahren eldtypen angeben optional n diesem schritt geben sie für jedesfeld aus dem datenset den typ an ieser schritt ist optional eldtypen";
-const kTeststr_dv_Thaa = " Þ€Þ¨Þ‚Þ°Þ‹Þ© Þ„Þ¦Þ€ÞªÞ‚Þ° ÞˆÞ§Þ€Þ¦Þ†Þ¦ Þ‹Þ¦Þ‡Þ°Þ†Þ§Þ‡Þ¨ÞƒÞª Þ‹Þ¬ÞˆÞ¦Þ‚Þ¦ Þ„Þ¦Þ€Þ¬Þ‡Þ°ÞŽÞ¬ ގޮތުގައާއި Þ‡Þ¬Þ‚Þ«Þ‚Þ° ގޮތްގޮތުން Þ€Þ¨Þ‚Þ°Þ‹Þ© Þ„Þ¦Þ€ÞªÞ‚Þ° ÞˆÞ§Þ€Þ¦Þ†Þ¦ Þ‹Þ¦Þ‡Þ°Þ†Þ§ Þ‰Þ©Þ€ÞªÞ‚Þ°ÞŽÞ¬ Þ‡Þ¦Þ‹Þ¦Þ‹Þª Þ‰Þ¨ÞÞ¨Þ‡Þ¦Þ‚Þ¦ÞÞ°";
-const kTeststr_dz_Tibt = " རྩིས བརà¾à¾±à½– ཚུལ ལྡན དང ངེས བདེན སྦ སྟོན ནིའི དོན ལུ à½à¾±à½¼à½‘ གུག ཤད ལག ལེན འà½à½– དགོ ག དང ཨིན པུཊི གྲལ à½à½²à½‚ གུ";
-const kTeststr_ee_Latn = "Yi (Di tanya sia) tatia akɔ wò ayi axa yeye dzi kple tanya si sɔ kple esi wòŋlɔ ɖe goa me, negbe axaa ɖe li kpakple tanya mawo xoxo ko. Teƒe le axa yeye sia dzi si wòateŋu atia na kpekpeɖeŋu kple nuwoŋlɔŋlɔ ne anɔ hahiãm na wò. Mehiã be na gbugbɔ ava afii na axa yeye gɔmedzedze o. Woateŋu adze wo gɔme kple nuŋɔŋlɔ dzẽwo tatia. Megavɔ̃ na nuyeyewo gɔmedzedze kroa o.";
-const kTeststr_el_Grek = " ή αÏνητική αναζήτηση λέξης ÎºÎ»ÎµÎ¹Î´Î¹Î¿Ï ÎºÎ±Ï„Î±ÏƒÏ„Î®ÏƒÏ„Îµ τις μεμονωμένες λέξεις κλειδιά πεÏισσότεÏο στοχοθετημένες με τη μετατÏοπή τους σε";
-const kTeststr_en_Latn = " a backup credit card by visiting your billing preferences page or visit the adwords help centre for more details https adwords google com support bin answer py answer hl en we were unable to process the payment of for your outstanding google adwords";
-const kTeststr_eo_Latn = " a jarcento refoje per enmetado de koncerna pastro tiam de reformita konfesio ekde refoje ekzistis luteranaj komunumanoj tamen tiuj fondis propran komunumon nur en ambaÅ­ apartenis ekde al la evangela eklezio en prusio resp ties rejnlanda provinceklezio en";
-const kTeststr_es_Latn = " a continuación haz clic en el botón obtener ruta también puedes desplazarte hasta el final de la página para cambiar tus opciones de búsqueda gráfico y detalles ésta es una lista de los vídeos que te recomendamos nuestras recomendaciones se basan";
-const kTeststr_et_Latn = " a niipea kui sinu maksimaalne igakuine krediidi limiit on meie poolt heaks kiidetud on sinu kohustuseks see krediidilimiit";
-const kTeststr_eu_Latn = " a den eraso bat honen kontra hortaz eragiketa bakarrik behar dituen eraso batek aes apurtuko luke nahiz eta oraingoz eraso bideraezina izan gaur egungo teknologiaren mugak direla eta oraingoz kezka hauek alde batera utzi daitezke orain arteko indar";
-const kTeststr_fa_Arab = " آب خوردن عجله Ù…ÛŒ کردند به جای باز ÛŒ کتک کاری Ù…ÛŒ کردند Ùˆ همه چيز مثل قبل بود Ùقط من ماندم Ùˆ ÙŠÚ© دنيا حر٠و انتظار تا عاقبت رسيد احضاريه ÛŒ ای با";
-const kTeststr_fi_Latn = " a joilla olet käynyt tämä kerro meille kuka ä olet ei tunnistettavia käyttötietoja kuten virheraportteja käytetään google desktopin parantamiseen etsi näyttää mukautettuja uutisia google desktop keskivaihto leikkaa voit kaksoisnapsauttaa";
-const kTeststr_fj_Latn = " i kina na i iri ka duatani na matana main a meke wesi se meke mada na meke ni yaqona oqo na meke ka dau vakayagataki ena yaqona vakaturaga e dau caka toka ga kina na vucu ka dau lagati tiko kina na ka e yaco tiko na talo ni wai ni yaqona na lewai ni wai";
-const kTeststr_fo_Latn = " at verða átaluverdar óhóskandi ella áloypandi vit kunnu ikki garanterða at google leitanin ikki finnur naka sum er áloypandi óhóskandi ella átaluvert og google tekur onga ábyrgd yvir tær síður sum koma við í okkara leitiskipan fá tær ein";
-const kTeststr_fr_Latn = " a accès aux collections et aux frontaux qui lui ont été attribués il peut consulter et modifier ses collections et exporter des configurations de collection toutefois il ne peut pas créer ni supprimer des collections enfin il a accès aux fonctions";
-const kTeststr_fy_Latn = " adfertinsjes gewoan lytse adfertinsjes mei besibbe siden dy t fan belang binne foar de ynhâld fan jo berjochten wolle jo mear witte fan gmail foardat jo jo oanmelde gean dan nei wy wurkje eltse dei om gmail te ferbetterjen dêrta sille wy jo sa út en";
-const kTeststr_ga_Latn = " a bhfuil na focail go léir i do cheist le fáil orthu ní gá ach focail breise a chur leis na cinn a cuardaíodh cheana chun an cuardach a bheachtú nó a chúngú má chuirtear focal breise isteach aimseofar fo aicme ar leith de na torthaí a fuarthas";
-const kTeststr_gaa_Latn = "Akε mlawookpeehe kε Maŋhiεnyiεlכ oshikifככ lε eba naagbee ni maŋ lε nitsumכ ni kwεכ oshikifככ nכ lε etsככ mכ ni ye kunim ni akε lε eta esεŋ nכ. Dani nomεi baaba nכ lε, maŋ nכkwεmכ kui wuji enyכ ni yככ wכ maŋ lε mli, NPP kε NDC mli bii fכfכi wiemכi kεmaje majee amεhe. Ekomεi kwraa po yafee hiεkwεmכi ni ha ni gidigidi, pilamכ kε la shishwiemכ aaba yε heikomεi. ";
-const kTeststr_gd_Latn = " air son is gum bi casg air a h uile briosgaid no gum faigh thu brath nuair a tha briosgaid a tighinn gad rannsachadh ghoogle gu ceart mura bheil briosgaidean ceadaichte cuiridh google briosgaid dha do neach cleachdaidh fa leth tha google a cleachdadh";
-const kTeststr_gl_Latn = " debe ser como mínimo taranto tendas de venda polo miúdo cociñas servizos bordado canadá viaxes parques de vehículos de recreo hotel oriental habitación recibir unha postal no enderezo indicado anteriormente";
-const kTeststr_gn_Latn = " aháta añe ë ne mbo ehára ndive ajeruréta chupe oporandujey haÄua peëme mba épa pekaru ha áÄa oporandúvo nde eréta avei re paraguaýpe kachíke he i leúpe ndépa re úma kure tatakuápe ha leu ombohovái héë ha ujepéma kachíke he ijey";
-const kTeststr_gu_Gujr = " આના પરિણામ પà«àª°àª®àª¾àª£àª¸àª° ફોનà«àªŸ અવતરણ ચિનà«àª¹àªµàª¾àª³àª¾ પાઠને છà«àªªàª¾àªµà«‹ બધા સમૂહો શોધાયા હાલનો જ સંદેશ વિષયની";
-const kTeststr_gv_Latn = " and not ripe as i thought yn assyl yn shynnagh as yn lion the ass the fox and the lion va assyl as shynnagh ayns commee son nyn vendeilys as sauchys hie ad magh ayns y cheyll dy shelg cha row ad er gholl feer foddey tra veeit ad rish lion yn shynnagh";
-const kTeststr_ha_Latn = " a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako daga guda daga ranar zuwa a kan sakamako daga shafukan daga ranar zuwa a kan sakamako daga guda a cikin last hour a kan sakamako daga guda daga kafar";
-const kTeststr_haw_Latn = "He puke noiÊ»i kÅ«Ê»ikena kÅ«noa Ê»o Wikipikia. E Ê»oluÊ»olu nÅ, e hÄÊ»awi mai i kÄu Ê»ike, kÄu manaÊ»o, a me kou leo no ke kÅ«kulu Ê»ana a me ke kÄkoÊ»o Ê»ana mai i ka Wikipikia HawaiÊ»i. He kahua pÅ«naewele HawaiÊ»i kÄ“ia no ka hoÊ»oulu Ê»ana i ka Ê»ike HawaiÊ»i. InÄ hiki iÄ Ê»oe ke Ê»Ålelo HawaiÊ»i, e Ê»oluÊ»olu nÅ, e kÅkua mai a e hoÊ»ololi i nÄ Ê»atikala ma Ê»aneÊ»i, a pono e haÊ»i aku i kou mau hoa aloha e pili ana i ka Wikipikia HawaiÊ»i. E ola mau nÅ ka Ê»Ålelo HawaiÊ»i a mau loa aku.";
-const kTeststr_hi_Deva = " ं à¤à¤¡à¤µà¤°à¥à¤¡à¥à¤¸ विजà¥à¤žà¤¾à¤ªà¤¨à¥‹à¤‚ के अनà¥à¤­à¤µ पर आधारित हैं और इनकी मदद से आपको अपने विजà¥à¤žà¤¾à¤ªà¤¨à¥‹à¤‚ का अधिकतम लाभ";
-const kTeststr_hr_Latn = "Posljednja dva vladara su Kijaksar (ΚυαξαÏης; 625-585 prije Krista), fraortov sin koji će proÅ¡iriti teritorij Medije i Astijag. Kijaksar je imao kćer ili unuku koja se zvala Amitis a postala je ženom Nabukodonosora II. kojoj je ovaj izgradio Viseće vrtove Babilona. Kijaksar je modernizirao svoju vojsku i uniÅ¡tio Ninivu 612. prije Krista. Naslijedio ga je njegov sin, posljednji medijski kralj, Astijag, kojega je detronizirao (sruÅ¡io sa vlasti) njegov unuk Kir Veliki. Zemljom su zavladali Perzijanci.";
-const kTeststr_ht_Latn = " ak pitit tout sosyete a chita se pou sa leta dwe pwoteje yo nimewo leta fèt pou li pwoteje tout paran ak pitit nan peyi a menm jan kit paran yo marye kit yo pa marye tout manman ki fè pitit leta fèt pou ba yo konkoul menm jan tou pou timoun piti ak pou";
-const kTeststr_hu_Latn = " a felhasználóim a google azonosító szöveget ikor látják a felhasználóim a google azonosító szöveget felhasználók a google azonosító szöveget fogják látni minden tranzakció után ha a vásárlását regisztrációját oldalunk";
-const kTeststr_hy_Armn = " Õ¡ Õµ Õ¥Õ¾ Õ¶Õ¡ Õ°Õ«Õ¡ÖÕ¡Õ® Õ¡Õ¹Ö„Õ¥Ö€Õ¸Õ¾ Õ¶Õ¡ÕµÕ¸Ö‚Õ´ Õ§ Õ°Õ«Õ¶Õ£Õ°Õ¡Ö€Õ¯Õ¡Õ¶Õ« Õ·Õ¥Õ¶Ö„Õ« Õ¿Õ¡Ö€Ö…Ö€Õ«Õ¶Õ¡Õ¯ ÖƒÕ¸Ö„Ö€Õ«Õ¯ Ö„Õ¡Õ¼Õ¡Õ¯Õ¸Ö‚Õ½Õ« ÕºÕ¡Õ¿Õ¸Ö‚Õ°Õ¡Õ¶Õ¶Õ¥Ö€Õ«Õ¶ Õ¤Õ¥Õ¼ Õ´Õ¥Õ¶Ö„ Õ·Õ¡Õ¿ Õ¥Õ¶Ö„ Õ°Õ¥Õ¿Õ¡Õ´Õ¶Õ¡Ö Õ¡Õ½Õ¸Ö‚Õ´ Õ§ Õ¶Õ¡ Õ¡ÕµÕ½ÕºÕ¥Õ½ Õ§";
-const kTeststr_ia_Latn = " super le sitos que tu visita isto es necessari pro render disponibile alcun functionalitates del barra de utensiles a fin que nos pote monstrar informationes ulterior super un sito le barra de utensiles debe dicer a nos le";
-// From 10% testing part of new lang=id scrape
-const kTeststr_id_Latn = "berdiri setelah pengurusnya yang berusia 83 tahun, Fayzrahman Satarov, mendeklarasikan diri sebagai nabi dan rumahnya sebagai negara Islam Satarov digambarkan sebagai mantan ulama Islam tahun 1970-an. Pengikutnya didorong membaca manuskripnya dan kebanyakan dilarang meninggalkan tempat persembunyian bawah tanah di dasar gedung delapan lantai mereka. Jaksa membuka penyelidikan kasus kriminal pada kelompok itu dan menyatakan akan membubarkan kelompok kalau tetap melakukan kegiatan ilegal seperti mencegah anggotanya mencari bantuan medis atau pendidikan. Sampai sekarang pihak berwajib belum melakukan penangkapan meskipun polisi mencurigai adanya tindak kekerasan pada anak. Pengadilan selanjutnya akan memutuskan apakah anak-anak diizinkan tetap tinggal dengan orang tua mereka. Kazan yang berada sekitar 800 kilometer di timur Moskow merupakan wilayah Tatarstan yang";
-
-const kTeststr_ie_Latn = " abhorre exceptiones in li derivation plu cardinal por un l i es li regularità del flexion conjugation ples comparar latino sine flexione e li antiqui projectes naturalistic queles have quasi null regules de derivation ma si on nu examina li enunciationes";
-const kTeststr_ig_Latn = "Chineke bụ aha á»zá» ndï omenala Igbo kpá»ro Chukwu. Mgbe ndị bekee bịara, ha mee ya nke ndi Christian. N'echiche ndi ekpere chi Omenala Ndi Igbo, Christianity, Judaism, ma Islam, Chineke nwere á»tụtụ utu aha, ma nwee nanị otu aha. Ụzá» abụỠe si akpá» aha ahụ bụ Jehovah ma Ọ bụ Yahweh. Na á»tụtụ Akwụkwá» Nsá», e wepụla aha Chineke ma jiri utu aha bụ Onyenwe Anyị ma á» bụ Chineke dochie ya. Ma mgbe e dere akwụkwá» nsá», aha ahụ bụ Jehova pụtara n’ime ya, ihe dị ka ugboro pụkụ asaa(7,000).";
-// From 10% testing part of new lang=ik scrape
-const kTeststr_ik_Latn = "sabvaqjuktuq sabvaba atiqaqpa atiqaqpa ibiq iebiq ixafich niuqtulgiññatif uvani natural gas tatpikka ufasiksigiruaq maaffa savaannafarufa mi tatkivani navy qanuqjugugguuq taaptuma inna uqsrunik ivaqjiqhutik taktuk allualiuqtuq sigukun nanuq puuvraatuq taktuum amugaa kalumnitigun nanuq agliruq allualiuqtuq";
-
-const kTeststr_is_Latn = " a afköst leitarorða þinna leitarorð neikvæð leitarorð auglýsingahópa byggja upp aðallista yfir ný leitarorð fyrir auglýsingahópana og skoða ítarleg gögn um árangur leitarorða eins og samkeppni auglýsenda og leitarmagn er krafist notkun";
-const kTeststr_it_Latn = " a causa di un intervento di manutenzione del sistema fino alle ore circa ora legale costa del pacifico del novembre le campagne esistenti continueranno a essere pubblicate come di consueto anche durante questo breve periodo di inattività ci scusiamo per";
-const kTeststr_iu_Cans = "áƒá‘¯á’ªá’»á’ªá‘¦ ᕿᓈá–á“ᓇᓲᖑᒻᒪᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ ᑎᑦᕆáŠá‘á“á–ᑦᑕᑎᑦ ᑎᑎᖅᑕᑉá±á‘¦ ᓯᕗᓂᖓᓂ ᑎᑎᖅᖃᖅ ᑎᑎᕆáŠá‘á“á–á‘•áƒá‘¦ ᕿᓂᓲᖑᔪá’ᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ";
-const kTeststr_he_Hebr = " ×ו לערוך ×ת העדפות ההפצה ×× × ×¢×§×•×‘ ×חרי ×”×©×œ×‘×™× ×”×‘××™× ×›× ×¡ לחשבון ×”×ישי שלך ב";
-const kTeststr_ja_Hani = " ã“ã®ãƒš ジã§ã¯ アカウントã«æŒ‡å®šã•ã‚ŒãŸäºˆç®—ã®å±¥æ­´ã‚’一覧ã«ã—ã¦ã„ã¾ã™ ãã‚Œãžã‚Œã®é …ç›®ã«ã¯ 予算é¡ã¨ç‰¹å®šæœŸé–“ã®ã‚¹ãƒ† タスãŒè¡¨ç¤ºã•ã‚Œã¾ã™ ç¾åœ¨ã¾ãŸã¯ä»Šå¾Œã®äºˆç®—を設定ã™ã‚‹ã«ã¯";
-const kTeststr_jw_Latn = " account ten server niki kalian username meniko tanpo judul cacahe account nggonanmu wes pol pesen mu wes diguwak pesenan mu wes di simpen sante wae pesenan mu wes ke kirim mbuh tekan ora pesenan e ke kethok pesenan mu wes ke kirim mbuh tekan ora pesenan";
-const kTeststr_ka_Geor = " რბირთვიდáƒáƒœ მიღებული ელემენტი მენდელეევის პერიáƒáƒ“ულ სიტემáƒáƒ¨áƒ˜ გáƒáƒ“áƒáƒ˜áƒœáƒáƒªáƒ•áƒšáƒ”ბს áƒáƒ áƒ˜ უჯრით";
-const kTeststr_kha_Latn = " kaba jem jai sa sngap thuh ia ki bynta ba sharum naka sohbuin jong phi nangta sa pynhiar ia ka kti kadiang jong phi sha ka krung jong phi bad da kaba pyndonkam kumjuh ia ki shympriahti jong phi sa sngap thuh shapoh ka tohtit jong phi pyndonkam ia kajuh ka";
-const kTeststr_kk_Arab = " ﺎ ﻗﻴﺎﻧﺎﺕ ﺑﻮﻟﻤﺎﻳﺪﻯ ïº‘ï¯˜ï» ï­˜ïº®ï»­ïº—ïº´ï»ªïº³ï¯©ï»¦ ﻳﺎﻋﻨﻲ ﻗﺎﻻ ﻭﻣﯩﺮﯨﻨﺪﻩ ﻗﺎﺯïºï»• Ø¡ ﺗﯩﻠﯩﻨﯩﯔ ﻗﻮﻟﺪïºï»§ï¯©ï» ï»¤ïºŽï¯žï»¯ ﻗﺎﺯïºï»• ﺟﻪﺭﯨﻨﺪﻩ";
-const kTeststr_kk_Cyrl = " а билердің өзіне Ñ€Ò±Ò›Ñат берілмеген егер халық талап етÑе ғана хан келіÑім берген өздеріңіз білеÑіздер қр қыл Ð¼Ñ‹Ñ Ñ‚Ñ‹Ò› кодекÑінде жазаның";
-const kTeststr_kk_Latn = " bolsa da otanyna qaityp keledi al oralmandar basqa elderde diasporasy ote az bolghandyqtan bir birine komektesip bauyrmal bolady birde men poezben oralmandardyng qazaqstangha keluin kordim monghol qazaqtary poezdan tuse sala jerdi suip jylap keletin biraq";
-const kTeststr_kl_Latn = " at nittartakkalli uani toqqarsimasatta akornanni nittartakkanut allanut ingerlaqqittoqarsinnaavoq kanukoka tassaavoq kommuneqarfiit kattuffiat nuna tamakkerlugu kommunit nittartagaannut ingerlaqqiffiusinnaasoq kisitsiserpassuit nunatsinnut tunngasut";
-const kTeststr_km_Khmr = " ក ហគ ឃ ង ច ឆ ជ ឈ ញ ដ ឋ ឌ ហណ ហហទ ធ ន ប ផ ព ភ ម យ រ ល វ ស ហ ឡ អ ឥ ឦ ឧ ឪ ឫ ឬ ឯ ឱ ទាំងអស់";
-const kTeststr_kn_Knda = " ಂಠಯà³à²¯à²¨à²µà²°à³ ತà³à²®à²•à³‚ರೠಜಿಲà³à²²à³†à²¯ ಚಿಕà³à²•à²¨à²¾à²¯à²•à²¨à²¹à²³à³à²³à²¿ ತಾಲà³à²²à³‚ಕಿನ ತೀರà³à²¥à²ªà³à²° ವೆಂಬ ಸಾಧಾರಣ ಹಳà³à²³à²¿à²¯ ಶà³à²¯à²¾à²¨à³à²­à³‹à²—ರ";
-const kTeststr_ko_Hani = " 개별ì ìœ¼ë¡œ 리í¬íŠ¸ 액세스 ê¶Œí•œì„ ë¶€ì—¬í•  수 있습니다 액세스 권한 부여사용ìžì—게 프로필 리í¬íŠ¸ì— 액세스할 수 있는 ê¶Œí•œì„ ë¶€ì—¬í•˜ì‹œë ¤ë©´ 가용 프로필 ìƒìžì—ì„œ 프로필 ì´ë¦„ì„ ì„ íƒí•œ 다ìŒ";
-// From 10% testing part of new lang=ks scrape
-const kTeststr_ks_Arab = " ژماں سرابن منز گرٲن Ú†Ú¾ÙÛ Ø®Ø§Ø¨Ù•Ú© کھلونÛÙ• ؤڈراواں تÙلتÙÚ¾ Ù†Ùیَس تÛÙ• گوشÛ٠گوشÛ٠مندچھاوى۪س دÙلس Ú†Ú¾ÙÛ ÙˆÙˆÙ†Ù˜Øª ÙˆÙچھان از ستم قلم صبوÙرٕ وول مسٲÙر لیۆکھÙÙ† بێتابن منز ورل سوال Ú†Ú¾ÙÛ ØªØ±Ø§ÙˆØ§Úº جوابن منز کالÛÙ• پھۯستÛÙ• پھن٘ب Ù¾Ú¯ÙŽÛÛ Ù¾Û Ù¾Û†Øª نظر دÙÚ˜ Ù†ÛÙ• ژھالÛÙ• مٔت آرن مٲنز مسول متھان Ú†Ú¾Û’Ùš مس والن ÙˆÛ…Ù† Ú†Ú¾Û’Ùš غارن تÛ٠نارٕ Ú˜Ú¾Ù¹Ú¾ ژاپان رێش تۅرگ تراوٕÛÙ† تÛÙ• ون رٹÛÙ• ÛÙ† ÛوشÛÙ ÛÛŽÛ†Ú†Ú¾ Ù†ÛÙ• پوشنوÙلس Ù†ÙØ´ Ù…Û…Ûرٕ دی دی زٕلاں چھ٠زى۪و حرÙÙ† لۆدرٕ Ù¾Ú¾Ù”Ù„ Ûى۪تھ ملر عازمؔ سۆدرٕ Ú©Ú¾Û…Ù†Û٠منز منگاں Ú†Ú¾ÙÛ Ù†Ø¯Ø±Ù‰ÛªÙ† پن Ú˜Û’ تھى۪کی ÛŒÛ٠مسٲÙر پنن ÙˆÙÚˆÙˆ تÛÙ• پڑاو گٕتَو گٕتَو Ú†Ú¾Û’Ùš ÛŒÛÙ Ú©Û…Ù„ بÙتھ تÛÙ• بانÛÙ• سٕÛÛ Ú¯Û…Ø±Ø¯Ù• Ú†Ú¾Û٠سپداں دمÛÙ• Ù¾ÙÚ¾Ù¹ Ú†Ú¾ÙÙ¹Û Ù¾ÙˆÙ†Ù¾Ø± Ù¾Ú©Ú¾ÛÙ• داران سÙÛ ÛŒØªÙ‰ÛªÙ† تۯاو٠کم نظر دۯاکھ تÛÙ• باسیوے سÙÛ Ù…Û†Û Ûیو یێران Ù…Û’Ùš ژى۪تÙرمÙت Ú†Ú¾ÙÛ Ø³ÙÙ„ÛŒ تس Ú†Ú¾Û’Ùš کتى۪ن تھپھ شاد مس کراں ÙˆÙÚ†Ú¾ Ù…Û’Ùš خون Ú˜Ù• خبر کیاز٠کراں دۯاکھ تمÙس پى۪ٹھ ماتم أز Ú©Û٠شبÛÙ• آو Ù…Û’Ùš بێیÛ٠پیش سÙر زانÛ٠خدا دار٠پى۪ٹھ ژٲنگ Ûنا تھو ز٠ژے Ú†Ú¾Û’Ùš مێون أنÛÙ• کپٹاں Ú†Ú¾ÙÛ Ø²Ù•Ú˜Ù† سون مظÙّر عازمؔ Ù¾ÙˆØ´Û Ø¨Ø±Ú¯Ù† Ú†Ú¾ÙÛ Ø³Ùواں چاکھ سÙÛ Ø§Ù„Ù…Ø§Ø³ قلم لو٠کٔ Úˆ نو٠سرٕ سونتس Ú©Ù„ پرو٠بۆر Ø¨ÛŽÛŒÛ Ø§Ø² بانبر٠Ûۆت یمبرزلÛ٠ٹارى۪ن منز نار وزملÛ٠کۅسÛÙ• کتھ کٔر اظÛار Ú©Ú†Ú¾Û٠منزٕ ÙˆÙ”Ù† رووÙÙ… اچھÛ٠چشمو ژوپÙÙ… Ú©Ù”Ù†Úˆ انبار تماشÛÙ Ú†Ú¾Û٠تگاں";
-
-const kTeststr_ks_Deva = "नमसà¥à¤¤à¥‡ शारदे देवि काशà¥à¤®à¤¿à¤°à¤ªà¥à¤°à¥à¤µà¤¾à¤¸à¤¿à¤¨à¤¿ तà¥à¤µà¤¾à¤®à¤¹à¤® पà¥à¤°à¤¾à¤°à¥à¤¥à¤¯à¥‡ देवि विदà¥à¤¯ दानम च देहि मे कॉशà¥à¤° लेख॒नà¥à¤• सारिव॒य खॊत॒ आसान तरीक॒ छॠयि देवनागरी टाइपराइटर इसà¥à¤¤à¤¿à¤®à¤¾à¤² करà¥à¤¨. अथ मंज़ छि कॉशà¥à¤° लेख॒न॒चि सारॆय मातà¥à¤°à¤¾à¤¯à¤¿. अमि अलाव॒ हॆकिव तॊहà¥à¤¯à¥ यिम॒ यूनिकोड à¤à¤¡à¤¿à¤Ÿà¤° ति वरतॉविथ मगर कॉशिरि मातà¥à¤°à¤¾à¤¯à¤¿ लेख॒नस गछ़ि हना दिकथ: अकà¥à¤·à¤°à¤®à¤¾à¤²à¤¾à¤›à¥ अख मà¥à¤«à¤¼à¥à¤¤ त॒ सॅहॅल सोफà¥à¤Ÿà¤µà¥‡à¤° यॆमि स॒तà¥à¤¯à¥ यà¥à¤¨à¤¿à¤•à¥‹à¤¡ देवनागरी मंज़ ITRANS scheme स॒तà¥à¤¯à¥ छॠयिवान लेख॒न॒. वà¥à¤›à¤¿à¤µ: सहायता. अथ स॒तà¥à¤¯à¥ जà¥à¤¡à¤¿à¤¥ जालपृषà¥à¤  (वेबपेज) (सॉरी अà¤à¤—à¥à¤°à¥€à¤œà¤¼à¥€ पॉठà¥à¤¯)";
-const kTeststr_ku_Arab = " بۆ به ڕێوه بردنی نامه ی که دێتن ڕاسته وخۆ ڕه وان بکه نامه کانی گ مایل بۆ حسابی پۆستێکی تر هێنانی په یوه ندکاره کان له";
-const kTeststr_ku_Latn = " be zmaneki ter le inglis werdegeretewe em srvise heshta le cor beta daye wate hest a taqi dekrete u bashtr dekret tewawwzmanekan wernegrawnetewe u ne hemu laperakn ke eme pshtiwan dekayn be teaweti wergerawete nermwalley wergeran teksti new wene nasnatewe";
-const kTeststr_ky_Arab = " جانا انى تانۇۇ ۇلۇتۇن تانۇۇ قىرعىزدى بئلۉۉ دەگەندىك اچىق ايتساق ماناستى تاانىعاندىق ۅزۉڭدۉ تاانىعاندىق بۉگۉن تەما جۉكتۅمۅ ق ى رع ى ز ت ى ل ى";
-const kTeststr_ky_Cyrl = " агай Ñле оболу мен ÑÐ°Ð´Ñ‹Ð±Ð°ÐºÐ°Ñ Ð°Ð³Ð°Ð½Ñ‹Ð½ өзү менен ÑÐ¼ÐµÑ Ñмгектери менен тааныштым жылдары ташкенде өзбекÑтан илимдер академиÑÑынын баÑны";
-const kTeststr_la_Latn = " a deo qui enim nocendi causa mentiri solet si iam consulendi causa mentiatur multum profecit sed aliud est quod per se ipsum laudabile proponitur aliud quod in deterioris comparatione praeponitur aliter enim gratulamur cum sanus est homo aliter cum melius";
-const kTeststr_lb_Latn = " a gewerkschaften och hei gefuerdert dir dammen an dir häre vun de gewerkschaften denkt un déi aarm wann der äer fuerderunge formuléiert d sechst congés woch an aarbechtszäitverkierzung hëllefen hinnen net d unhiewe vun de steigerungssäz bei de";
-const kTeststr_lg_Latn = " abaana ba bani lukaaga mu ana mu babiri abaana ba bebayi lukaaga mu abiri mu basatu abaana ba azugaadi lukumi mu ebikumi bibiri mu abiri mu babiri abaana ba adonikamu lukaaga mu nltaaga mu mukaaga abaana ba biguvaayi enkumi bbiri mu ataano mu mukaaga";
-const kTeststr_lif_Limb = "á¤á¤¡á¤–ᤠᤳ ᤕᤠᤰᤌᤢᤱ ᤆᤢᤶᤗᤢᤱᤖᤧ ᤛᤥᤎᤢᤱᤃᤧᤴ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤆᤧᤶᤈᤱᤗᤧ á¤á¤¢á¤”ᤡᤱᤅᤥ á¤á¤ á¤ˆá¤¡á¤–ᤡ ᤋᤱᤒᤣ ᥈᥆᥆᥉ ᤒᤠ ᤈá¤á¤˜á¤–ᤡ ᤗᤠá¤á¤¢á¤€á¤ á¤± á¤á¤¹á¤á¤  ᤋᤱᤒᤣ á¤á¤ á¤° á¤á¤ á¤ºá¤³á¤‹á¤¢ ᤕᤢᤖᤢᤒᤠ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤋᤱᤃᤡᤵᤛᤡᤱ ᤌᤡᤶᤒᤣᤴ ᤂᤠᤃᤴ ᤛᤡᤛᤣ᤺ᤰᤗᤠ ᥇ᥠᤂᤧᤴ ᤀᤡᤛᤡᤰ ᥇ ᤈá¤á¤˜á¤–ᤡ ᥈᥆᥆᥊ ᤀᤥ á¤á¤ á¤›á¤¢á¤µ ᤆᤥ᤺ᤰᤔᤠ ᤌᤡᤶᤒᤣ ᤋᤱᤃᤠᤶᤛᤡᤱᤗ á¤á¤³á¤á¤  ᤀᤡᤱᤄᤱ ᤘᤠ᤹";
-const kTeststr_ln_Latn = " abakisamaki ndenge esengeli moyebami abongisamaki solo mpenza kombo ya moyebami elonguamaki kombo ya bayebami elonguamaki kombo eleki molayi po na esika epesameli limbisa esika ya kotia ba kombo esuki boye esengeli olimbola ndako na yo ya mikanda kombo";
-const kTeststr_lo_Laoo = " àºàº«àº²àº—ົ່ວທັງເວັບ à»àº¥àº°à»ƒàº™à»€àº§àº±àºšà»„ຮ້ສາຠທຳອິດໃຫ້ທຳàºàº²àº™àºŠàº­àºàº«àº²àºà»ˆàº­àº™ ຈາàºàº™àº±à»‰àº™ ໃຫ້àºàº»àº”ປຸ່ມເມນູ ໃນໜ້າຜົນໄດ້";
-const kTeststr_lt_Latn = " a išsijungia mano idėja dėl geriausio laiko po pastarųjų savo santykių pasimokiau penki dalykai be kurių negaliu gyventi mano miegamajame tu surasi ideali pora išsilavinimas aukštoji mokykla koledžas universitetas pagrindinis laipsnis metai";
-const kTeststr_lv_Latn = " a gadskÄrtÄ“jÄ izpÄrdoÅ¡ana slÄ“poÅ¡ana jÄņi atlaide izmaiņas trafikÄ kas saistÄ«tas ar sezonas izpÄrdoÅ¡anu speciÄlajÄm atlaidÄ“m u c ir parastas un atslÄ“gvÄrdi kas ir populÄri noteiktos laika posmos Å¡ajÄ laikÄ saņems lielÄku klikÅ¡Ä·u";
-const kTeststr_mfe_Latn = "Anz dir mwa, Sa bann delo ki to trouve la, kot fam prostitie asize, samem bann pep, bann lafoul dimoun, bann nasion ek bann langaz. Sa dis korn ki to finn trouve, ansam avek bebet la, zot pou ena laenn pou prostitie la; zot pou pran tou seki li ena e met li touni, zot pou manz so laser e bril seki reste dan dife. Parski Bondie finn met dan zot leker proze pou realiz so plan. Zot pou met zot dakor pou sed zot pouvwar bebet la ziska ki parol Bondie fini realize.";
-const kTeststr_mg_Latn = " amporisihin i ianao mba hijery ny dika teksta ranofotsiny an ity lahatsoratra ity tsy ilaina ny opérateur efa karohina daholo ny teny rehetra nosoratanao ampiasao anaovana dokambarotra i google telugu datin ny takelaka fikarohana sary renitakelak i";
-const kTeststr_mi_Latn = " haere ki te kainga o o haere ki te kainga o o haere ki te kainga o te rapunga ahua o haere ki te kainga o ka tangohia he ki to rapunga kaore au mohio te tikanga whakatiki o te ra he whakaharuru te pai rapunga a te rapunga ahua a e kainga o nga awhina o te";
-const kTeststr_mk_Cyrl = " глаÑовите коалицијата на вмро дпмне како партија Ñо најмногу оÑвоени глаÑови ќе добие евра а на Ñметката на коализијата за македонија";
-const kTeststr_ml_Mlym = " à´‚ à´…à´™àµà´™à´¨àµ† à´žà´™àµà´™à´³àµ അവരàµà´Ÿàµ† à´®àµà´®àµà´ªà´¿à´²àµ നിനàµà´¨àµ ഔടàµà´‚ ഉടനെ നിങàµà´™à´³àµ പതിയിരിപàµà´ªà´¿à´²àµ നിനàµà´¨àµ à´Žà´´àµà´¨àµà´¨àµ‡à´±àµà´±àµ";
-const kTeststr_mn_Cyrl = " а боловÑронгуй болгох орон нутгийн ажил үйлÑийг уÑлдуулж зохицуулах дүрÑм журам боловÑруулах орон нутгийн өмч хөрөнгө Ñанхүүгийн";
-const kTeststr_mn_Mong = "ᠦᠭᠡ ᠵᠢᠨ ᠴᠢᠨᠭ᠎ᠠ ᠬᠦᠨᠳᠡᠢ ᠵᠢ ᠢᠯᠭᠠᠬᠣ";
-const kTeststr_mr_Deva = "हैदराबाद उचà¥à¤šà¤¾à¤° à¤à¤•à¤¾ (सहायà¥à¤¯Â·à¤®à¤¾à¤¹à¤¿à¤¤à¥€)तेलà¥à¤—ू: హైదరాబాదౠ, उरà¥à¤¦à¥‚: حیدر آباد हे भारतातील आंधà¥à¤° पà¥à¤°à¤¦à¥‡à¤¶ राजà¥à¤¯à¤¾à¤šà¥à¤¯à¤¾ राजधानीचे शहर आहे. हैदराबादची लोकसंखà¥à¤¯à¤¾ ७७ लाख ४० हजार ३३४ आहे. मोतà¥à¤¯à¤¾à¤‚चे शहर अशी à¤à¤•à¥‡à¤•à¤¾à¤³à¥€ ओळख असलेलà¥à¤¯à¤¾ या शहराला à¤à¤¤à¤¿à¤¹à¤¾à¤¸à¤¿à¤•, सांसà¥à¤•à¥ƒà¤¤à¤¿à¤• आणि सà¥à¤¥à¤¾à¤ªà¤¤à¥à¤¯à¤¶à¤¾à¤¸à¥à¤¤à¥à¤°à¥€à¤¯ वारसा लाभला आहे. १९९० नंतर शिकà¥à¤·à¤£ आणि माहिती तंतà¥à¤°à¤œà¥à¤žà¤¾à¤¨ तà¥à¤¯à¤¾à¤šà¤ªà¥à¤°à¤®à¤¾à¤£à¥‡ औषधनिरà¥à¤®à¤¿à¤¤à¥€ आणि जैवतंतà¥à¤°à¤œà¥à¤žà¤¾à¤¨ कà¥à¤·à¥‡à¤¤à¥à¤°à¤¾à¤¤à¥€à¤² उदà¥à¤¯à¥‹à¤—धंदà¥à¤¯à¤¾à¤‚ची वाढ शहरात à¤à¤¾à¤²à¥€. दकà¥à¤·à¤¿à¤£ मधà¥à¤¯ भारतातील परà¥à¤¯à¤Ÿà¤¨ आणि तेलà¥à¤—ू चितà¥à¤°à¤ªà¤Ÿà¤¨à¤¿à¤°à¥à¤®à¤¿à¤¤à¥€à¤šà¥‡ हैदराबाद हे केंदà¥à¤° आहे";
-// From 10% testing part of new lang=ms scrape
-const kTeststr_ms_Latn = "pengampunan beramai-ramai supaya mereka pulang ke rumah masing-masing. Orang-orang besarnya enggan mengiktiraf sultan yang dilantik oleh Belanda sebagai Yang DiPertuan Selangor. Orang ramai pula tidak mahu menjalankan perniagaan bijih timah dengan Belanda, selagi raja yang berhak tidak ditabalkan. Perdagang yang lain dibekukan terus kerana untuk membalas jasa beliau yang membantu Belanda menentang Riau, Johor dan Selangor. Di antara tiga orang Sultan juga dipandang oleh rakyat sebagai seorang sultan yang paling gigih. 1 | 2 SULTAN Sebagai ganti Sultan Ibrahim ditabalkan Raja Muhammad iaitu Raja Muda. Walaupun baginda bukan anak isteri pertama bergelar Sultan Muhammad bersemayam di Kuala Selangor juga. Pentadbiran baginda yang lemah itu menyebabkan Kuala Selangor menjadi sarang ioleh Cina di Lukut tidak diambil tindakan, sedangkan baginda sendiri banyak berhutang kepada 1";
-
-const kTeststr_ms_Latn2 = "bilik sebelah berkata julai pada pm ladymariah hmm sume ni terpulang kepada individu mungkin anda bernasib baik selama ini dalam membeli hp yang bagus deli berkata julai pada pm walaupun bukan bahsa baku tp tetap bahasa melayu kan perubahan boleh dibuat";
-const kTeststr_mt_Latn = " ata ikteb messaġġ lil indirizzi differenti billi tagħżilhom u tagħfas il buttuna ikteb żid numri tfittxijja tal kotba mur print home kotba minn pagni ghal pagna minn ghall ktieb ta aċċessa stieden habib iehor grazzi it tim tal gruppi google";
-const kTeststr_my_Latn = " jyk ef oif gawgodcsifayvdrfhrnf bmawgrsm topf dsvj g mail tamumif avhvm atmif txjwgif yxrqhk avhvm efae m pwifavhvm ef ufkyfwdky help center odkyvmyg drsm ar avh dswjhar cgef rsm udkawdkifygw f tajzawgudk smedkifygw f jyd awmh g mail cool features rsm";
-const kTeststr_my_Mymr = " á€á€€á€¹á€€á€žá€¯á€­á€œá€¹ မ္ဟ ပ္ရန္ လာ္ရပီးေနာက္ န္ဟစ္ အရ္á€á€šá€¹ ဦးသန္ ့သည္ ပန္ းá€á€”ော္ အမ္ယုိးသား ေက္ယာင္ း";
-const kTeststr_na_Latn = " arcol obabakaen riringa itorere ibibokiei ababaro min kuduwa airumena baoin tokin rowiowet itiket keram damadamit eigirow etoreiy row keitsito boney ibingo itsiw dorerin naoerodelaporte s nauruan dictionary a c a c d g h o p s t y aiquen ion eins aiquen";
-const kTeststr_ne_Deva = "अरू ठाऊà¤à¤¬à¤¾à¤Ÿà¤ªà¤¨à¤¿ खà¥à¤²à¥‡à¤•à¥‹ छ यो खाता अर अरू ठाऊà¤à¤¬à¤¾à¤Ÿà¤ªà¤¨à¤¿ खà¥à¤²à¥‡à¤•à¥‹ छ यो खाता अर ू";
-const kTeststr_nl_Latn = " a als volgt te werk om een configuratiebestand te maken sitemap gen py ebruik filters om de s op te geven die moeten worden toegevoegd of uitgesloten op basis van de opmaaktaal elke sitemap mag alleen de s bevatten voor een bepaalde opmaaktaal dit";
-const kTeststr_nn_Latn = " a for verktylina til å hjelpa deg å nå oss merk at pagerank syninga ikkje automatisk kjem til å henta inn informasjon frå sider med argument dvs frå sider med eit i en dersom datamaskina di er plassert bak ein mellomtenar for vevsider kan det verka";
-const kTeststr_no_Latn = " a er obligatorisk tidsforskyvning plassering av katalogsøk planinformasjon loggfilbane gruppenavn kontoinformasjon passord domene gruppeinformasjon alle kampanjesporing alternativ bruker grupper oppgaveplanlegger oppgavehistorikk kontosammendrag antall";
-const kTeststr_nr_Latn = "ikomiti elawulako yegatja emhlanganweni walo ]imithetho mgomo ye anc ibekwa malunga wayo begodu ubudosiphambili kugandelela lokho okutjhiwo yi lokha nayithi abantu ngibo ";
-
-const kTeststr_nso_Latn = "Bophara bja Asia ekaba 8.6% bja lefase goba 29.4% bja naga ya lefase (ntle le mawatle). Asia enale badudu bao bakabago dimillione millione tše nne (4 billion) yeo e bago 60% ya badudi ba lefase ka bophara. A bapolelwa rena sefapanong mehleng ya Pontius Pilatus. A hlokofatšwa, A bolokwa, A tsoga ka letšatši la boraro, ka mo mangwalo a bolelago ka gona, a rotogela magodimong, ";
-const kTeststr_ny_Latn = "Boma ndi gawo la dziko lomwe linapangidwa ndi cholinga chothandiza ntchito yolamulira. Kuŵalako kulikuunikabe mandita, Edipo nyima unalephera kugonjetsa kuŵalako.";
-const kTeststr_oc_Latn = " Pasmens, la classificacion pus admesa uei (segon Juli Ronjat e Pèire Bèc) agropa lei parlars deis Aups dins l'occitan vivaroaupenc e non dins lo dialècte provençau.";
-const kTeststr_om_Latn = " afaan katalaa bork bork bork hiikaa jira hin argamne gareen barbaadame hin argamne gargarsa qube en gar bayee jira garee walitti firooman gareewwan walitti firooman fuula web akka tartiiba qubeetiin agarsiisi akka tartiiba qubeetiin agarsiisaa jira akka";
-const kTeststr_or_Orya = "ଅକà­à¬Ÿà­‹à¬¬à¬° ଡିସେମà­à¬¬à¬°";
-const kTeststr_pa_Guru = " ਂ ਦਿਨਾਂ ਵਿਚ ਭਾਈ ਸਾਹਿਬ ਦੀ ਬà©à©±à¨šà©œ ਗੋਬਿੰਦ ਰਾਮ ਨਾਲ ਅੜਫਸ ਚੱਲ ਰਹੀ ਸੀ ਗੋਬਿੰਦ ਰਾਮ ਨੇ ਭਾਈ ਸਾਹਿਬ ਦੀਆਂ ਭੈਣਾ";
-const kTeststr_pl_Latn = " a australii będzie widział inne reklamy niż użytkownik z kanady kierowanie geograficzne sprawia że reklamy są lepiej dopasowane do użytkownika twojej strony oznacza to także że możesz nie zobaczyć wszystkich reklam które są wyświetlane na";
-const kTeststr_ps_Arab = " اتو مستقل رياست جوړ شو او د پخواني ادبي انجمن Ú…Ø§Ù†Ú«Û Ø¯Ø¯Û Ø±ÙŠØ§Ø³Øª جز شوی او Ø¯Ø¯Û Ø§Ù†Ø¬Ù…Ù† د Ú˜Ø¨Û Ù…Ø¯ÙŠØ±ÙŠØª د پښتو Ù¼ÙˆÙ„Ù†Û Ù¾Ù‡ لوی مديريت واوښت لوی مدير ÙŠÛ Ø¯";
-const kTeststr_pt_Latn = " a abit prevê que a entrada desses produtos estrangeiros no mercado têxtil e vestuário do brasil possa reduzir os preços em cerca de a partir de má notícia para os empresários que terão que lutar para garantir suas margens de lucro mas boa notícia";
-const kTeststr_qu_Latn = " is t ipanakunatapis rikuchinankupaq qanpa simiykipi noqaykoqpa uya jllanakunamanta kunan jamoq simikunaman qelqan tiyan watukuy qpa uyata qanpa llaqtaykipi llank anakuna simimanta yanapakuna simimanta mayqen llaqtallapis kay simimanta t ijray qpa qelqa";
-const kTeststr_rm_Latn = " Cur ch’il chantun Turitg ha dà il dretg da votar a las dunnas (1970) è ella vegnida elegida en il cussegl da vischnanca da Zumikon per la Partida liberaldemocratica svizra (PLD). Da 1974 enfin 1982 è ella stada presidenta da vischnanca da Zumikon. L’onn 1979 è Elisabeth Kopp vegnida elegida en il Cussegl naziunal e reelegida quatter onns pli tard cun in resultat da sur 100 000 vuschs. L’onn 1984 è ella daventada vicepresidenta da la PLD.";
-const kTeststr_rn_Latn = " ishaka mu ndero y abana bawe ganira n abigisha nimba hari ingorane izo ari zo zose ushobora gusaba kubonana n umwigisha canke kuvugana nawe kuri terefone inyuma y uko babarungikira urutonde rw amanota i muhira mu bisanzwe amashure aratumira abavyeyi";
-const kTeststr_ro_Latn = " a anunţurilor reţineţi nu plătiţi pentru clicuri sau impresii ci numai atunci când pe site ul dvs survine o acţiune dorită site urile negative nu pot avea uri de destinaţie daţi instrucţiuni societăţii dvs bancare sau constructoare să";
-const kTeststr_ro_Cyrl = "Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ñ Ð° органелор ши инÑтитуциилор екзекутиве ши а органелор жудичиаре але путерий де Ñтат фиекÑруй орган ал путерий де Ñтат и Ñе";
-const kTeststr_ru_Cyrl = " а неправильный формат идентификатора дн назад";
-const kTeststr_rw_Latn = " dore ibyo ukeneye kumenya ukwo watubona ibibazo byinshi abandi babaza ububonero byibibina google onjela ho izina dyikyibina kyawe onjela ho yawe mulugo kulaho ibyandiko byawe shyilaho tegula yawe tulubaka tukongeraho iyanya mishya buliko tulambula";
-const kTeststr_sa_Deva = " ं क रà¥à¤®à¤£à¤¸à¥ त सà¥à¤¯ य तà¥à¤•à¤¿ ङà¥à¤šà¥‡à¤¹ करो तà¥à¤¯à¤¯ ं त सà¥à¤®à¤¾à¤²à¥ लोका तà¥à¤ªà¥ नरै ति असà¥à¤®à¥ˆ लोका य क रà¥à¤®à¤£ इ ति नॠकाम";
-const kTeststr_sa_Latn = " brahmÄ tatraivÄntaradhÄ«yata tataḥ saÅ›iá¹£yo vÄlmÄ«kir munir vismayam Äyayau tasya Å›iá¹£yÄs tataḥ sarve jaguḥ Å›lokam imaṃ punaḥ muhur muhuḥ prÄ«yamÄṇÄḥ prÄhuÅ› ca bhṛśavismitÄḥ samÄká¹£araiÅ› caturbhir yaḥ pÄdair gÄ«to";
-const kTeststr_sco_Latn = " a gless an geordie runciman ower a gless an tamson their man preached a hale hoor aboot the glorious memories o forty three an backsliders an profane persons like esau an aboot jeroboam the son o nebat that gaed stravagin to anither kirk an made aa israel";
-const kTeststr_sd_Arab = " اضاÙÙˆ ٿي ٿيو پر اها خبر عثمان Ú©ÙŠ بعد پيئي ته سگريٽ ڇڪيندڙ مسلمان نه هو بلڪ هندو هو دڪان تي پهچي عثمان ڪسبت کولي گراهڪن جي سيرب لاهڻ شروع ڪئي پر";
-const kTeststr_sg_Latn = " atâa na âkotta zo me lâkwê angbâ gï tarrango nî âkotta zo tî koddoro nî âde agbû tenne nî na kate töngana mbênî kotta kpalle tî nzönî dutï tî halëzo pëpe atâa sô âla lü gbâ tî ândya tî mâi na sahngo asâra gbâ tî";
-const kTeststr_si_Sinh = " අනුරà·à¶° මිහිඳුකුල නමින් සකුර෠ට ලිපියක් තà·à¶´à·‘ලෙන් එව෠තිබුණ෠කි à·Š රස්ටි ෂෙල්ටන් ප à·Š රනà·à¶±à·Šà¶¯à·” ද";
-const kTeststr_sit_NP = " dialekten in de roerstreek pierre bakkes oet roerstreek blz bewirk waordebook zónjig oktoeaber is t ieëste mofers waordebook oetgekaome dit waordebook is samegestèldj";
-const kTeststr_sk_Latn = " a aktivovaÅ¥ reklamnú kampaň ak chcete kampaň pred spustením eÅ¡te prispôsobiÅ¥ uložte ju ako Å¡ablónu a pokraÄujte v úprave vyberte si jednu z možností nižšie a kliknite na tlaÄidlo uložiÅ¥ kampaň nastavenia kampane môžete ľubovoľne";
-const kTeststr_sl_Latn = " adsense stanje prijave za google adsense google adsense raÄun je bil zaÄasno zamrznjen pozdravljeni hvala za vaÅ¡e zanimanje v google adsense po pregledu vaÅ¡e prijavnice so naÅ¡i strokovnjaki ugotovili da spletna stran ki je trenutno povezana z vaÅ¡im";
-const kTeststr_sm_Latn = " autu mea o lo totonu le e le minaomia matou te tuu i totonu i le faamatalaina o le suesuega i taimi uma mea o lo totonu fuafua i mea e tatau fa afoi tala mai le newsgroup mataupu fa afoi mai tala e ai le mataupu e ai totonu tusitala o le itu o faamatalaga";
-const kTeststr_sn_Latn = " chete vanyori vanotevera vakabatsira kunyora zvikamu zvino kumba home tinyorere tsamba chikamu chakumbirwa hachina kuwanikwa chikamu ichi cheninge chakayiswa kuimwe nzvimbo mudhairekitori rino chimwe chikamu chopadhuze pane chinhu chatadza kushanda bad";
-const kTeststr_so_Latn = " a oo maanta bogga koobaad ugu qoran yahey beesha caalamka laakiin si kata oo beesha caalamku ula guntato soomaaliya waxa aan shaki ku jirin in aakhirataanka dadka soomaalida oo kaliya ay yihiin ku soomaaliya ka saari kara dhibka ay ku jirto";
-const kTeststr_sq_Latn = " a do të kërkoni nga beogradi që të njohë pavarësinë e kosovës zoti thaçi prishtina është gati ta njoh pavarësinë e serbisë ndërsa natyrisht se do të kërkohet një gjë e tillë që edhe beogradi ta njoh shtetin e pavarur dhe sovran të";
-const kTeststr_sr_Cyrl = "балчак балчак на мапи Ñрбије уреди демографија у наÑељу балчак живи пунолетна Ñтановника а проÑечна ÑтароÑÑ‚ Ñтановништва изноÑи година";
-const kTeststr_sr_Latn = "DruÅ¡tvo | Äetvrtak 1.08.2013 | 13:43 Krade se i izvorska voda Izvor: Gornji Milanovac -- U gružanskom selu Belo Polje proÅ¡le noći ukradeno je viÅ¡e od 10.000 litara kojima je obijen bazen. Bazen je bio zakljuÄan i propisno obezbeÄ‘en.";
-
-const kTeststr_sr_ME_Latn = "savjet pobjeda a radi bržeg rada poÅ¡to rom radi sporije nego ram izvorni rom se iskljuÄuje a dio ram a se rezerviÅ¡e te se u njega ne ploÄa procesor ram memorija grafiÄka kartica zvuÄna kartica modem mrežna kartica napojna jedinica ureÄ‘aji za pohranjivanje";
-const kTeststr_ss_Latn = " bakhokhintsela yesikhashana bafake imininingwane ye akhawunti leliciniso kulelifomu nangabe akukafakwa imininingwane leliciniso imali lekhokhiwe angeke ifakwe kumkhokhintsela lofanele imininingwane ye akhawunti ime ngalendlela lelandzelako inombolo";
-const kTeststr_st_Latn = " bang ba nang le thahasello matshwao a sehlooho thuto e thehilweng hodima diphetho ke tsela ya ho ruta le ho ithuta e totobatsang hantle seo baithuti ba lokelang ho se fihlella ntlhatheo eo e sebetsang ka yona ke ya hore titjhere o hlakisa pele seo";
-const kTeststr_su_Latn = "Nu ngatur kahirupan warga, keur kapentingan pamarentahan diatur ku RT, RW jeung Kepala Dusun, sedengkeun urusan adat dipupuhuan ku Kuncen jeung kepala adat. Sanajan Kampung Kuta teu pati anggang jeung lembur sejenna nu aya di wewengkon Desa Pasir Angin, tapi boh wangunan imah atawa tradisi kahirupan masarakatna nenggang ti nu lian.";
-const kTeststr_sv_Latn = " a bort objekt från google desktop post äldst meny öretag dress etaljer alternativ för vad är inne yaste google skrivbord plugin program för nyheter google visa nyheter som är anpassade efter de artiklar som du läser om du till exempel läser";
-const kTeststr_sw_Latn = " a ujumbe mpya jumla unda tafuta na angalia vikundi vya kujadiliana na kushiriki mawazo iliyopangwa kwa tarehe watumiaji wapya futa orodha hizi lugha hoja vishikanisho vilivyo dhaminiwa ujumbe sanaa na tamasha toka udhibitisho wa neno kwa haraka fikia";
-const kTeststr_syr_Syrc = "ÜܕܪÜÜ£ ܓܛܘ ܫܘܪÜÜ Ü¡Ü¢ Ü¦ÜªÜ¢Ü£Ü Ü¡Ü¢ ÜܣܦܢÜÜ ÜšÜÜªÜ˜Ü¬Ü Ü’Üܕܪ Ü’Ü¢Üܣܢ Ü«Ü›ÜÜšÜ˜Ü¬Ü ÜŸÜ Ü¢ÜÜ Ü¡ÜÌˆÜ Ü’Ü¥Ü Ü¡Ü";
-const kTeststr_ta_Taml = " à®…à®™à¯à®•à¯ ராஜேநà¯à®¤à®¿à®° சோழனால௠கடà¯à®Ÿà®ªà¯à®ªà®Ÿà¯à®Ÿ பிரமà¯à®®à®¾à®£à¯à®Ÿà®®à®¾à®© சிவன௠கோவில௠ஒனà¯à®±à¯à®®à¯ உளà¯à®³à®¤à¯ தொகà¯";
-const kTeststr_te_Telu = " ఠదనర జయించిన తతà±à°µ మరసి చూడఠదాన యగà±à°¨à± రాజయోగి యిటà±à°²à± తేజరిలà±à°²à±à°šà± à°¨à±à°‚డౠవిశà±à°µà°¦à°¾à°­à°¿à°°à°¾à°® వినర వేమ";
-const kTeststr_tg_Arab = "رادیو Ùردا راديوى آزادى";
-const kTeststr_tg_Cyrl = " адолат ва инÑондӯÑтиро бар фашизм нажодпараÑÑ‚Ó£ ва адоват тарҷеҳ додааÑÑ‚ чоп кунед ба дигарон фириÑтед чоп кунед ба дигарон фириÑтед";
-const kTeststr_th_Thai = " à¸à¸à¹ƒà¸™à¸à¸²à¸£à¸„้นหา หรือหน้าเนื้อหา หาà¸à¸—่านเลือà¸à¸¥à¸‡à¹‚ฆษณา ท่านอาจจะปรับต้องเพิ่มงบประมาณรายวันตา";
-const kTeststr_ti_Ethi = " ሃገር ተረáŽáˆ ዘለዉ ኢትዮጵያá‹á‹«áŠ• ኣብቲ áˆáˆµ ኢትዮጵያ á‹á‹³á‹á‰¥ ኣá‹áˆ«áŒƒ ደቡብ ንኽáŠá‰¥áˆ© ኣይáቀደሎáˆáŠ• እዩ ካብ ሃገር ንኽትወጽእ ዜጋ ኹን ወጻእተኛ ናይ";
-const kTeststr_tk_Cyrl = " айдÑнларына ынанÑрмыка Ñхли боз мейданлары Ñурулип гутарылан тебигы ота гарып гумлукларда миллиондан да артыкмач ири шахлы малы миллиона";
-const kTeststr_tk_Latn = " akyllylyk çyn söýgi üçin böwet däl de tebigylykdyr duýgularyň gödeňsiligi aç açanlygy bahyllygy söýgini betnyşanlyk derejesine düşürýändir söýeni söý söýmedige süýkenme özüni söýmeýändigini görmek ýigit üçin uly";
-const kTeststr_tl_Latn = " a na ugma sa google ay nakaka bantog sa gitna nang kliks na nangyayari sa pamamagitan nang ordinaryong paggagamit at sa kliks na likha nang pandaraya o hindi tunay na paggamit bunga nito nasasala namin ang mga kliks na hindi kailangan o hindi gusto nang";
-const kTeststr_tl_Tglg = " ᜋᜇ᜔ áœáœ“ᜎᜆ᜔ ᜃ ᜈᜅ᜔ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜂᜉᜅ᜔᜔ ᜋáœáœˆáœŒáœ” ᜎᜅ᜔ áœáœ ᜉᜅ᜔ ᜀᜃ᜔ᜎᜆ᜔ ᜆᜓᜅ᜔ᜃᜓᜎ᜔ ᜠᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜠᜆᜒᜅᜒᜈ᜔ ᜃᜓ";
-const kTeststr_tlh_Latn = " a ghuv bid soh naq jih lodni yisov chich wo vamvo qeylis lunge pu chah povpu vodleh a dah ghah cho ej dah wo che pujwi bommu tlhegh darinmohlahchu pu majqa horey so lom qa ip quv law may vad suvtahbogh wa sanid utlh quv pus datu pu a vitu chu pu johwi tar";
-const kTeststr_tn_Latn = " go etela batla ditsebe tsa web tse di nang le le batla ditsebe tse di golaganya le tswang mo leka go batla web yotlhe batla mo web yotlhe go bona home page ya google batla mo a o ne o batla gore a o ne o batla ditsebe tsa bihari batla mo re maswabi ga go";
-const kTeststr_to_Latn = " a ke kumi oku ikai ke ma u vakai ki hono hokohoko faka alafapeti api pe ko e uluaki peesi a ho o fekumi faka malatihi fekumi ki he lea oku fakaha atu pe ko ha fonua fekumi ki he fekumi ki he peesi oku ngaahi me a oku sai imisi alu ki he ki he ulu aki";
-const kTeststr_tr_Latn = " a ayarlarınızı görmeniz ve yönetmeniz içindir eğer kampanyanız için günlük bütçenizi gözden geçirebileceğiniz yeri arıyorsanız kampanya yönetimi ne gidin kampanyanızı seçin ve kampanya ayarlarını düzenle yi tıklayın sunumu";
-const kTeststr_ts_Latn = " a ku na timhaka leti nga ta vulavuriwa na google google yi hlonipha yi tlhela yi sirheleta vanhu hinkwavo lava tirhisaka google toolbar ku dyondza hi vusireleli eka system ya hina hi kombela u hlaya vusireleli bya hina eka toolbar mbulavulo wu tshikiwile";
-const kTeststr_tt_Cyrl = "ачарга да бирмәде чәт чәт килеп тора безнең абыйнымы олы абыйнымы Ñштән";
-const kTeststr_tt_Latn = " alarnı eşkärtü proğramnarın eşläwen däwam itü tatar söylämen buldıru wä sizep alu sistemnarın eşläwen däwat itü häm başqalar yılnıñ mayında tatar internetı ictimağıy oyışması milli ts isemle berençe däräcäle häm tat";
-const kTeststr_tw_Latn = " amammui tumidifo no bɛtow ahyɛ atoro som so mpofirim na wɔasɛe no pasaa ma ayɛ nwonwa dɛn na ɛbɛka wɔn ma wɔayɛ saa bible no ma ho mmuae wɔ adiyisɛm nhoma no mu sɛ onyankopɔn na ɔde hyɛɛ wɔn komam sɛ wɔmma ne nsusuwii mmra mu";
-const kTeststr_ug_Arab = " ئالەملەرنىڭ پەرۋەردىگارىدىن تىلەيمەن سىلەر بۇ يەرلەردە باغچىلاردىن بۇلاقلاردىن زىرائەتلەردىن يۇمشاق پىشقان خورمىلاردىن بەھرىمەن بولۇپ";
-const kTeststr_ug_Cyrl = " а башлиди әмма бу қетимқи канада мәтбуатлириниң хәвәрлиридә илгирикидәк хитай һөкүмәт мәтбуатлиридин нәқил алидиған вә уни көчүрүп";
-const kTeststr_ug_Latn = " adawet bolghachqa hazir musherrepmu bu ikki partiyining birleshme hökümet qurushta pikir birliki hasil qilalmasliqini kütüwatqan iken wehalenki pakistan xelq partiyisining rehbiri asif eli zerdari pakistandiki bashqa ushshaq partiyilerning rehberliri";
-const kTeststr_uk_Cyrl = " а більший бюджет щоб забезпечити Ñобі макÑимум прибутків від переходів відÑтежуйте Ñвої об Ñви за датою географічним розташуваннÑм";
-const kTeststr_ur_Arab = " آپ Ú©Ùˆ Ú©Ù… سے Ú©Ù… Ù…Ù…Ú©Ù†Û Ø±Ù‚Ù… چارج کرتا ÛÛ’ اس Ú©ÛŒ مثال Ú©Û’ طور پر Ùرض کریں اگر آپ Ú©ÛŒ Ø²ÛŒØ§Ø¯Û Ø³Û’ Ø²ÛŒØ§Ø¯Û Ù‚ÛŒÙ…Øª ÙÛŒ Ú©Ù„ÙÚ© امریکی ڈالر اور Ú©Ù„ÙÚ© کرنے Ú©ÛŒ شرح ÛÙˆ تو";
-const kTeststr_uz_Arab = " آرقلی بوتون سیاسی حزب Ùˆ گروه لرÙعالیتیگه رخصت بیرگن اخبارات واسطه لری شو ییل مدتیده مثال سیز ترقی تاپکن Ùˆ اهالی نینگ اقتصادی وضعیتی اوتمیش";
-const kTeststr_uz_Cyrl = " а гапирадиган бўлÑак бунинг иккита йўли бор биринчиÑи мана шу қуриган Ñатҳини қумликларни тўхтатиш учун Ñкотизимни муÑтаҳкамлаш қумга";
-const kTeststr_uz_Latn = " abadiylashtirildi aqsh ayol prezidentga tayyormi markaziy osiyo afg onistonga qanday yordam berishi mumkin ukrainada o zbekistonlik muhojirlar tazyiqdan shikoyat qilmoqda gruziya va ukraina hozircha natoga qabul qilinmaydi afg oniston o zbekistonni g";
-const kTeststr_ve_Latn = "Vho ṱanganedzwa kha Wikipedia nga tshiVenḓa. Vhadivhi vha manwalo a TshiVenda vha talusa divhazwakale na vhubvo ha Vhavenda ngau fhambana. Vha tikedza mbuno dzavho uya nga mawanwa a thoduluso dze vha ita. Vhanwe vha vhatodulusi vhari Vhavenda vho tumbuka Afrika vhukati vha tshimbila vha tshiya Tshipembe ha Afrika, Rhodesia hune ha vho vhidzwa Zimbagwe namusi.";
-const kTeststr_vi_Latn = " adsense cho nội dung nhaÌ€ cung câÌp diÌ£ch vuÌ£ di động xaÌc minh tiÌn duÌ£ng thay đổi nhãn kg caÌc ô xem chi phiÌ cho tÆ°Ì€ chôÌi caÌc Ä‘Æ¡n đặt haÌ€ng daÌ£ng câÌp dữ liệu aÌc minh trang web của baÌ£n để xem";
-const kTeststr_vo_Latn = " brefik se volapükavol nüm balid äpubon ün dü lif lölik okas redakans älaipübons gasedi at nomöfiko äd ai mu kuratiko pläo timü koup nedäna fa ns deutän kü päproibon fa koupanef me gased at ästeifülom ad propagidön volapüki as sam ün";
-const kTeststr_war_Latn = "Amo ini an balay han Winaray o Binisaya nga Lineyte-Samarnon nga Wikipedia, an libre ngan gawasnon nga ensayklopedya nga bisan hin-o puyde magliwat o mag-edit. An Wikipedia syahan gintikang ha Iningles nga yinaknan han tuig 2001. Ini nga bersyon Winaray gintikang han ika-25 han Septyembre 2005 ngan ha yana mayda 514,613 nga artikulo. Kon karuyag niyo magsari o magprobar, pakadto ha . An Gastrotheca pulchra[2] in uska species han Anura nga ginhulagway ni Ulisses Caramaschi ngan Rodrigues hadton 2007. An Gastrotheca pulchra in nahilalakip ha genus nga Gastrotheca, ngan familia nga Hemiphractidae.[3][4] Ginklasipika han IUCN an species komo kulang hin datos.[1] Waray hini subspecies nga nakalista.[3]";
-const kTeststr_wo_Latn = " am ak dëgg dëggam ak gëm aji bind ji te gëstu ko te jëfandikoo tegtalu xel ci saxal ko sokraat nag jëfandikoo woon na xeltu ngir tas jikko yu rafet ci biir nit ñi ak dëggu ak soppante sokraat nag ñëw na mook aflaton platon sukkandiku ci ñaari";
-const kTeststr_xh_Latn = " a naynga zonke futhi libhengezwa kwiwebsite yebond yasemzantsi afrika izinga elisebenzayo xa usenza olu tyalo mali liya kusebenza de liphele ixesha lotyalo mali lwakho inzala ihlawulwa rhoqo emva kweenyanga ezintandathu ngomhla wamashumi amathathu ananye";
-const kTeststr_xx_Bugi = "ᨄᨛᨑᨊᨒ ᨑᨗ ᨔᨒᨗᨓᨛ ᨕᨗᨋᨗᨔᨗ ᨒᨛᨄ ᨑᨛᨔᨛᨆᨗᨊ";
-const kTeststr_xx_Goth = "ðŒ° ðŒ°ðŒ±ð‚ðŒ°ðŒ·ðŒ°ðŒ¼ ðŒ°ðŒ²ðŒ²ðŒ¹ðŒ»ðŒ¹ðƒðŒºðƒ ðŒ¸ðŒ¹ðŒ¿ðŒ³ðŒ¹ðƒðŒºðƒ ð†ð‚ðŒ°ðŒ²ðŒºðŒ¹ðƒðŒºðƒ";
-const kTeststr_yi_Hebr = "×ון פ×נט××–×™×¢ ער ××™×– ב×ק×נט ×¦×™× ×ž×¢×¨×¡×˜×Ÿ פ×ר ×–×™×™× ×¢ ב×ַל×ַדעס ער ×”×ָט געוווינט ×ין וו×רשע יעס פ×ריס ליווערפול ×ון ל×נד×ן סוף כל סוף ××™×– ער";
-const kTeststr_yo_Latn = " abinibi han ikawe alantakun le ni opolopo ede abinibi ti a to lesese bi eniyan to fe lo se fe lati se atunse jowo mo pe awon oju iwe itakunagbaye miran ti ako ni oniruru ede abinibi le faragba nipa atunse ninu se iwadi blogs ni ori itakun agbaye ti e ba";
-const kTeststr_za_Hani = " 两个宾语的字数较少时 åªå¸¦ä¸€ä¸ªåŠ¨è¯ å¦åˆ™å°±å¸¦ä¸¤ä¸ªåŠ¨è¯ 三å¥å­ç±» 从å¥å­æ–¹é¢åŽ»è°ˆæ±‰ 壮语结构格å¼ç›¸å¼‚的类型的 å«å¥å­ç±» 汉 壮语中 å¥å­ç±»ç»“æž„æ ¼å¼æœ‰å·®åˆ«çš„自然ä¸å°‘";
-const kTeststr_za_Latn = " dih yinzminz ndaej daengz bujbienq youjyau dih cingzyin caeuq cinhingz diuz daihit boux boux ma daengz lajmbwn couh miz cwyouz cinhyenz caeuq genzli bouxboux bingzdaengj gyoengq vunz miz lijsing caeuq liengzsim wngdang daih gyoengq de lumj beixnuengx";
-const kTeststr_zh_Hans = "产å“的简报和公告 æ交该申请åŽæ— æ³•è¿›è¡Œæ›´æ”¹ 请确认您的选择是正确的 对于è¦æ交的图书 我确认 我是版æƒæ‰€æœ‰è€…或已得到版æƒæ‰€æœ‰è€…çš„æŽˆæƒ è¦æ›´æ”¹æ‚¨çš„国家 地区 请在此表的最上端更改您的";
-const kTeststr_zh_Hant = " 之å‰ç‚º å¸³å–®äº¤æ˜“ä½œæ¥­å€ å·²è®Šæ›´ 廣告內容 之å‰ç‚º 銷售代表 之å‰ç‚º 張貼日期為 百分比之å‰ç‚º åˆç´„ 為 目標å°è±¡æ¢ä»¶å·²åˆªé™¤ çµæŸæ—¥æœŸä¹‹å‰ç‚º";
-const kTeststr_zu_Latn = " ana engu uma inkinga iqhubeka siza ubike kwi isexwayiso ngenxa yephutha lomlekeleli sikwazi ukubuyisela emuva kuphela imiphumela engaqediwe ukuthola imiphumela eqediwe zama ukulayisha kabusha leli khasi emizuzwini engu uma inkinga iqhubeka siza uthumele";
-const kTeststr_zzb_Latn = "becoose a ve a leemit qooereees tu vurds um gesh dee bork bork nu peges vere a fuoond cunteeening is a fery cummun vurd und ves nut inclooded in yuoor seerch zee ooperetur is unnecessery ve a incloode a ell seerch terms by deffoolt um de hur de hur de hur";
-const kTeststr_zze_Latn = " a diffewent type of seawch send feedback about google wiwewess seawch to wap google com wesuwts found on de entiwe web fow wesuwts found on de mobiwe web fow de functionawity of de toolbar up button has been expanded swightwy it now considews fow exampwe";
-const kTeststr_zzh_Latn = " b x z un b e t und rs n a dr ss p as ry an th r a dr ss ry us n a l ss mb gu us c ti n l ke a z p c d n a dr ss nt r d pl as en r n a dr ss y ur s ar h f r n ar d d n t m tch ny l c ti n w th n m l s nd m r r at d p g s th l c ti ns b l w w r ut m t ca y";
-const kTeststr_zzp_Latn = " away ackupbay editcray ardcay ybay isitingvay ouryay illingbay eferencespray agepay orway isitvay ethay adwordsway elphay entrecay orfay oremay etailsday adwordsway ooglegay omcay upportsay";
-
-// Two very close Wikipedia page beginnings
-const kTeststr_ms_close = "sukiyaki wikipedia bahasa melayu ensiklopedia bebas sukiyaki dari wikipedia bahasa melayu ensiklopedia bebas lompat ke navigasi gelintar sukiyaki sukiyaki hirisan tipis daging lembu sayur sayuran dan tauhu di dalam periuk besi yang dimasak di atas meja makan dengan cara rebusan sukiyaki dimakan dengan mence";
-const kTeststr_id_close = "sukiyaki wikipedia indonesia ensiklopedia bebas berbahasa bebas berbahasa indonesia langsung ke navigasi cari untuk pengertian lain dari sukiyaki lihat sukiyaki irisan tipis daging sapi sayur sayuran dan tahu di dalam panci besi yang dimasak di atas meja makan dengan cara direbus sukiyaki dimakan dengan mence";
-
-// Simple intermixed French/English text
-const kTeststr_fr_en_Latn = "France is the largest country in Western Europe and the third-largest in Europe as a whole. " +
- "A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter " +
- "Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, " +
- "Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus." +
- "Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog";
-
-// This can be used to cross-check the build date of the main quadgram table
-const kTeststr_version = "qpdbmrmxyzptlkuuddlrlrbas las les qpdbmrmxyzptlkuuddlrlrbas el la qpdbmrmxyzptlkuuddlrlrbas";
-
-const kTestPairs = [
-// A simple case to begin
- ["en", "ENGLISH", kTeststr_en],
-
-// 20 languages recognized via Unicode script
- ["hy", "ARMENIAN", kTeststr_hy_Armn],
- ["chr", "CHEROKEE", kTeststr_chr_Cher],
- ["dv", "DHIVEHI", kTeststr_dv_Thaa],
- ["ka", "GEORGIAN", kTeststr_ka_Geor],
- ["el", "GREEK", kTeststr_el_Grek],
- ["gu", "GUJARATI", kTeststr_gu_Gujr],
- ["iu", "INUKTITUT", kTeststr_iu_Cans],
- ["kn", "KANNADA", kTeststr_kn_Knda],
- ["km", "KHMER", kTeststr_km_Khmr],
- ["lo", "LAOTHIAN", kTeststr_lo_Laoo],
- ["lif", "LIMBU", kTeststr_lif_Limb],
- ["ml", "MALAYALAM", kTeststr_ml_Mlym],
- ["or", "ORIYA", kTeststr_or_Orya],
- ["pa", "PUNJABI", kTeststr_pa_Guru],
- ["si", "SINHALESE", kTeststr_si_Sinh],
- ["syr", "SYRIAC", kTeststr_syr_Syrc],
- ["tl", "TAGALOG", kTeststr_tl_Tglg], // Also in quadgram list below
- ["ta", "TAMIL", kTeststr_ta_Taml],
- ["te", "TELUGU", kTeststr_te_Telu],
- ["th", "THAI", kTeststr_th_Thai],
-
-// 4 languages regognized via single letters
- ["zh", "CHINESE", kTeststr_zh_Hans],
- ["zh-Hant", "CHINESET", kTeststr_zh_Hant],
- ["ja", "JAPANESE", kTeststr_ja_Hani],
- ["ko", "KOREAN", kTeststr_ko_Hani],
-
-// 60 languages recognized via combinations of four letters
- ["af", "AFRIKAANS", kTeststr_af_Latn],
- ["sq", "ALBANIAN", kTeststr_sq_Latn],
- ["ar", "ARABIC", kTeststr_ar_Arab],
- ["az", "AZERBAIJANI", kTeststr_az_Latn],
- ["eu", "BASQUE", kTeststr_eu_Latn],
- ["be", "BELARUSIAN", kTeststr_be_Cyrl],
- ["bn", "BENGALI", kTeststr_bn_Beng], // No Assamese in subset
- ["bh", "BIHARI", kTeststr_bh_Deva],
- ["bg", "BULGARIAN", kTeststr_bg_Cyrl],
- ["ca", "CATALAN", kTeststr_ca_Latn],
- ["ceb", "CEBUANO", kTeststr_ceb_Latn],
- ["hr", "CROATIAN", kTeststr_hr_Latn, [false, 0, "el", 4]],
- ["cs", "CZECH", kTeststr_cs_Latn],
- ["da", "DANISH", kTeststr_da_Latn],
- ["nl", "DUTCH", kTeststr_nl_Latn],
- ["en", "ENGLISH", kTeststr_en_Latn],
- ["et", "ESTONIAN", kTeststr_et_Latn],
- ["fi", "FINNISH", kTeststr_fi_Latn],
- ["fr", "FRENCH", kTeststr_fr_Latn],
- ["gl", "GALICIAN", kTeststr_gl_Latn],
- ["lg", "GANDA", kTeststr_lg_Latn],
- ["de", "GERMAN", kTeststr_de_Latn],
- ["ht", "HAITIAN_CREOLE", kTeststr_ht_Latn],
- ["he", "HEBREW", kTeststr_he_Hebr],
- ["hi", "HINDI", kTeststr_hi_Deva],
- ["hmn", "HMONG", kTeststr_blu_Latn],
- ["hu", "HUNGARIAN", kTeststr_hu_Latn],
- ["is", "ICELANDIC", kTeststr_is_Latn],
- ["id", "INDONESIAN", kTeststr_id_Latn],
- ["ga", "IRISH", kTeststr_ga_Latn],
- ["it", "ITALIAN", kTeststr_it_Latn],
- ["jw", "JAVANESE", kTeststr_jw_Latn],
- ["rw", "KINYARWANDA", kTeststr_rw_Latn],
- ["lv", "LATVIAN", kTeststr_lv_Latn],
- ["lt", "LITHUANIAN", kTeststr_lt_Latn],
- ["mk", "MACEDONIAN", kTeststr_mk_Cyrl],
- ["ms", "MALAY", kTeststr_ms_Latn],
- ["mt", "MALTESE", kTeststr_mt_Latn],
- ["mr", "MARATHI", kTeststr_mr_Deva, [false, 0, "te", 3]],
- ["ne", "NEPALI", kTeststr_ne_Deva],
- ["no", "NORWEGIAN", kTeststr_no_Latn],
- ["fa", "PERSIAN", kTeststr_fa_Arab],
- ["pl", "POLISH", kTeststr_pl_Latn],
- ["pt", "PORTUGUESE", kTeststr_pt_Latn],
- ["ro", "ROMANIAN", kTeststr_ro_Latn],
- ["ro", "ROMANIAN", kTeststr_ro_Cyrl],
- ["ru", "RUSSIAN", kTeststr_ru_Cyrl],
- ["gd", "SCOTS_GAELIC", kTeststr_gd_Latn],
- ["sr", "SERBIAN", kTeststr_sr_Cyrl],
- ["sr", "SERBIAN", kTeststr_sr_Latn],
- ["sk", "SLOVAK", kTeststr_sk_Latn],
- ["sl", "SLOVENIAN", kTeststr_sl_Latn],
- ["es", "SPANISH", kTeststr_es_Latn],
- ["sw", "SWAHILI", kTeststr_sw_Latn],
- ["sv", "SWEDISH", kTeststr_sv_Latn],
- ["tl", "TAGALOG", kTeststr_tl_Latn],
- ["tr", "TURKISH", kTeststr_tr_Latn],
- ["uk", "UKRAINIAN", kTeststr_uk_Cyrl],
- ["ur", "URDU", kTeststr_ur_Arab],
- ["vi", "VIETNAMESE", kTeststr_vi_Latn],
- ["cy", "WELSH", kTeststr_cy_Latn],
- ["yi", "YIDDISH", kTeststr_yi_Hebr],
-
- // Added 2013.08.31 so-Latn ig-Latn ha-Latn yo-Latn zu-Latn
- ["so", "SOMALI", kTeststr_so_Latn],
- ["ig", "IGBO", kTeststr_ig_Latn],
- ["ha", "HAUSA", kTeststr_ha_Latn],
- ["yo", "YORUBA", kTeststr_yo_Latn],
- ["zu", "ZULU", kTeststr_zu_Latn],
- // Added 2014.01.22 bs-Latn
- ["bs", "BOSNIAN", kTeststr_bs_Latn],
-
-// 2 statistically-close languages
- ["id", "INDONESIAN", kTeststr_id_close, [true, 80], []],
- ["ms", "MALAY", kTeststr_ms_close],
-
-// Simple intermixed French/English text
- ["fr", "FRENCH", kTeststr_fr_en_Latn, [false, 80, "en", 32]],
-
-// Cross-check the main quadgram table build date
-// Change the expected language each time it is rebuilt
- ["az", "AZERBAIJANI", kTeststr_version] // 2014.01.31
-];
-
-Components.utils.import("resource://gre/modules/Timer.jsm");
-let detectorModule = Components.utils.import("resource:///modules/translation/LanguageDetector.jsm");
-
-function check_result(result, langCode, expected) {
- equal(result.language, langCode, "Expected language code");
-
- // Round percentage up to the nearest 5%, since most strings are
- // detected at slightly less than 100%, and we don't want to
- // encode each exact value.
- let percent = result.languages[0].percent;
- percent = Math.ceil(percent / 20) * 20;
-
- equal(result.languages[0].languageCode, langCode, "Expected first guess language code");
- equal(percent, expected[1] || 100, "Expected first guess language percent");
-
- if (expected.length < 3) {
- // We're not expecting a second language.
- equal(result.languages.length, 1, "Expected only one language result");
- } else {
- equal(result.languages.length, 2, "Expected two language results");
-
- equal(result.languages[1].languageCode, expected[2], "Expected second guess language code");
- equal(result.languages[1].percent, expected[3], "Expected second guess language percent");
- }
-
- equal(result.confident, !expected[0], "Expected confidence");
-}
-
-add_task(function* test_pairs() {
- for (let item of kTestPairs) {
- let params = [item[2],
- { text: item[2], tld: "com", language: item[0], encoding: "utf-8" }]
-
- for (let [i, param] of params.entries()) {
- // For test items with different expected results when using the
- // language hint, use those for the hinted version of the API.
- // Otherwise, fall back to the first set of expected values.
- let expected = item[3 + i] || item[3] || [];
-
- let result = yield LanguageDetector.detectLanguage(param);
- check_result(result, item[0], expected);
- }
- }
-});
-
-// Test that the worker is flushed shortly after processing a large
-// string.
-add_task(function* test_worker_flush() {
- let test_string = kTeststr_fr_en_Latn;
- let test_item = kTestPairs.find(item => item[2] == test_string);
-
- // Set shorter timeouts and lower string lengths to make things easier
- // on the test infrastructure.
- detectorModule.LARGE_STRING = test_string.length - 1;
- detectorModule.IDLE_TIMEOUT = 1000;
-
- equal(detectorModule.workerManager._idleTimeout, null,
- "Should have no idle timeout to start with");
-
- let result = yield LanguageDetector.detectLanguage(test_string);
-
- // Make sure the results are still correct.
- check_result(result, test_item[0], test_item[3]);
-
- // We should have an idle timeout after processing the string.
- ok(detectorModule.workerManager._idleTimeout != null,
- "Should have an idle timeout");
- ok(detectorModule.workerManager._worker != null,
- "Should have a worker instance");
- ok(detectorModule.workerManager._workerReadyPromise != null,
- "Should have a worker promise");
-
- // Wait for the idle timeout to elapse.
- yield new Promise(resolve => setTimeout(resolve, detectorModule.IDLE_TIMEOUT));
-
- equal(detectorModule.workerManager._idleTimeout, null,
- "Should have no idle timeout after it has elapsed");
- equal(detectorModule.workerManager._worker, null,
- "Should have no worker instance after idle timeout");
- equal(detectorModule.workerManager._workerReadyPromise, null,
- "Should have no worker promise after idle timeout");
-
- // We should still be able to use the language detector after its
- // worker has been flushed.
- result = yield LanguageDetector.detectLanguage(test_string);
-
- // Make sure the results are still correct.
- check_result(result, test_item[0], test_item[3]);
-});
diff --git a/browser/components/translation/test/unit/xpcshell.ini b/browser/components/translation/test/unit/xpcshell.ini
deleted file mode 100644
index 8431a8c4e..000000000
--- a/browser/components/translation/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-head =
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_cld2.js]
diff --git a/browser/components/translation/test/yandex.sjs b/browser/components/translation/test/yandex.sjs
deleted file mode 100644
index ed515beab..000000000
--- a/browser/components/translation/test/yandex.sjs
+++ /dev/null
@@ -1,199 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, Constructor: CC} = Components;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(req, res) {
- try {
- reallyHandleRequest(req, res);
- } catch (ex) {
- res.setStatusLine("1.0", 200, "AlmostOK");
- let msg = "Error handling request: " + ex + "\n" + ex.stack;
- log(msg);
- res.write(msg);
- }
-}
-
-function log(msg) {
- dump("YANDEX-SERVER-MOCK: " + msg + "\n");
-}
-
-const statusCodes = {
- 400: "Bad Request",
- 401: "Invalid API key",
- 402: "This API key has been blocked",
- 403: "Daily limit for requests reached",
- 404: "Daily limit for chars reached",
- 413: "The text size exceeds the maximum",
- 422: "The text could not be translated",
- 500: "Internal Server Error",
- 501: "The specified translation direction is not supported",
- 503: "Service Unavailable"
-};
-
-function HTTPError(code = 500, message) {
- this.code = code;
- this.name = statusCodes[code] || "HTTPError";
- this.message = message || this.name;
-}
-HTTPError.prototype = new Error();
-HTTPError.prototype.constructor = HTTPError;
-
-function sendError(res, err) {
- if (!(err instanceof HTTPError)) {
- err = new HTTPError(typeof err == "number" ? err : 500,
- err.message || typeof err == "string" ? err : "");
- }
- res.setStatusLine("1.1", err.code, err.name);
- res.write(err.message);
-}
-
-// Based on the code borrowed from:
-// http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
-function parseQuery(query) {
- let match,
- params = {},
- pl = /\+/g,
- search = /([^&=]+)=?([^&]*)/g,
- decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
-
- while (match = search.exec(query)) {
- let k = decode(match[1]),
- v = decode(match[2]);
- if (k in params) {
- if(params[k] instanceof Array)
- params[k].push(v);
- else
- params[k] = [params[k], v];
- } else {
- params[k] = v;
- }
- }
-
- return params;
-}
-
-function sha1(str) {
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- // `result` is an out parameter, `result.value` will contain the array length.
- let result = {};
- // `data` is an array of bytes.
- let data = converter.convertToByteArray(str, result);
- let ch = Cc["@mozilla.org/security/hash;1"]
- .createInstance(Ci.nsICryptoHash);
- ch.init(ch.SHA1);
- ch.update(data, data.length);
- let hash = ch.finish(false);
-
- // Return the two-digit hexadecimal code for a byte.
- function toHexString(charCode) {
- return ("0" + charCode.toString(16)).slice(-2);
- }
-
- // Convert the binary hash data to a hex string.
- return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join("");
-}
-
-function getRequestBody(req) {
- let avail;
- let bytes = [];
- let body = new BinaryInputStream(req.bodyInputStream);
-
- while ((avail = body.available()) > 0)
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
-
- return String.fromCharCode.apply(null, bytes);
-}
-
-function getInputStream(path) {
- let file = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("CurWorkD", Ci.nsILocalFile);
- for (let part of path.split("/"))
- file.append(part);
- let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- fileStream.init(file, 1, 0, false);
- return fileStream;
-}
-
-/**
- * Yandex Requests have to be signed with an API Key. This mock server
- * supports the following keys:
- *
- * yandexValidKey Always passes the authentication,
- * yandexInvalidKey Never passes authentication and fails with 401 code,
- * yandexBlockedKey Never passes authentication and fails with 402 code,
- * yandexOutOfRequestsKey Never passes authentication and fails with 403 code,
- * yandexOutOfCharsKey Never passes authentication and fails with 404 code.
- *
- * If any other key is used the server reponds with 401 error code.
- */
-function checkAuth(params) {
- if(!("key" in params))
- throw new HTTPError(400);
-
- let key = params.key;
- if(key === "yandexValidKey")
- return true;
-
- let invalidKeys = {
- "yandexInvalidKey" : 401,
- "yandexBlockedKey" : 402,
- "yandexOutOfRequestsKey" : 403,
- "yandexOutOfCharsKey" : 404,
- };
-
- if(key in invalidKeys)
- throw new HTTPError(invalidKeys[key]);
-
- throw new HTTPError(401);
-}
-
-function reallyHandleRequest(req, res) {
-
- try {
-
- // Preparing the query parameters.
- let params = {};
- if(req.method == 'POST') {
- params = parseQuery(getRequestBody(req));
- }
-
- // Extracting the API key and attempting to authenticate the request.
- log(JSON.stringify(params));
-
- checkAuth(params);
- methodHandlers['translate'](res, params);
-
- } catch (ex) {
- sendError(res, ex, ex.code);
- }
-
-}
-
-const methodHandlers = {
- translate: function(res, params) {
- res.setStatusLine("1.1", 200, "OK");
- res.setHeader("Content-Type", "application/json");
-
- let hash = sha1(JSON.stringify(params)).substr(0, 10);
- log("SHA1 hash of content: " + hash);
-
- let fixture = "browser/browser/components/translation/test/fixtures/result-yandex-" + hash + ".json";
- log("PATH: " + fixture);
-
- let inputStream = getInputStream(fixture);
- res.bodyOutputStream.writeFrom(inputStream, inputStream.available());
- inputStream.close();
- }
-
-};
diff --git a/browser/components/uitour/test/.eslintrc.js b/browser/components/uitour/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/components/uitour/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/components/uitour/test/browser.ini b/browser/components/uitour/test/browser.ini
deleted file mode 100644
index ae027a738..000000000
--- a/browser/components/uitour/test/browser.ini
+++ /dev/null
@@ -1,49 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- image.png
- uitour.html
- ../UITour-lib.js
-
-[browser_backgroundTab.js]
-[browser_closeTab.js]
-[browser_fxa.js]
-skip-if = debug || asan # updateAppMenuItem leaks
-[browser_no_tabs.js]
-[browser_openPreferences.js]
-[browser_openSearchPanel.js]
-skip-if = true # Bug 1113038 - Intermittent "Popup was opened"
-[browser_trackingProtection.js]
-skip-if = os == "linux" # Intermittent NS_ERROR_NOT_AVAILABLE [nsIUrlClassifierDBService.beginUpdate]
-tag = trackingprotection
-support-files =
- !/browser/base/content/test/general/benignPage.html
- !/browser/base/content/test/general/trackingPage.html
-[browser_trackingProtection_tour.js]
-tag = trackingprotection
-[browser_showMenu_controlCenter.js]
-tag = trackingprotection
-[browser_UITour.js]
-skip-if = os == "linux" # Intermittent failures, bug 951965
-[browser_UITour2.js]
-[browser_UITour3.js]
-skip-if = os == "linux" # Linux: Bug 986760, Bug 989101.
-[browser_UITour_availableTargets.js]
-[browser_UITour_annotation_size_attributes.js]
-[browser_UITour_defaultBrowser.js]
-[browser_UITour_detach_tab.js]
-[browser_UITour_forceReaderMode.js]
-[browser_UITour_heartbeat.js]
-skip-if = os == "win" # Bug 1277107
-[browser_UITour_modalDialog.js]
-skip-if = os != "mac" # modal dialog disabling only working on OS X.
-[browser_UITour_observe.js]
-[browser_UITour_panel_close_annotation.js]
-skip-if = true # Disabled due to frequent failures, bugs 1026310 and 1032137
-[browser_UITour_pocket.js]
-skip-if = true # Disabled pending removal of pocket UI Tour
-[browser_UITour_registerPageID.js]
-[browser_UITour_resetProfile.js]
-[browser_UITour_showNewTab.js]
-[browser_UITour_sync.js]
-[browser_UITour_toggleReaderMode.js]
diff --git a/browser/components/uitour/test/browser_UITour.js b/browser/components/uitour/test/browser_UITour.js
deleted file mode 100644
index 964be0215..000000000
--- a/browser/components/uitour/test/browser_UITour.js
+++ /dev/null
@@ -1,408 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-Components.utils.import("resource://testing-common/TelemetryArchiveTesting.jsm", this);
-
-function test() {
- UITourTest();
-}
-
-var tests = [
- function test_untrusted_host(done) {
- loadUITourTestPage(function() {
- let bookmarksMenu = document.getElementById("bookmarks-menu-button");
- is(bookmarksMenu.open, false, "Bookmark menu should initially be closed");
-
- gContentAPI.showMenu("bookmarks");
- is(bookmarksMenu.open, false, "Bookmark menu should not open on a untrusted host");
-
- done();
- }, "http://mochi.test:8888/");
- },
- function test_testing_host(done) {
- // Add two testing origins intentionally surrounded by whitespace to be ignored.
- Services.prefs.setCharPref("browser.uitour.testingOrigins",
- "https://test1.example.org, https://test2.example.org:443 ");
-
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.uitour.testingOrigins");
- });
- function callback(result) {
- ok(result, "Callback should be called on a testing origin");
- done();
- }
-
- loadUITourTestPage(function() {
- gContentAPI.getConfiguration("appinfo", callback);
- }, "https://test2.example.org/");
- },
- function test_unsecure_host(done) {
- loadUITourTestPage(function() {
- let bookmarksMenu = document.getElementById("bookmarks-menu-button");
- is(bookmarksMenu.open, false, "Bookmark menu should initially be closed");
-
- gContentAPI.showMenu("bookmarks");
- is(bookmarksMenu.open, false, "Bookmark menu should not open on a unsecure host");
-
- done();
- }, "http://example.org/");
- },
- function test_unsecure_host_override(done) {
- Services.prefs.setBoolPref("browser.uitour.requireSecure", false);
- loadUITourTestPage(function() {
- let highlight = document.getElementById("UITourHighlight");
- is_element_hidden(highlight, "Highlight should initially be hidden");
-
- gContentAPI.showHighlight("urlbar");
- waitForElementToBeVisible(highlight, done, "Highlight should be shown on a unsecure host when override pref is set");
-
- Services.prefs.setBoolPref("browser.uitour.requireSecure", true);
- }, "http://example.org/");
- },
- function test_disabled(done) {
- Services.prefs.setBoolPref("browser.uitour.enabled", false);
-
- let bookmarksMenu = document.getElementById("bookmarks-menu-button");
- is(bookmarksMenu.open, false, "Bookmark menu should initially be closed");
-
- gContentAPI.showMenu("bookmarks");
- is(bookmarksMenu.open, false, "Bookmark menu should not open when feature is disabled");
-
- Services.prefs.setBoolPref("browser.uitour.enabled", true);
- done();
- },
- function test_highlight(done) {
- function test_highlight_2() {
- let highlight = document.getElementById("UITourHighlight");
- gContentAPI.hideHighlight();
-
- waitForElementToBeHidden(highlight, test_highlight_3, "Highlight should be hidden after hideHighlight()");
- }
- function test_highlight_3() {
- is_element_hidden(highlight, "Highlight should be hidden after hideHighlight()");
-
- gContentAPI.showHighlight("urlbar");
- waitForElementToBeVisible(highlight, test_highlight_4, "Highlight should be shown after showHighlight()");
- }
- function test_highlight_4() {
- let highlight = document.getElementById("UITourHighlight");
- gContentAPI.showHighlight("backForward");
- waitForElementToBeVisible(highlight, done, "Highlight should be shown after showHighlight()");
- }
-
- let highlight = document.getElementById("UITourHighlight");
- is_element_hidden(highlight, "Highlight should initially be hidden");
-
- gContentAPI.showHighlight("urlbar");
- waitForElementToBeVisible(highlight, test_highlight_2, "Highlight should be shown after showHighlight()");
- },
- function test_highlight_circle(done) {
- function check_highlight_size() {
- let panel = highlight.parentElement;
- let anchor = panel.anchorNode;
- let anchorRect = anchor.getBoundingClientRect();
- info("addons target: width: " + anchorRect.width + " height: " + anchorRect.height);
- let maxDimension = Math.round(Math.max(anchorRect.width, anchorRect.height));
- let highlightRect = highlight.getBoundingClientRect();
- info("highlight: width: " + highlightRect.width + " height: " + highlightRect.height);
- is(Math.round(highlightRect.width), maxDimension, "The width of the highlight should be equal to the largest dimension of the target");
- is(Math.round(highlightRect.height), maxDimension, "The height of the highlight should be equal to the largest dimension of the target");
- is(Math.round(highlightRect.height), Math.round(highlightRect.width), "The height and width of the highlight should be the same to create a circle");
- is(highlight.style.borderRadius, "100%", "The border-radius should be 100% to create a circle");
- done();
- }
- let highlight = document.getElementById("UITourHighlight");
- is_element_hidden(highlight, "Highlight should initially be hidden");
-
- gContentAPI.showHighlight("addons");
- waitForElementToBeVisible(highlight, check_highlight_size, "Highlight should be shown after showHighlight()");
- },
- function test_highlight_customize_auto_open_close(done) {
- let highlight = document.getElementById("UITourHighlight");
- gContentAPI.showHighlight("customize");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Move the highlight outside which should close the app menu.
- gContentAPI.showHighlight("appMenu");
- waitForElementToBeVisible(highlight, function checkPanelIsClosed() {
- isnot(PanelUI.panel.state, "open",
- "Panel should have closed after the highlight moved elsewhere.");
- done();
- }, "Highlight should move to the appMenu button");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
- function test_highlight_customize_manual_open_close(done) {
- let highlight = document.getElementById("UITourHighlight");
- // Manually open the app menu then show a highlight there. The menu should remain open.
- let shownPromise = promisePanelShown(window);
- gContentAPI.showMenu("appMenu");
- shownPromise.then(() => {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
- gContentAPI.showHighlight("customize");
-
- waitForElementToBeVisible(highlight, function checkPanelIsStillOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should still be open");
-
- // Move the highlight outside which shouldn't close the app menu since it was manually opened.
- gContentAPI.showHighlight("appMenu");
- waitForElementToBeVisible(highlight, function () {
- isnot(PanelUI.panel.state, "closed",
- "Panel should remain open since UITour didn't open it in the first place");
- gContentAPI.hideMenu("appMenu");
- done();
- }, "Highlight should move to the appMenu button");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- }).then(null, Components.utils.reportError);
- },
- function test_highlight_effect(done) {
- function waitForHighlightWithEffect(highlightEl, effect, next, error) {
- return waitForCondition(() => highlightEl.getAttribute("active") == effect,
- next,
- error);
- }
- function checkDefaultEffect() {
- is(highlight.getAttribute("active"), "none", "The default should be no effect");
-
- gContentAPI.showHighlight("urlbar", "none");
- waitForHighlightWithEffect(highlight, "none", checkZoomEffect, "There should be no effect");
- }
- function checkZoomEffect() {
- gContentAPI.showHighlight("urlbar", "zoom");
- waitForHighlightWithEffect(highlight, "zoom", () => {
- let style = window.getComputedStyle(highlight);
- is(style.animationName, "uitour-zoom", "The animation-name should be uitour-zoom");
- checkSameEffectOnDifferentTarget();
- }, "There should be a zoom effect");
- }
- function checkSameEffectOnDifferentTarget() {
- gContentAPI.showHighlight("appMenu", "wobble");
- waitForHighlightWithEffect(highlight, "wobble", () => {
- highlight.addEventListener("animationstart", function onAnimationStart(aEvent) {
- highlight.removeEventListener("animationstart", onAnimationStart);
- ok(true, "Animation occurred again even though the effect was the same");
- checkRandomEffect();
- });
- gContentAPI.showHighlight("backForward", "wobble");
- }, "There should be a wobble effect");
- }
- function checkRandomEffect() {
- function waitForActiveHighlight(highlightEl, next, error) {
- return waitForCondition(() => highlightEl.hasAttribute("active"),
- next,
- error);
- }
-
- gContentAPI.hideHighlight();
- gContentAPI.showHighlight("urlbar", "random");
- waitForActiveHighlight(highlight, () => {
- ok(highlight.hasAttribute("active"), "The highlight should be active");
- isnot(highlight.getAttribute("active"), "none", "A random effect other than none should have been chosen");
- isnot(highlight.getAttribute("active"), "random", "The random effect shouldn't be 'random'");
- isnot(UITour.highlightEffects.indexOf(highlight.getAttribute("active")), -1, "Check that a supported effect was randomly chosen");
- done();
- }, "There should be an active highlight with a random effect");
- }
-
- let highlight = document.getElementById("UITourHighlight");
- is_element_hidden(highlight, "Highlight should initially be hidden");
-
- gContentAPI.showHighlight("urlbar");
- waitForElementToBeVisible(highlight, checkDefaultEffect, "Highlight should be shown after showHighlight()");
- },
- function test_highlight_effect_unsupported(done) {
- function checkUnsupportedEffect() {
- is(highlight.getAttribute("active"), "none", "No effect should be used when an unsupported effect is requested");
- done();
- }
-
- let highlight = document.getElementById("UITourHighlight");
- is_element_hidden(highlight, "Highlight should initially be hidden");
-
- gContentAPI.showHighlight("urlbar", "__UNSUPPORTED__");
- waitForElementToBeVisible(highlight, checkUnsupportedEffect, "Highlight should be shown after showHighlight()");
- },
- function test_info_1(done) {
- let popup = document.getElementById("UITourTooltip");
- let title = document.getElementById("UITourTooltipTitle");
- let desc = document.getElementById("UITourTooltipDescription");
- let icon = document.getElementById("UITourTooltipIcon");
- let buttons = document.getElementById("UITourTooltipButtons");
-
- popup.addEventListener("popupshown", function onPopupShown() {
- popup.removeEventListener("popupshown", onPopupShown);
- is(popup.popupBoxObject.anchorNode, document.getElementById("urlbar"), "Popup should be anchored to the urlbar");
- is(title.textContent, "test title", "Popup should have correct title");
- is(desc.textContent, "test text", "Popup should have correct description text");
- is(icon.src, "", "Popup should have no icon");
- is(buttons.hasChildNodes(), false, "Popup should have no buttons");
-
- popup.addEventListener("popuphidden", function onPopupHidden() {
- popup.removeEventListener("popuphidden", onPopupHidden);
-
- popup.addEventListener("popupshown", function onPopupShown() {
- popup.removeEventListener("popupshown", onPopupShown);
- done();
- });
-
- gContentAPI.showInfo("urlbar", "test title", "test text");
-
- });
- gContentAPI.hideInfo();
- });
-
- gContentAPI.showInfo("urlbar", "test title", "test text");
- },
- taskify(function* test_info_2() {
- let popup = document.getElementById("UITourTooltip");
- let title = document.getElementById("UITourTooltipTitle");
- let desc = document.getElementById("UITourTooltipDescription");
- let icon = document.getElementById("UITourTooltipIcon");
- let buttons = document.getElementById("UITourTooltipButtons");
-
- yield showInfoPromise("urlbar", "urlbar title", "urlbar text");
-
- is(popup.popupBoxObject.anchorNode, document.getElementById("urlbar"), "Popup should be anchored to the urlbar");
- is(title.textContent, "urlbar title", "Popup should have correct title");
- is(desc.textContent, "urlbar text", "Popup should have correct description text");
- is(icon.src, "", "Popup should have no icon");
- is(buttons.hasChildNodes(), false, "Popup should have no buttons");
-
- yield showInfoPromise("search", "search title", "search text");
-
- is(popup.popupBoxObject.anchorNode, document.getElementById("searchbar"), "Popup should be anchored to the searchbar");
- is(title.textContent, "search title", "Popup should have correct title");
- is(desc.textContent, "search text", "Popup should have correct description text");
- }),
- function test_getConfigurationVersion(done) {
- function callback(result) {
- let props = ["defaultUpdateChannel", "version"];
- for (let property of props) {
- ok(typeof(result[property]) !== "undefined", "Check " + property + " isn't undefined.");
- is(result[property], Services.appinfo[property], "Should have the same " + property + " property.");
- }
- done();
- }
-
- gContentAPI.getConfiguration("appinfo", callback);
- },
- function test_getConfigurationDistribution(done) {
- gContentAPI.getConfiguration("appinfo", (result) => {
- ok(typeof(result.distribution) !== "undefined", "Check distribution isn't undefined.");
- is(result.distribution, "default", "Should be \"default\" without preference set.");
-
- let defaults = Services.prefs.getDefaultBranch("distribution.");
- let testDistributionID = "TestDistribution";
- defaults.setCharPref("id", testDistributionID);
- gContentAPI.getConfiguration("appinfo", (result) => {
- ok(typeof(result.distribution) !== "undefined", "Check distribution isn't undefined.");
- is(result.distribution, testDistributionID, "Should have the distribution as set in preference.");
-
- done();
- });
- });
- },
- function test_addToolbarButton(done) {
- let placement = CustomizableUI.getPlacementOfWidget("panic-button");
- is(placement, null, "default UI has panic button in the palette");
-
- gContentAPI.getConfiguration("availableTargets", (data) => {
- let available = (data.targets.indexOf("forget") != -1);
- ok(!available, "Forget button should not be available by default");
-
- gContentAPI.addNavBarWidget("forget", () => {
- info("addNavBarWidget callback successfully called");
-
- let placement = CustomizableUI.getPlacementOfWidget("panic-button");
- is(placement.area, CustomizableUI.AREA_NAVBAR);
-
- gContentAPI.getConfiguration("availableTargets", (data) => {
- let available = (data.targets.indexOf("forget") != -1);
- ok(available, "Forget button should now be available");
-
- // Cleanup
- CustomizableUI.removeWidgetFromArea("panic-button");
- done();
- });
- });
- });
- },
- function test_search(done) {
- Services.search.init(rv => {
- if (!Components.isSuccessCode(rv)) {
- ok(false, "search service init failed: " + rv);
- done();
- return;
- }
- let defaultEngine = Services.search.defaultEngine;
- gContentAPI.getConfiguration("search", data => {
- let visibleEngines = Services.search.getVisibleEngines();
- let expectedEngines = visibleEngines.filter((engine) => engine.identifier)
- .map((engine) => "searchEngine-" + engine.identifier);
-
- let engines = data.engines;
- ok(Array.isArray(engines), "data.engines should be an array");
- is(engines.sort().toString(), expectedEngines.sort().toString(),
- "Engines should be as expected");
-
- is(data.searchEngineIdentifier, defaultEngine.identifier,
- "the searchEngineIdentifier property should contain the defaultEngine's identifier");
-
- let someOtherEngineID = data.engines.filter(t => t != "searchEngine-" + defaultEngine.identifier)[0];
- someOtherEngineID = someOtherEngineID.replace(/^searchEngine-/, "");
-
- let observe = function (subject, topic, verb) {
- info("browser-search-engine-modified: " + verb);
- if (verb == "engine-current") {
- is(Services.search.defaultEngine.identifier, someOtherEngineID, "correct engine was switched to");
- done();
- }
- };
- Services.obs.addObserver(observe, "browser-search-engine-modified", false);
- registerCleanupFunction(() => {
- // Clean up
- Services.obs.removeObserver(observe, "browser-search-engine-modified");
- Services.search.defaultEngine = defaultEngine;
- });
-
- gContentAPI.setDefaultSearchEngine(someOtherEngineID);
- });
- });
- },
- taskify(function* test_treatment_tag() {
- let ac = new TelemetryArchiveTesting.Checker();
- yield ac.promiseInit();
- yield gContentAPI.setTreatmentTag("foobar", "baz");
- // Wait until the treatment telemetry is sent before looking in the archive.
- yield BrowserTestUtils.waitForContentEvent(gTestTab.linkedBrowser, "mozUITourNotification", false,
- event => event.detail.event === "TreatmentTag:TelemetrySent");
- yield new Promise((resolve) => {
- gContentAPI.getTreatmentTag("foobar", (data) => {
- is(data.value, "baz", "set and retrieved treatmentTag");
- ac.promiseFindPing("uitour-tag", [
- [["payload", "tagName"], "foobar"],
- [["payload", "tagValue"], "baz"],
- ]).then((found) => {
- ok(found, "Telemetry ping submitted for setTreatmentTag");
- resolve();
- }, (err) => {
- ok(false, "Exception finding uitour telemetry ping: " + err);
- resolve();
- });
- });
- });
- }),
-
- // Make sure this test is last in the file so the appMenu gets left open and done will confirm it got tore down.
- taskify(function* cleanupMenus() {
- let shownPromise = promisePanelShown(window);
- gContentAPI.showMenu("appMenu");
- yield shownPromise;
- }),
-];
diff --git a/browser/components/uitour/test/browser_UITour2.js b/browser/components/uitour/test/browser_UITour2.js
deleted file mode 100644
index e74a71afa..000000000
--- a/browser/components/uitour/test/browser_UITour2.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-function test() {
- UITourTest();
-}
-
-var tests = [
- function test_info_customize_auto_open_close(done) {
- let popup = document.getElementById("UITourTooltip");
- gContentAPI.showInfo("customize", "Customization", "Customize me please!");
- UITour.getTarget(window, "customize").then((customizeTarget) => {
- waitForPopupAtAnchor(popup, customizeTarget.node, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened before the popup anchored");
- ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been set");
-
- // Move the info outside which should close the app menu.
- gContentAPI.showInfo("appMenu", "Open Me", "You know you want to");
- UITour.getTarget(window, "appMenu").then((target) => {
- waitForPopupAtAnchor(popup, target.node, function checkPanelIsClosed() {
- isnot(PanelUI.panel.state, "open",
- "Panel should have closed after the info moved elsewhere.");
- ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up on close");
- done();
- }, "Info should move to the appMenu button");
- });
- }, "Info panel should be anchored to the customize button");
- });
- },
- function test_info_customize_manual_open_close(done) {
- let popup = document.getElementById("UITourTooltip");
- // Manually open the app menu then show an info panel there. The menu should remain open.
- let shownPromise = promisePanelShown(window);
- gContentAPI.showMenu("appMenu");
- shownPromise.then(() => {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
- ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been set");
- gContentAPI.showInfo("customize", "Customization", "Customize me please!");
-
- UITour.getTarget(window, "customize").then((customizeTarget) => {
- waitForPopupAtAnchor(popup, customizeTarget.node, function checkMenuIsStillOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should still be open");
- ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should still be set");
-
- // Move the info outside which shouldn't close the app menu since it was manually opened.
- gContentAPI.showInfo("appMenu", "Open Me", "You know you want to");
- UITour.getTarget(window, "appMenu").then((target) => {
- waitForPopupAtAnchor(popup, target.node, function checkMenuIsStillOpen() {
- isnot(PanelUI.panel.state, "closed",
- "Menu should remain open since UITour didn't open it in the first place");
- waitForElementToBeHidden(window.PanelUI.panel, () => {
- ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up on close");
- done();
- });
- gContentAPI.hideMenu("appMenu");
- }, "Info should move to the appMenu button");
- });
- }, "Info should be shown after showInfo() for fixed menu panel items");
- });
- }).then(null, Components.utils.reportError);
- },
- taskify(function* test_bookmarks_menu() {
- let bookmarksMenuButton = document.getElementById("bookmarks-menu-button");
-
- is(bookmarksMenuButton.open, false, "Menu should initially be closed");
- gContentAPI.showMenu("bookmarks");
-
- yield waitForConditionPromise(() => {
- return bookmarksMenuButton.open;
- }, "Menu should be visible after showMenu()");
-
- gContentAPI.hideMenu("bookmarks");
- yield waitForConditionPromise(() => {
- return !bookmarksMenuButton.open;
- }, "Menu should be hidden after hideMenu()");
- }),
-];
diff --git a/browser/components/uitour/test/browser_UITour3.js b/browser/components/uitour/test/browser_UITour3.js
deleted file mode 100644
index b852339f1..000000000
--- a/browser/components/uitour/test/browser_UITour3.js
+++ /dev/null
@@ -1,181 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-requestLongerTimeout(2);
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_info_icon() {
- let popup = document.getElementById("UITourTooltip");
- let title = document.getElementById("UITourTooltipTitle");
- let desc = document.getElementById("UITourTooltipDescription");
- let icon = document.getElementById("UITourTooltipIcon");
- let buttons = document.getElementById("UITourTooltipButtons");
-
- // Disable the animation to prevent the mouse clicks from hitting the main
- // window during the transition instead of the buttons in the popup.
- popup.setAttribute("animate", "false");
-
- yield showInfoPromise("urlbar", "a title", "some text", "image.png");
-
- is(title.textContent, "a title", "Popup should have correct title");
- is(desc.textContent, "some text", "Popup should have correct description text");
-
- let imageURL = getRootDirectory(gTestPath) + "image.png";
- imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/");
- is(icon.src, imageURL, "Popup should have correct icon shown");
-
- is(buttons.hasChildNodes(), false, "Popup should have no buttons");
-}),
-
-add_UITour_task(function* test_info_buttons_1() {
- let popup = document.getElementById("UITourTooltip");
- let title = document.getElementById("UITourTooltipTitle");
- let desc = document.getElementById("UITourTooltipDescription");
- let icon = document.getElementById("UITourTooltipIcon");
-
- yield showInfoPromise("urlbar", "another title", "moar text", "./image.png", "makeButtons");
-
- is(title.textContent, "another title", "Popup should have correct title");
- is(desc.textContent, "moar text", "Popup should have correct description text");
-
- let imageURL = getRootDirectory(gTestPath) + "image.png";
- imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/");
- is(icon.src, imageURL, "Popup should have correct icon shown");
-
- let buttons = document.getElementById("UITourTooltipButtons");
- is(buttons.childElementCount, 4, "Popup should have four buttons");
-
- is(buttons.childNodes[0].nodeName, "label", "Text label should be a <label>");
- is(buttons.childNodes[0].getAttribute("value"), "Regular text", "Text label should have correct value");
- is(buttons.childNodes[0].getAttribute("image"), "", "Text should have no image");
- is(buttons.childNodes[0].className, "", "Text should have no class");
-
- is(buttons.childNodes[1].nodeName, "button", "Link should be a <button>");
- is(buttons.childNodes[1].getAttribute("label"), "Link", "Link should have correct label");
- is(buttons.childNodes[1].getAttribute("image"), "", "Link should have no image");
- is(buttons.childNodes[1].className, "button-link", "Check link class");
-
- is(buttons.childNodes[2].nodeName, "button", "Button 1 should be a <button>");
- is(buttons.childNodes[2].getAttribute("label"), "Button 1", "First button should have correct label");
- is(buttons.childNodes[2].getAttribute("image"), "", "First button should have no image");
- is(buttons.childNodes[2].className, "", "Button 1 should have no class");
-
- is(buttons.childNodes[3].nodeName, "button", "Button 2 should be a <button>");
- is(buttons.childNodes[3].getAttribute("label"), "Button 2", "Second button should have correct label");
- is(buttons.childNodes[3].getAttribute("image"), imageURL, "Second button should have correct image");
- is(buttons.childNodes[3].className, "button-primary", "Check button 2 class");
-
- let promiseHidden = promisePanelElementHidden(window, popup);
- EventUtils.synthesizeMouseAtCenter(buttons.childNodes[2], {}, window);
- yield promiseHidden;
-
- ok(true, "Popup should close automatically");
-
- let returnValue = yield waitForCallbackResultPromise();
- is(returnValue.result, "button1", "Correct callback should have been called");
-});
-
-add_UITour_task(function* test_info_buttons_2() {
- let popup = document.getElementById("UITourTooltip");
- let title = document.getElementById("UITourTooltipTitle");
- let desc = document.getElementById("UITourTooltipDescription");
- let icon = document.getElementById("UITourTooltipIcon");
-
- yield showInfoPromise("urlbar", "another title", "moar text", "./image.png", "makeButtons");
-
- is(title.textContent, "another title", "Popup should have correct title");
- is(desc.textContent, "moar text", "Popup should have correct description text");
-
- let imageURL = getRootDirectory(gTestPath) + "image.png";
- imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/");
- is(icon.src, imageURL, "Popup should have correct icon shown");
-
- let buttons = document.getElementById("UITourTooltipButtons");
- is(buttons.childElementCount, 4, "Popup should have four buttons");
-
- is(buttons.childNodes[1].getAttribute("label"), "Link", "Link should have correct label");
- is(buttons.childNodes[1].getAttribute("image"), "", "Link should have no image");
- ok(buttons.childNodes[1].classList.contains("button-link"), "Link should have button-link class");
-
- is(buttons.childNodes[2].getAttribute("label"), "Button 1", "First button should have correct label");
- is(buttons.childNodes[2].getAttribute("image"), "", "First button should have no image");
-
- is(buttons.childNodes[3].getAttribute("label"), "Button 2", "Second button should have correct label");
- is(buttons.childNodes[3].getAttribute("image"), imageURL, "Second button should have correct image");
-
- let promiseHidden = promisePanelElementHidden(window, popup);
- EventUtils.synthesizeMouseAtCenter(buttons.childNodes[3], {}, window);
- yield promiseHidden;
-
- ok(true, "Popup should close automatically");
-
- let returnValue = yield waitForCallbackResultPromise();
-
- is(returnValue.result, "button2", "Correct callback should have been called");
-}),
-
-add_UITour_task(function* test_info_close_button() {
- let closeButton = document.getElementById("UITourTooltipClose");
-
- yield showInfoPromise("urlbar", "Close me", "X marks the spot", null, null, "makeInfoOptions");
-
- EventUtils.synthesizeMouseAtCenter(closeButton, {}, window);
-
- let returnValue = yield waitForCallbackResultPromise();
-
- is(returnValue.result, "closeButton", "Close button callback called");
-}),
-
-add_UITour_task(function* test_info_target_callback() {
- let popup = document.getElementById("UITourTooltip");
-
- yield showInfoPromise("appMenu", "I want to know when the target is clicked", "*click*", null, null, "makeInfoOptions");
-
- yield PanelUI.show();
-
- let returnValue = yield waitForCallbackResultPromise();
-
- is(returnValue.result, "target", "target callback called");
- is(returnValue.data.target, "appMenu", "target callback was from the appMenu");
- is(returnValue.data.type, "popupshown", "target callback was from the mousedown");
-
- // Cleanup.
- yield hideInfoPromise();
-
- popup.removeAttribute("animate");
-}),
-
-add_UITour_task(function* test_getConfiguration_selectedSearchEngine() {
- yield new Promise((resolve) => {
- Services.search.init(Task.async(function*(rv) {
- ok(Components.isSuccessCode(rv), "Search service initialized");
- let engine = Services.search.defaultEngine;
- let data = yield getConfigurationPromise("selectedSearchEngine");
- is(data.searchEngineIdentifier, engine.identifier, "Correct engine identifier");
- resolve();
- }));
- });
-});
-
-add_UITour_task(function* test_setSearchTerm() {
- const TERM = "UITour Search Term";
- yield gContentAPI.setSearchTerm(TERM);
-
- let searchbar = document.getElementById("searchbar");
- // The UITour gets to the searchbar element through a promise, so the value setting
- // only happens after a tick.
- yield waitForConditionPromise(() => searchbar.value == TERM, "Correct term set");
-});
-
-add_UITour_task(function* test_clearSearchTerm() {
- yield gContentAPI.setSearchTerm("");
-
- let searchbar = document.getElementById("searchbar");
- // The UITour gets to the searchbar element through a promise, so the value setting
- // only happens after a tick.
- yield waitForConditionPromise(() => searchbar.value == "", "Search term cleared");
-});
diff --git a/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js b/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js
deleted file mode 100644
index dbdeb9589..000000000
--- a/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Test that width and height attributes don't get set by widget code on the highlight panel.
- */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var highlight = document.getElementById("UITourHighlightContainer");
-var tooltip = document.getElementById("UITourTooltip");
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_highlight_size_attributes() {
- yield gContentAPI.showHighlight("appMenu");
- yield elementVisiblePromise(highlight,
- "Highlight should be shown after showHighlight() for the appMenu");
- yield gContentAPI.showHighlight("urlbar");
- yield elementVisiblePromise(highlight, "Highlight should be moved to the urlbar");
- yield new Promise((resolve) => {
- SimpleTest.executeSoon(() => {
- is(highlight.height, "", "Highlight panel should have no explicit height set");
- is(highlight.width, "", "Highlight panel should have no explicit width set");
- resolve();
- });
- });
-});
-
-add_UITour_task(function* test_info_size_attributes() {
- yield gContentAPI.showInfo("appMenu", "test title", "test text");
- yield elementVisiblePromise(tooltip, "Tooltip should be shown after showInfo() for the appMenu");
- yield gContentAPI.showInfo("urlbar", "new title", "new text");
- yield elementVisiblePromise(tooltip, "Tooltip should be moved to the urlbar");
- yield new Promise((resolve) => {
- SimpleTest.executeSoon(() => {
- is(tooltip.height, "", "Info panel should have no explicit height set");
- is(tooltip.width, "", "Info panel should have no explicit width set");
- resolve();
- });
- });
-});
diff --git a/browser/components/uitour/test/browser_UITour_availableTargets.js b/browser/components/uitour/test/browser_UITour_availableTargets.js
deleted file mode 100644
index a6e96e31f..000000000
--- a/browser/components/uitour/test/browser_UITour_availableTargets.js
+++ /dev/null
@@ -1,114 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-var hasWebIDE = Services.prefs.getBoolPref("devtools.webide.widget.enabled");
-var hasPocket = Services.prefs.getBoolPref("extensions.pocket.enabled");
-
-requestLongerTimeout(2);
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_availableTargets() {
- let data = yield getConfigurationPromise("availableTargets");
- ok_targets(data, [
- "accountStatus",
- "addons",
- "appMenu",
- "backForward",
- "bookmarks",
- "customize",
- "help",
- "home",
- "devtools",
- ...(hasPocket ? ["pocket"] : []),
- "privateWindow",
- "quit",
- "readerMode-urlBar",
- "search",
- "searchIcon",
- "trackingProtection",
- "urlbar",
- ...(hasWebIDE ? ["webide"] : [])
- ]);
-
- ok(UITour.availableTargetsCache.has(window),
- "Targets should now be cached");
-});
-
-add_UITour_task(function* test_availableTargets_changeWidgets() {
- CustomizableUI.removeWidgetFromArea("bookmarks-menu-button");
- ok(!UITour.availableTargetsCache.has(window),
- "Targets should be evicted from cache after widget change");
- let data = yield getConfigurationPromise("availableTargets");
- ok_targets(data, [
- "accountStatus",
- "addons",
- "appMenu",
- "backForward",
- "customize",
- "help",
- "devtools",
- "home",
- ...(hasPocket ? ["pocket"] : []),
- "privateWindow",
- "quit",
- "readerMode-urlBar",
- "search",
- "searchIcon",
- "trackingProtection",
- "urlbar",
- ...(hasWebIDE ? ["webide"] : [])
- ]);
-
- ok(UITour.availableTargetsCache.has(window),
- "Targets should now be cached again");
- CustomizableUI.reset();
- ok(!UITour.availableTargetsCache.has(window),
- "Targets should not be cached after reset");
-});
-
-add_UITour_task(function* test_availableTargets_exceptionFromGetTarget() {
- // The query function for the "search" target will throw if it's not found.
- // Make sure the callback still fires with the other available targets.
- CustomizableUI.removeWidgetFromArea("search-container");
- let data = yield getConfigurationPromise("availableTargets");
- // Default minus "search" and "searchIcon"
- ok_targets(data, [
- "accountStatus",
- "addons",
- "appMenu",
- "backForward",
- "bookmarks",
- "customize",
- "help",
- "home",
- "devtools",
- ...(hasPocket ? ["pocket"] : []),
- "privateWindow",
- "quit",
- "readerMode-urlBar",
- "trackingProtection",
- "urlbar",
- ...(hasWebIDE ? ["webide"] : [])
- ]);
-
- CustomizableUI.reset();
-});
-
-function ok_targets(actualData, expectedTargets) {
- // Depending on how soon after page load this is called, the selected tab icon
- // may or may not be showing the loading throbber. Check for its presence and
- // insert it into expectedTargets if it's visible.
- let selectedTabIcon =
- document.getAnonymousElementByAttribute(gBrowser.selectedTab,
- "anonid",
- "tab-icon-image");
- if (selectedTabIcon && UITour.isElementVisible(selectedTabIcon))
- expectedTargets.push("selectedTabIcon");
-
- ok(Array.isArray(actualData.targets), "data.targets should be an array");
- is(actualData.targets.sort().toString(), expectedTargets.sort().toString(),
- "Targets should be as expected");
-}
diff --git a/browser/components/uitour/test/browser_UITour_defaultBrowser.js b/browser/components/uitour/test/browser_UITour_defaultBrowser.js
deleted file mode 100644
index 5ebf553b0..000000000
--- a/browser/components/uitour/test/browser_UITour_defaultBrowser.js
+++ /dev/null
@@ -1,61 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var setDefaultBrowserCalled = false;
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochikit/content/tests/SimpleTest/MockObjects.js", this);
-
-function MockShellService() {}
-MockShellService.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIShellService]),
- isDefaultBrowser: function(aStartupCheck, aForAllTypes) { return false; },
- setDefaultBrowser: function(aClaimAllTypes, aForAllUsers) {
- setDefaultBrowserCalled = true;
- },
- shouldCheckDefaultBrowser: false,
- canSetDesktopBackground: false,
- BACKGROUND_TILE : 1,
- BACKGROUND_STRETCH : 2,
- BACKGROUND_CENTER : 3,
- BACKGROUND_FILL : 4,
- BACKGROUND_FIT : 5,
- setDesktopBackground: function(aElement, aPosition) {},
- APPLICATION_MAIL : 0,
- APPLICATION_NEWS : 1,
- openApplication: function(aApplication) {},
- desktopBackgroundColor: 0,
- openApplicationWithURI: function(aApplication, aURI) {},
- defaultFeedReader: 0,
-};
-
-var mockShellService = new MockObjectRegisterer("@mozilla.org/browser/shell-service;1",
- MockShellService);
-
-// Temporarily disabled, see note at test_setDefaultBrowser.
-// mockShellService.register();
-
-add_task(setup_UITourTest);
-
-/* This test is disabled (bug 1180714) since the MockObjectRegisterer
- is not actually replacing the original ShellService.
-add_UITour_task(function* test_setDefaultBrowser() {
- try {
- yield gContentAPI.setConfiguration("defaultBrowser");
- ok(setDefaultBrowserCalled, "setDefaultBrowser called");
- } finally {
- mockShellService.unregister();
- }
-});
-*/
-
-add_UITour_task(function* test_isDefaultBrowser() {
- let shell = Components.classes["@mozilla.org/browser/shell-service;1"]
- .getService(Components.interfaces.nsIShellService);
- let isDefault = shell.isDefaultBrowser(false);
- let data = yield getConfigurationPromise("appinfo");
- is(isDefault, data.defaultBrowser, "gContentAPI result should match shellService.isDefaultBrowser");
-});
diff --git a/browser/components/uitour/test/browser_UITour_detach_tab.js b/browser/components/uitour/test/browser_UITour_detach_tab.js
deleted file mode 100644
index b8edf6dc4..000000000
--- a/browser/components/uitour/test/browser_UITour_detach_tab.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Detaching a tab to a new window shouldn't break the menu panel.
- */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var gContentDoc;
-
-function test() {
- registerCleanupFunction(function() {
- gContentDoc = null;
- });
- UITourTest();
-}
-
-/**
- * When tab is changed we're tearing the tour down. So the UITour client has to always be aware of this
- * fact and therefore listens to visibilitychange events.
- * In particular this scenario happens for detaching the tab (ie. moving it to a new window).
- */
-var tests = [
- taskify(function* test_move_tab_to_new_window() {
- const myDocIdentifier = "Hello, I'm a unique expando to identify this document.";
-
- let highlight = document.getElementById("UITourHighlight");
- let windowDestroyedDeferred = Promise.defer();
- let onDOMWindowDestroyed = (aWindow) => {
- if (gContentWindow && aWindow == gContentWindow) {
- Services.obs.removeObserver(onDOMWindowDestroyed, "dom-window-destroyed", false);
- windowDestroyedDeferred.resolve();
- }
- };
-
- let browserStartupDeferred = Promise.defer();
- Services.obs.addObserver(function onBrowserDelayedStartup(aWindow) {
- Services.obs.removeObserver(onBrowserDelayedStartup, "browser-delayed-startup-finished");
- browserStartupDeferred.resolve(aWindow);
- }, "browser-delayed-startup-finished", false);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, myDocIdentifier, myDocIdentifier => {
- let onVisibilityChange = () => {
- if (!content.document.hidden) {
- let win = Cu.waiveXrays(content);
- win.Mozilla.UITour.showHighlight("appMenu");
- }
- };
- content.document.addEventListener("visibilitychange", onVisibilityChange);
- content.document.myExpando = myDocIdentifier;
- });
- gContentAPI.showHighlight("appMenu");
-
- yield elementVisiblePromise(highlight);
-
- gContentWindow = gBrowser.replaceTabWithWindow(gBrowser.selectedTab);
- yield browserStartupDeferred.promise;
-
- // This highlight should be shown thanks to the visibilitychange listener.
- let newWindowHighlight = gContentWindow.document.getElementById("UITourHighlight");
- yield elementVisiblePromise(newWindowHighlight);
-
- let selectedTab = gContentWindow.gBrowser.selectedTab;
- yield ContentTask.spawn(selectedTab.linkedBrowser, myDocIdentifier, myDocIdentifier => {
- is(content.document.myExpando, myDocIdentifier, "Document should be selected in new window");
- });
- ok(UITour.tourBrowsersByWindow && UITour.tourBrowsersByWindow.has(gContentWindow), "Window should be known");
- ok(UITour.tourBrowsersByWindow.get(gContentWindow).has(selectedTab.linkedBrowser), "Selected browser should be known");
-
- // Need this because gContentAPI in e10s land will try to use gTestTab to
- // spawn a content task, which doesn't work if the tab is dead, for obvious
- // reasons.
- gTestTab = gContentWindow.gBrowser.selectedTab;
-
- let shownPromise = promisePanelShown(gContentWindow);
- gContentAPI.showMenu("appMenu");
- yield shownPromise;
-
- isnot(gContentWindow.PanelUI.panel.state, "closed", "Panel should be open");
- ok(gContentWindow.PanelUI.contents.children.length > 0, "Panel contents should have children");
- gContentAPI.hideHighlight();
- gContentAPI.hideMenu("appMenu");
- gTestTab = null;
-
- Services.obs.addObserver(onDOMWindowDestroyed, "dom-window-destroyed", false);
- gContentWindow.close();
-
- yield windowDestroyedDeferred.promise;
- }),
-];
diff --git a/browser/components/uitour/test/browser_UITour_forceReaderMode.js b/browser/components/uitour/test/browser_UITour_forceReaderMode.js
deleted file mode 100644
index 5b5e883c3..000000000
--- a/browser/components/uitour/test/browser_UITour_forceReaderMode.js
+++ /dev/null
@@ -1,17 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function*() {
- ok(!gBrowser.selectedBrowser.isArticle, "Should not be an article when we start");
- ok(document.getElementById("reader-mode-button").hidden, "Button should be hidden.");
- yield gContentAPI.forceShowReaderIcon();
- yield waitForConditionPromise(() => gBrowser.selectedBrowser.isArticle);
- ok(gBrowser.selectedBrowser.isArticle, "Should suddenly be an article.");
- ok(!document.getElementById("reader-mode-button").hidden, "Button should now be visible.");
-});
-
diff --git a/browser/components/uitour/test/browser_UITour_heartbeat.js b/browser/components/uitour/test/browser_UITour_heartbeat.js
deleted file mode 100644
index 61be1d44b..000000000
--- a/browser/components/uitour/test/browser_UITour_heartbeat.js
+++ /dev/null
@@ -1,755 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-function getHeartbeatNotification(aId, aChromeWindow = window) {
- let notificationBox = aChromeWindow.document.getElementById("high-priority-global-notificationbox");
- // UITour.jsm prefixes the notification box ID with "heartbeat-" to prevent collisions.
- return notificationBox.getNotificationWithValue("heartbeat-" + aId);
-}
-
-/**
- * Simulate a click on a rating element in the Heartbeat notification.
- *
- * @param aId
- * The id of the notification box.
- * @param aScore
- * The score related to the rating element we want to click on.
- */
-function simulateVote(aId, aScore) {
- let notification = getHeartbeatNotification(aId);
-
- let ratingContainer = notification.childNodes[0];
- ok(ratingContainer, "The notification has a valid rating container.");
-
- let ratingElement = ratingContainer.getElementsByAttribute("data-score", aScore);
- ok(ratingElement[0], "The rating container contains the requested rating element.");
-
- ratingElement[0].click();
-}
-
-/**
- * Simulate a click on the learn-more link.
- *
- * @param aId
- * The id of the notification box.
- */
-function clickLearnMore(aId) {
- let notification = getHeartbeatNotification(aId);
-
- let learnMoreLabel = notification.childNodes[2];
- ok(learnMoreLabel, "The notification has a valid learn more label.");
-
- learnMoreLabel.click();
-}
-
-/**
- * Remove the notification box.
- *
- * @param aId
- * The id of the notification box to remove.
- * @param [aChromeWindow=window]
- * The chrome window the notification box is in.
- */
-function cleanUpNotification(aId, aChromeWindow = window) {
- let notification = getHeartbeatNotification(aId, aChromeWindow);
- notification.close();
-}
-
-/**
- * Check telemetry payload for proper format and expected content.
- *
- * @param aPayload
- * The Telemetry payload to verify
- * @param aFlowId
- * Expected value of the flowId field.
- * @param aExpectedFields
- * Array of expected fields. No other fields are allowed.
- */
-function checkTelemetry(aPayload, aFlowId, aExpectedFields) {
- // Basic payload format
- is(aPayload.version, 1, "Telemetry ping must have heartbeat version=1");
- is(aPayload.flowId, aFlowId, "Flow ID in the Telemetry ping must match");
-
- // Check for superfluous fields
- let extraKeys = new Set(Object.keys(aPayload));
- extraKeys.delete("version");
- extraKeys.delete("flowId");
-
- // Check for expected fields
- for (let field of aExpectedFields) {
- ok(field in aPayload, "The payload should have the field '" + field + "'");
- if (field.endsWith("TS")) {
- let ts = aPayload[field];
- ok(Number.isInteger(ts) && ts > 0, "Timestamp '" + field + "' must be a natural number");
- }
- extraKeys.delete(field);
- }
-
- is(extraKeys.size, 0, "No unexpected fields in the Telemetry payload");
-}
-
-/**
- * Waits for an UITour notification dispatched through |UITour.notify|. This should be
- * done with |gContentAPI.observe|. Unfortunately, in e10s, |gContentAPI.observe| doesn't
- * allow for multiple calls to the same callback, allowing to catch just the first
- * notification.
- *
- * @param aEventName
- * The notification name to wait for.
- * @return {Promise} Resolved with the data that comes with the event.
- */
-function promiseWaitHeartbeatNotification(aEventName) {
- return ContentTask.spawn(gTestTab.linkedBrowser, { aEventName },
- function({ aEventName }) {
- return new Promise(resolve => {
- addEventListener("mozUITourNotification", function listener(event) {
- if (event.detail.event !== aEventName) {
- return;
- }
- removeEventListener("mozUITourNotification", listener, false);
- resolve(event.detail.params);
- }, false);
- });
- });
-}
-
-/**
- * Waits for UITour notifications dispatched through |UITour.notify|. This works like
- * |promiseWaitHeartbeatNotification|, but waits for all the passed notifications to
- * be received before resolving. If it receives an unaccounted notification, it rejects.
- *
- * @param events
- * An array of expected notification names to wait for.
- * @return {Promise} Resolved with the data that comes with the event. Rejects with the
- * name of an undesired notification if received.
- */
-function promiseWaitExpectedNotifications(events) {
- return ContentTask.spawn(gTestTab.linkedBrowser, { events },
- function({ events }) {
- let stillToReceive = events;
- return new Promise((res, rej) => {
- addEventListener("mozUITourNotification", function listener(event) {
- if (stillToReceive.includes(event.detail.event)) {
- // Filter out the received event.
- stillToReceive = stillToReceive.filter(x => x !== event.detail.event);
- } else {
- removeEventListener("mozUITourNotification", listener, false);
- rej(event.detail.event);
- }
- // We still need to catch some notifications. Don't do anything.
- if (stillToReceive.length > 0) {
- return;
- }
- // We don't need to listen for other notifications. Resolve the promise.
- removeEventListener("mozUITourNotification", listener, false);
- res();
- }, false);
- });
- });
-}
-
-function validateTimestamp(eventName, timestamp) {
- info("'" + eventName + "' notification received (timestamp " + timestamp.toString() + ").");
- ok(Number.isFinite(timestamp), "Timestamp must be a number.");
-}
-
-add_task(function* test_setup() {
- yield setup_UITourTest();
- requestLongerTimeout(2);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.uitour.surveyDuration");
- });
-});
-
-/**
- * Check that the "stars" heartbeat UI correctly shows and closes.
- */
-add_UITour_task(function* test_heartbeat_stars_show() {
- let flowId = "ui-ratefirefox-" + Math.random();
- let engagementURL = "http://example.com";
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(
- ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL);
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Close the heartbeat notification.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
- cleanUpNotification(flowId);
-
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
-
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received");
- checkTelemetry(data, flowId, ["offeredTS", "closedTS"]);
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Check that the heartbeat UI correctly takes optional icon URL.
- */
-add_UITour_task(function* test_heartbeat_take_optional_icon_URL() {
- let flowId = "ui-ratefirefox-" + Math.random();
- let engagementURL = "http://example.com";
- let iconURL = "chrome://branding/content/icon48.png";
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(
- ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, {
- iconURL: iconURL
- });
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Check the icon URL
- let notification = getHeartbeatNotification(flowId);
- is(notification.image, iconURL, "The optional icon URL is not taken correctly");
-
- // Close the heartbeat notification.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
- cleanUpNotification(flowId);
-
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
-
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received");
- checkTelemetry(data, flowId, ["offeredTS", "closedTS"]);
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the heartbeat UI correctly works with null engagement URL.
- */
-add_UITour_task(function* test_heartbeat_null_engagementURL() {
- let flowId = "ui-ratefirefox-" + Math.random();
- let originalTabCount = gBrowser.tabs.length;
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null);
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // The UI was just shown. We can simulate a click on a rating element (i.e., "star").
- simulateVote(flowId, 2);
- data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
-
- // Validate the closing timestamp.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
- is(data.score, 2, "Checking Telemetry payload.score");
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the heartbeat UI correctly works with an invalid, but non null, engagement URL.
- */
-add_UITour_task(function* test_heartbeat_invalid_engagement_URL() {
- let flowId = "ui-ratefirefox-" + Math.random();
- let originalTabCount = gBrowser.tabs.length;
- let invalidEngagementURL = "invalidEngagement";
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, invalidEngagementURL);
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // The UI was just shown. We can simulate a click on a rating element (i.e., "star").
- simulateVote(flowId, 2);
- data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
-
- // Validate the closing timestamp.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
- is(data.score, 2, "Checking Telemetry payload.score");
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the score is correctly reported.
- */
-add_UITour_task(function* test_heartbeat_stars_vote() {
- const expectedScore = 4;
- let originalTabCount = gBrowser.tabs.length;
- let flowId = "ui-ratefirefox-" + Math.random();
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null);
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // The UI was just shown. We can simulate a click on a rating element (i.e., "star").
- simulateVote(flowId, expectedScore);
- data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
- is(data.score, expectedScore, "Should report a score of " + expectedScore);
-
- // Validate the closing timestamp and vote.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
- is(data.score, expectedScore, "Checking Telemetry payload.score");
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the engagement page is correctly opened when voting.
- */
-add_UITour_task(function* test_heartbeat_engagement_tab() {
- let engagementURL = "http://example.com";
- let flowId = "ui-ratefirefox-" + Math.random();
- let originalTabCount = gBrowser.tabs.length;
- const expectedTabCount = originalTabCount + 1;
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL);
-
- // Validate the returned timestamp.
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // The UI was just shown. We can simulate a click on a rating element (i.e., "star").
- simulateVote(flowId, 1);
- data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
-
- // Validate the closing timestamp, vote and make sure the engagement page was opened.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab.");
- gBrowser.removeCurrentTab();
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
- is(data.score, 1, "Checking Telemetry payload.score");
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the engagement button opens the engagement URL.
- */
-add_UITour_task(function* test_heartbeat_engagement_button() {
- let engagementURL = "http://example.com";
- let flowId = "ui-engagewithfirefox-" + Math.random();
- let originalTabCount = gBrowser.tabs.length;
- const expectedTabCount = originalTabCount + 1;
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:Engaged", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, null, null, {
- engagementButtonLabel: "Engage Me",
- });
-
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the Engaged, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let engagedPromise = promiseWaitHeartbeatNotification("Heartbeat:Engaged");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // Simulate user engagement.
- let notification = getHeartbeatNotification(flowId);
- is(notification.querySelectorAll(".star-x").length, 0, "No stars should be present");
- // The UI was just shown. We can simulate a click on the engagement button.
- let engagementButton = notification.querySelector(".notification-button");
- is(engagementButton.label, "Engage Me", "Check engagement button text");
- engagementButton.doCommand();
-
- data = yield engagedPromise;
- validateTimestamp('Heartbeat:Engaged', data.timestamp);
-
- // Validate the closing timestamp, vote and make sure the engagement page was opened.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab.");
- gBrowser.removeCurrentTab();
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "engagedTS", "closedTS"]);
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Test that the learn more link is displayed and that the page is correctly opened when
- * clicking on it.
- */
-add_UITour_task(function* test_heartbeat_learnmore() {
- let dummyURL = "http://example.com";
- let flowId = "ui-ratefirefox-" + Math.random();
- let originalTabCount = gBrowser.tabs.length;
- const expectedTabCount = originalTabCount + 1;
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:LearnMore", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, dummyURL,
- "What is this?", dummyURL);
-
- let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
-
- // Wait an the LearnMore, Closed and Telemetry Sent events. They are fired together, so
- // wait for them here.
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let learnMorePromise = promiseWaitHeartbeatNotification("Heartbeat:LearnMore");
- let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- // The UI was just shown. Simulate a click on the learn more link.
- clickLearnMore(flowId);
-
- data = yield learnMorePromise;
- validateTimestamp('Heartbeat:LearnMore', data.timestamp);
- cleanUpNotification(flowId);
-
- // The notification was closed.
- data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
- is(gBrowser.tabs.length, expectedTabCount, "Learn more URL should open in a new tab.");
- gBrowser.removeCurrentTab();
-
- // Validate the data we send out.
- data = yield pingSentPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "learnMoreTS", "closedTS"]);
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-add_UITour_task(function* test_invalidEngagementButtonLabel() {
- let engagementURL = "http://example.com";
- let flowId = "invalidEngagementButtonLabel-" + Math.random();
-
- let eventPromise = promisePageEvent();
-
- gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL,
- null, null, {
- engagementButtonLabel: 42,
- });
-
- yield eventPromise;
- ok(!isTourBrowser(gBrowser.selectedBrowser),
- "Invalid engagementButtonLabel should prevent init");
-
-})
-
-add_UITour_task(function* test_privateWindowsOnly_noneOpen() {
- let engagementURL = "http://example.com";
- let flowId = "privateWindowsOnly_noneOpen-" + Math.random();
-
- let eventPromise = promisePageEvent();
-
- gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL,
- null, null, {
- engagementButtonLabel: "Yes!",
- privateWindowsOnly: true,
- });
-
- yield eventPromise;
- ok(!isTourBrowser(gBrowser.selectedBrowser),
- "If there are no private windows opened, tour init should be prevented");
-})
-
-add_UITour_task(function* test_privateWindowsOnly_notMostRecent() {
- let engagementURL = "http://example.com";
- let flowId = "notMostRecent-" + Math.random();
-
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
- let mostRecentWin = yield BrowserTestUtils.openNewBrowserWindow();
-
- let eventPromise = promisePageEvent();
-
- gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL,
- null, null, {
- engagementButtonLabel: "Yes!",
- privateWindowsOnly: true,
- });
-
- yield eventPromise;
- is(getHeartbeatNotification(flowId, window), null,
- "Heartbeat shouldn't appear in the default window");
- is(!!getHeartbeatNotification(flowId, privateWin), true,
- "Heartbeat should appear in the most recent private window");
- is(getHeartbeatNotification(flowId, mostRecentWin), null,
- "Heartbeat shouldn't appear in the most recent non-private window");
-
- yield BrowserTestUtils.closeWindow(mostRecentWin);
- yield BrowserTestUtils.closeWindow(privateWin);
-})
-
-add_UITour_task(function* test_privateWindowsOnly() {
- let engagementURL = "http://example.com";
- let learnMoreURL = "http://example.org/learnmore/";
- let flowId = "ui-privateWindowsOnly-" + Math.random();
-
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true });
-
- yield new Promise((resolve) => {
- gContentAPI.observe(function(aEventName, aData) {
- info(aEventName + " notification received: " + JSON.stringify(aData, null, 2));
- ok(false, "No heartbeat notifications should arrive for privateWindowsOnly");
- }, resolve);
- });
-
- gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL,
- "Learn More", learnMoreURL, {
- engagementButtonLabel: "Yes!",
- privateWindowsOnly: true,
- });
-
- yield promisePageEvent();
-
- ok(isTourBrowser(gBrowser.selectedBrowser), "UITour should have been init for the browser");
-
- let notification = getHeartbeatNotification(flowId, privateWin);
-
- is(notification.querySelectorAll(".star-x").length, 0, "No stars should be present");
-
- info("Test the learn more link.");
- let learnMoreLink = notification.querySelector(".text-link");
- is(learnMoreLink.value, "Learn More", "Check learn more label");
- let learnMoreTabPromise = BrowserTestUtils.waitForNewTab(privateWin.gBrowser, null);
- learnMoreLink.click();
- let learnMoreTab = yield learnMoreTabPromise;
- is(learnMoreTab.linkedBrowser.currentURI.host, "example.org", "Check learn more site opened");
- ok(PrivateBrowsingUtils.isBrowserPrivate(learnMoreTab.linkedBrowser), "Ensure the learn more tab is private");
- yield BrowserTestUtils.removeTab(learnMoreTab);
-
- info("Test the engagement button's new tab.");
- let engagementButton = notification.querySelector(".notification-button");
- is(engagementButton.label, "Yes!", "Check engagement button text");
- let engagementTabPromise = BrowserTestUtils.waitForNewTab(privateWin.gBrowser, null);
- engagementButton.doCommand();
- let engagementTab = yield engagementTabPromise;
- is(engagementTab.linkedBrowser.currentURI.host, "example.com", "Check enagement site opened");
- ok(PrivateBrowsingUtils.isBrowserPrivate(engagementTab.linkedBrowser), "Ensure the engagement tab is private");
- yield BrowserTestUtils.removeTab(engagementTab);
-
- yield BrowserTestUtils.closeWindow(privateWin);
-})
-
-/**
- * Test that the survey closes itself after a while and submits Telemetry
- */
-add_UITour_task(function* test_telemetry_surveyExpired() {
- let flowId = "survey-expired-" + Math.random();
- let engagementURL = "http://example.com";
- let surveyDuration = 1; // 1 second (pref is in seconds)
- Services.prefs.setIntPref("browser.uitour.surveyDuration", surveyDuration);
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered",
- "Heartbeat:NotificationClosed", "Heartbeat:SurveyExpired", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL);
-
- let expiredPromise = promiseWaitHeartbeatNotification("Heartbeat:SurveyExpired");
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let pingPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
-
- yield Promise.all([shownPromise, expiredPromise, closedPromise]);
- // Validate the ping data.
- let data = yield pingPromise;
- checkTelemetry(data, flowId, ["offeredTS", "expiredTS", "closedTS"]);
-
- Services.prefs.clearUserPref("browser.uitour.surveyDuration");
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
-
-/**
- * Check that certain whitelisted experiment parameters get reflected in the
- * Telemetry ping
- */
-add_UITour_task(function* test_telemetry_params() {
- let flowId = "telemetry-params-" + Math.random();
- let engagementURL = "http://example.com";
- let extraParams = {
- "surveyId": "foo",
- "surveyVersion": 1.5,
- "testing": true,
- "notWhitelisted": 123,
- };
- let expectedFields = ["surveyId", "surveyVersion", "testing"];
-
- // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener|
- // in UITour-lib.js, otherwise no message will get propagated.
- gContentAPI.observe(() => {});
-
- let receivedExpectedPromise = promiseWaitExpectedNotifications(
- ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]);
-
- // Show the Heartbeat notification and wait for it to be displayed.
- let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
- gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!",
- flowId, engagementURL, null, null, extraParams);
- yield shownPromise;
-
- let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
- let pingPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
- cleanUpNotification(flowId);
-
- // The notification was closed.
- let data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
-
- // Validate the data we send out.
- data = yield pingPromise;
- info("'Heartbeat:TelemetrySent' notification received.");
- checkTelemetry(data, flowId, ["offeredTS", "closedTS"].concat(expectedFields));
- for (let param of expectedFields) {
- is(data[param], extraParams[param],
- "Whitelisted experiment configs should be copied into Telemetry pings");
- }
-
- // This rejects whenever an unexpected notification is received.
- yield receivedExpectedPromise;
-})
diff --git a/browser/components/uitour/test/browser_UITour_modalDialog.js b/browser/components/uitour/test/browser_UITour_modalDialog.js
deleted file mode 100644
index 1890739c4..000000000
--- a/browser/components/uitour/test/browser_UITour_modalDialog.js
+++ /dev/null
@@ -1,104 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var handleDialog;
-
-// Modified from toolkit/components/passwordmgr/test/prompt_common.js
-var didDialog;
-
-var timer; // keep in outer scope so it's not GC'd before firing
-function startCallbackTimer() {
- didDialog = false;
-
- // Delay before the callback twiddles the prompt.
- const dialogDelay = 10;
-
- // Use a timer to invoke a callback to twiddle the authentication dialog
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.init(observer, dialogDelay, Ci.nsITimer.TYPE_ONE_SHOT);
-}
-
-
-var observer = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
- const interfaces = [Ci.nsIObserver,
- Ci.nsISupports, Ci.nsISupportsWeakReference];
-
- if (!interfaces.some( function(v) { return iid.equals(v) } ))
- throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- observe : function (subject, topic, data) {
- var doc = getDialogDoc();
- if (doc)
- handleDialog(doc);
- else
- startCallbackTimer(); // try again in a bit
- }
-});
-
-function getDialogDoc() {
- // Find the <browser> which contains notifyWindow, by looking
- // through all the open windows and all the <browsers> in each.
- var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
- getService(Ci.nsIWindowMediator);
- // var enumerator = wm.getEnumerator("navigator:browser");
- var enumerator = wm.getXULWindowEnumerator(null);
-
- while (enumerator.hasMoreElements()) {
- var win = enumerator.getNext();
- var windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell;
-
- var containedDocShells = windowDocShell.getDocShellEnumerator(
- Ci.nsIDocShellTreeItem.typeChrome,
- Ci.nsIDocShell.ENUMERATE_FORWARDS);
- while (containedDocShells.hasMoreElements()) {
- // Get the corresponding document for this docshell
- var childDocShell = containedDocShells.getNext();
- // We don't want it if it's not done loading.
- if (childDocShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE)
- continue;
- var childDoc = childDocShell.QueryInterface(Ci.nsIDocShell)
- .contentViewer
- .DOMDocument;
-
- // ok(true, "Got window: " + childDoc.location.href);
- if (childDoc.location.href == "chrome://global/content/commonDialog.xul")
- return childDoc;
- }
- }
-
- return null;
-}
-
-function test() {
- UITourTest();
-}
-
-
-var tests = [
- taskify(function* test_modal_dialog_while_opening_tooltip() {
- let panelShown;
- let popup;
-
- handleDialog = (doc) => {
- popup = document.getElementById("UITourTooltip");
- gContentAPI.showInfo("appMenu", "test title", "test text");
- doc.defaultView.setTimeout(function() {
- is(popup.state, "closed", "Popup shouldn't be shown while dialog is up");
- panelShown = promisePanelElementShown(window, popup);
- let dialog = doc.getElementById("commonDialog");
- dialog.acceptDialog();
- }, 1000);
- };
- startCallbackTimer();
- executeSoon(() => alert("test"));
- yield waitForConditionPromise(() => panelShown, "Timed out waiting for panel promise to be assigned", 100);
- yield panelShown;
-
- yield hideInfoPromise();
- })
-];
diff --git a/browser/components/uitour/test/browser_UITour_observe.js b/browser/components/uitour/test/browser_UITour_observe.js
deleted file mode 100644
index b4b435659..000000000
--- a/browser/components/uitour/test/browser_UITour_observe.js
+++ /dev/null
@@ -1,85 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-function test() {
- requestLongerTimeout(2);
- UITourTest();
-}
-
-var tests = [
- function test_no_params(done) {
- function listener(event, params) {
- is(event, "test-event-1", "Correct event name");
- is(params, null, "No param object");
- gContentAPI.observe(null);
- done();
- }
-
- gContentAPI.observe(listener, () => {
- UITour.notify("test-event-1");
- });
- },
- function test_param_string(done) {
- function listener(event, params) {
- is(event, "test-event-2", "Correct event name");
- is(params, "a param", "Correct param string");
- gContentAPI.observe(null);
- done();
- }
-
- gContentAPI.observe(listener, () => {
- UITour.notify("test-event-2", "a param");
- });
- },
- function test_param_object(done) {
- function listener(event, params) {
- is(event, "test-event-3", "Correct event name");
- is(JSON.stringify(params), JSON.stringify({key: "something"}), "Correct param object");
- gContentAPI.observe(null);
- done();
- }
-
- gContentAPI.observe(listener, () => {
- UITour.notify("test-event-3", {key: "something"});
- });
- },
- function test_background_tab(done) {
- function listener(event, params) {
- is(event, "test-event-background-1", "Correct event name");
- is(params, null, "No param object");
- gContentAPI.observe(null);
- gBrowser.removeCurrentTab();
- done();
- }
-
- gContentAPI.observe(listener, () => {
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- isnot(gBrowser.selectedTab, gTestTab, "Make sure the selected tab changed");
-
- UITour.notify("test-event-background-1");
- });
- },
- // Make sure the tab isn't torn down when switching back to the tour one.
- function test_background_then_foreground_tab(done) {
- let blankTab = null;
- function listener(event, params) {
- is(event, "test-event-4", "Correct event name");
- is(params, null, "No param object");
- gContentAPI.observe(null);
- gBrowser.removeTab(blankTab);
- done();
- }
-
- gContentAPI.observe(listener, () => {
- blankTab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
- isnot(gBrowser.selectedTab, gTestTab, "Make sure the selected tab changed");
- gBrowser.selectedTab = gTestTab;
- is(gBrowser.selectedTab, gTestTab, "Switch back to the test tab");
-
- UITour.notify("test-event-4");
- });
- },
-];
diff --git a/browser/components/uitour/test/browser_UITour_panel_close_annotation.js b/browser/components/uitour/test/browser_UITour_panel_close_annotation.js
deleted file mode 100644
index cff446573..000000000
--- a/browser/components/uitour/test/browser_UITour_panel_close_annotation.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that annotations disappear when their target is hidden.
- */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var highlight = document.getElementById("UITourHighlight");
-var tooltip = document.getElementById("UITourTooltip");
-
-function test() {
- registerCleanupFunction(() => {
- // Close the find bar in case it's open in the remaining tab
- gBrowser.getFindBar(gBrowser.selectedTab).close();
- });
- UITourTest();
-}
-
-var tests = [
- function test_highlight_move_outside_panel(done) {
- gContentAPI.showInfo("urlbar", "test title", "test text");
- gContentAPI.showHighlight("customize");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Move the highlight outside which should close the app menu.
- gContentAPI.showHighlight("appMenu");
- waitForPopupAtAnchor(highlight.parentElement, document.getElementById("PanelUI-button"), () => {
- isnot(PanelUI.panel.state, "open",
- "Panel should have closed after the highlight moved elsewhere.");
- ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open");
- done();
- }, "Highlight should move to the appMenu button and still be visible");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_highlight_panel_hideMenu(done) {
- gContentAPI.showHighlight("customize");
- gContentAPI.showInfo("search", "test title", "test text");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Close the app menu and make sure the highlight also disappeared.
- gContentAPI.hideMenu("appMenu");
- waitForElementToBeHidden(highlight, function checkPanelIsClosed() {
- isnot(PanelUI.panel.state, "open",
- "Panel still should have closed");
- ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open");
- done();
- }, "Highlight should have disappeared when panel closed");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_highlight_panel_click_find(done) {
- gContentAPI.showHighlight("help");
- gContentAPI.showInfo("searchIcon", "test title", "test text");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Click the find button which should close the panel.
- let findButton = document.getElementById("find-button");
- EventUtils.synthesizeMouseAtCenter(findButton, {});
- waitForElementToBeHidden(highlight, function checkPanelIsClosed() {
- isnot(PanelUI.panel.state, "open",
- "Panel should have closed when the find bar opened");
- ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open");
- done();
- }, "Highlight should have disappeared when panel closed");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_highlight_info_panel_click_find(done) {
- gContentAPI.showHighlight("help");
- gContentAPI.showInfo("customize", "customize me!", "awesome!");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Click the find button which should close the panel.
- let findButton = document.getElementById("find-button");
- EventUtils.synthesizeMouseAtCenter(findButton, {});
- waitForElementToBeHidden(highlight, function checkPanelIsClosed() {
- isnot(PanelUI.panel.state, "open",
- "Panel should have closed when the find bar opened");
- waitForElementToBeHidden(tooltip, function checkTooltipIsClosed() {
- isnot(tooltip.state, "open", "The info panel should have closed too");
- done();
- }, "Tooltip should hide with the menu");
- }, "Highlight should have disappeared when panel closed");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_highlight_panel_open_subview(done) {
- gContentAPI.showHighlight("customize");
- gContentAPI.showInfo("backForward", "test title", "test text");
- waitForElementToBeVisible(highlight, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Click the help button which should open the subview in the panel menu.
- let helpButton = document.getElementById("PanelUI-help");
- EventUtils.synthesizeMouseAtCenter(helpButton, {});
- waitForElementToBeHidden(highlight, function highlightHidden() {
- is(PanelUI.panel.state, "open",
- "Panel should have stayed open when the subview opened");
- ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open");
- PanelUI.hide();
- done();
- }, "Highlight should have disappeared when the subview opened");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_info_panel_open_subview(done) {
- gContentAPI.showHighlight("urlbar");
- gContentAPI.showInfo("customize", "customize me!", "Open a subview");
- waitForElementToBeVisible(tooltip, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Click the help button which should open the subview in the panel menu.
- let helpButton = document.getElementById("PanelUI-help");
- EventUtils.synthesizeMouseAtCenter(helpButton, {});
- waitForElementToBeHidden(tooltip, function tooltipHidden() {
- is(PanelUI.panel.state, "open",
- "Panel should have stayed open when the subview opened");
- is(highlight.parentElement.state, "open", "The highlight should have remained open");
- PanelUI.hide();
- done();
- }, "Tooltip should have disappeared when the subview opened");
- }, "Highlight should be shown after showHighlight() for fixed panel items");
- },
-
- function test_info_move_outside_panel(done) {
- gContentAPI.showInfo("addons", "test title", "test text");
- gContentAPI.showHighlight("urlbar");
- let addonsButton = document.getElementById("add-ons-button");
- waitForPopupAtAnchor(tooltip, addonsButton, function checkPanelIsOpen() {
- isnot(PanelUI.panel.state, "closed", "Panel should have opened");
-
- // Move the info panel outside which should close the app menu.
- gContentAPI.showInfo("appMenu", "Cool menu button", "It's three lines");
- waitForPopupAtAnchor(tooltip, document.getElementById("PanelUI-button"), () => {
- isnot(PanelUI.panel.state, "open",
- "Menu should have closed after the highlight moved elsewhere.");
- is(highlight.parentElement.state, "open", "The highlight should have remained visible");
- done();
- }, "Tooltip should move to the appMenu button and still be visible");
- }, "Tooltip should be shown after showInfo() for a panel item");
- },
-
-];
diff --git a/browser/components/uitour/test/browser_UITour_pocket.js b/browser/components/uitour/test/browser_UITour_pocket.js
deleted file mode 100644
index 29548a475..000000000
--- a/browser/components/uitour/test/browser_UITour_pocket.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-var button;
-
-function test() {
- UITourTest();
-}
-
-var tests = [
- taskify(function* test_menu_show_navbar() {
- is(button.open, false, "Menu should initially be closed");
- gContentAPI.showMenu("pocket");
-
- // The panel gets created dynamically.
- let widgetPanel = null;
- yield waitForConditionPromise(() => {
- widgetPanel = document.getElementById("customizationui-widget-panel");
- return widgetPanel && widgetPanel.state == "open";
- }, "Menu should be visible after showMenu()");
-
- ok(button.open, "Button should know its view is open");
- ok(!widgetPanel.hasAttribute("noautohide"), "@noautohide shouldn't be on the pocket panel");
- ok(button.hasAttribute("open"), "Pocket button should know that the menu is open");
-
- widgetPanel.hidePopup();
- checkPanelIsHidden(widgetPanel);
- }),
- taskify(function* test_menu_show_appMenu() {
- CustomizableUI.addWidgetToArea("pocket-button", CustomizableUI.AREA_PANEL);
-
- is(PanelUI.multiView.hasAttribute("panelopen"), false, "Multiview should initially be closed");
- gContentAPI.showMenu("pocket");
-
- yield waitForConditionPromise(() => {
- return PanelUI.panel.state == "open";
- }, "Menu should be visible after showMenu()");
-
- ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide shouldn't be on the pocket panel");
- ok(PanelUI.multiView.showingSubView, "Subview should be open");
- ok(PanelUI.multiView.hasAttribute("panelopen"), "Multiview should know it's open");
-
- PanelUI.showMainView();
- PanelUI.panel.hidePopup();
- checkPanelIsHidden(PanelUI.panel);
- }),
-];
-
-// End tests
-
-function checkPanelIsHidden(aPanel) {
- if (aPanel.parentElement) {
- is_hidden(aPanel);
- } else {
- ok(!aPanel.parentElement, "Widget panel should have been removed");
- }
- is(button.hasAttribute("open"), false, "Pocket button should know that the panel is closed");
-}
-
-if (Services.prefs.getBoolPref("extensions.pocket.enabled")) {
- let placement = CustomizableUI.getPlacementOfWidget("pocket-button");
-
- // Add the button to the nav-bar by default.
- if (!placement || placement.area != CustomizableUI.AREA_NAVBAR) {
- CustomizableUI.addWidgetToArea("pocket-button", CustomizableUI.AREA_NAVBAR);
- }
- registerCleanupFunction(() => {
- CustomizableUI.reset();
- });
-
- let widgetGroupWrapper = CustomizableUI.getWidget("pocket-button");
- button = widgetGroupWrapper.forWindow(window).node;
- ok(button, "Got button node");
-} else {
- todo(false, "Pocket is disabled so skip its UITour tests");
- tests = [];
-}
diff --git a/browser/components/uitour/test/browser_UITour_registerPageID.js b/browser/components/uitour/test/browser_UITour_registerPageID.js
deleted file mode 100644
index 369abb1ed..000000000
--- a/browser/components/uitour/test/browser_UITour_registerPageID.js
+++ /dev/null
@@ -1,108 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-Components.utils.import("resource://gre/modules/UITelemetry.jsm");
-Components.utils.import("resource:///modules/BrowserUITelemetry.jsm");
-
-add_task(function* setup_telemetry() {
- UITelemetry._enabled = true;
-
- registerCleanupFunction(function() {
- Services.prefs.clearUserPref("browser.uitour.seenPageIDs");
- resetSeenPageIDsLazyGetter();
- UITelemetry._enabled = undefined;
- BrowserUITelemetry.setBucket(null);
- delete window.UITelemetry;
- delete window.BrowserUITelemetry;
- });
-});
-
-add_task(setup_UITourTest);
-
-function resetSeenPageIDsLazyGetter() {
- delete UITour.seenPageIDs;
- // This should be kept in sync with how UITour.init() sets this.
- Object.defineProperty(UITour, "seenPageIDs", {
- get: UITour.restoreSeenPageIDs.bind(UITour),
- configurable: true,
- });
-}
-
-function checkExpectedSeenPageIDs(expected) {
- is(UITour.seenPageIDs.size, expected.length, "Should be " + expected.length + " total seen page IDs");
-
- for (let id of expected)
- ok(UITour.seenPageIDs.has(id), "Should have seen '" + id + "' page ID");
-
- let prefData = Services.prefs.getCharPref("browser.uitour.seenPageIDs");
- prefData = new Map(JSON.parse(prefData));
-
- is(prefData.size, expected.length, "Should be " + expected.length + " total seen page IDs persisted");
-
- for (let id of expected)
- ok(prefData.has(id), "Should have seen '" + id + "' page ID persisted");
-}
-
-
-add_UITour_task(function test_seenPageIDs_restore() {
- info("Setting up seenPageIDs to be restored from pref");
- let data = JSON.stringify([
- ["savedID1", { lastSeen: Date.now() }],
- ["savedID2", { lastSeen: Date.now() }],
- // 9 weeks ago, should auto expire.
- ["savedID3", { lastSeen: Date.now() - 9 * 7 * 24 * 60 * 60 * 1000 }],
- ]);
- Services.prefs.setCharPref("browser.uitour.seenPageIDs",
- data);
-
- resetSeenPageIDsLazyGetter();
- checkExpectedSeenPageIDs(["savedID1", "savedID2"]);
-});
-
-add_UITour_task(function* test_seenPageIDs_set_1() {
- yield gContentAPI.registerPageID("testpage1");
-
- yield waitForConditionPromise(() => UITour.seenPageIDs.size == 3, "Waiting for page to be registered.");
-
- checkExpectedSeenPageIDs(["savedID1", "savedID2", "testpage1"]);
-
- const PREFIX = BrowserUITelemetry.BUCKET_PREFIX;
- const SEP = BrowserUITelemetry.BUCKET_SEPARATOR;
-
- let bucket = PREFIX + "UITour" + SEP + "testpage1";
- is(BrowserUITelemetry.currentBucket, bucket, "Bucket should have correct name");
-
- gBrowser.selectedTab = gBrowser.addTab("about:blank");
- bucket = PREFIX + "UITour" + SEP + "testpage1" + SEP + "inactive" + SEP + "1m";
- is(BrowserUITelemetry.currentBucket, bucket,
- "After switching tabs, bucket should be expiring");
-
- gBrowser.removeTab(gBrowser.selectedTab);
- gBrowser.selectedTab = gTestTab;
- BrowserUITelemetry.setBucket(null);
-});
-
-add_UITour_task(function* test_seenPageIDs_set_2() {
- yield gContentAPI.registerPageID("testpage2");
-
- yield waitForConditionPromise(() => UITour.seenPageIDs.size == 4, "Waiting for page to be registered.");
-
- checkExpectedSeenPageIDs(["savedID1", "savedID2", "testpage1", "testpage2"]);
-
- const PREFIX = BrowserUITelemetry.BUCKET_PREFIX;
- const SEP = BrowserUITelemetry.BUCKET_SEPARATOR;
-
- let bucket = PREFIX + "UITour" + SEP + "testpage2";
- is(BrowserUITelemetry.currentBucket, bucket, "Bucket should have correct name");
-
- gBrowser.removeTab(gTestTab);
- gTestTab = null;
- bucket = PREFIX + "UITour" + SEP + "testpage2" + SEP + "closed" + SEP + "1m";
- is(BrowserUITelemetry.currentBucket, bucket,
- "After closing tab, bucket should be expiring");
-
- BrowserUITelemetry.setBucket(null);
-});
diff --git a/browser/components/uitour/test/browser_UITour_resetProfile.js b/browser/components/uitour/test/browser_UITour_resetProfile.js
deleted file mode 100644
index c91d0a4f2..000000000
--- a/browser/components/uitour/test/browser_UITour_resetProfile.js
+++ /dev/null
@@ -1,48 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-// Test that a reset profile dialog appears when "resetFirefox" event is triggered
-add_UITour_task(function* test_resetFirefox() {
- let canReset = yield getConfigurationPromise("canReset");
- ok(!canReset, "Shouldn't be able to reset from mochitest's temporary profile.");
- let dialogPromise = new Promise((resolve) => {
- let winWatcher = Cc["@mozilla.org/embedcomp/window-watcher;1"].
- getService(Ci.nsIWindowWatcher);
- winWatcher.registerNotification(function onOpen(subj, topic, data) {
- if (topic == "domwindowopened" && subj instanceof Ci.nsIDOMWindow) {
- subj.addEventListener("load", function onLoad() {
- subj.removeEventListener("load", onLoad);
- if (subj.document.documentURI ==
- "chrome://global/content/resetProfile.xul") {
- winWatcher.unregisterNotification(onOpen);
- ok(true, "Observed search manager window open");
- is(subj.opener, window,
- "Reset Firefox event opened a reset profile window.");
- subj.close();
- resolve();
- }
- });
- }
- });
- });
-
- // make reset possible.
- let profileService = Cc["@mozilla.org/toolkit/profile-service;1"].
- getService(Ci.nsIToolkitProfileService);
- let currentProfileDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let profileName = "mochitest-test-profile-temp-" + Date.now();
- let tempProfile = profileService.createProfile(currentProfileDir, profileName);
- canReset = yield getConfigurationPromise("canReset");
- ok(canReset, "Should be able to reset from mochitest's temporary profile once it's in the profile manager.");
- yield gContentAPI.resetFirefox();
- yield dialogPromise;
- tempProfile.remove(false);
- canReset = yield getConfigurationPromise("canReset");
- ok(!canReset, "Shouldn't be able to reset from mochitest's temporary profile once removed from the profile manager.");
-});
-
diff --git a/browser/components/uitour/test/browser_UITour_showNewTab.js b/browser/components/uitour/test/browser_UITour_showNewTab.js
deleted file mode 100644
index 2deb08148..000000000
--- a/browser/components/uitour/test/browser_UITour_showNewTab.js
+++ /dev/null
@@ -1,17 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-// Test that we can switch to about:newtab
-add_UITour_task(function* test_aboutNewTab() {
- let newTabLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:newtab");
- info("Showing about:newtab");
- yield gContentAPI.showNewTab();
- info("Waiting for about:newtab to load");
- yield newTabLoaded;
- is(gBrowser.selectedBrowser.currentURI.spec, "about:newtab", "Loaded about:newtab");
-});
diff --git a/browser/components/uitour/test/browser_UITour_sync.js b/browser/components/uitour/test/browser_UITour_sync.js
deleted file mode 100644
index 14ac0c1f6..000000000
--- a/browser/components/uitour/test/browser_UITour_sync.js
+++ /dev/null
@@ -1,105 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-registerCleanupFunction(function() {
- Services.prefs.clearUserPref("services.sync.username");
-});
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_checkSyncSetup_disabled() {
- let result = yield getConfigurationPromise("sync");
- is(result.setup, false, "Sync shouldn't be setup by default");
-});
-
-add_UITour_task(function* test_checkSyncSetup_enabled() {
- Services.prefs.setCharPref("services.sync.username", "uitour@tests.mozilla.org");
- let result = yield getConfigurationPromise("sync");
- is(result.setup, true, "Sync should be setup");
-});
-
-add_UITour_task(function* test_checkSyncCounts() {
- Services.prefs.setIntPref("services.sync.clients.devices.desktop", 4);
- Services.prefs.setIntPref("services.sync.clients.devices.mobile", 5);
- Services.prefs.setIntPref("services.sync.numClients", 9);
- let result = yield getConfigurationPromise("sync");
- is(result.mobileDevices, 5, "mobileDevices should be set");
- is(result.desktopDevices, 4, "desktopDevices should be set");
- is(result.totalDevices, 9, "totalDevices should be set");
-
- Services.prefs.clearUserPref("services.sync.clients.devices.desktop");
- result = yield getConfigurationPromise("sync");
- is(result.mobileDevices, 5, "mobileDevices should be set");
- is(result.desktopDevices, 0, "desktopDevices should be 0");
- is(result.totalDevices, 9, "totalDevices should be set");
-
- Services.prefs.clearUserPref("services.sync.clients.devices.mobile");
- result = yield getConfigurationPromise("sync");
- is(result.mobileDevices, 0, "mobileDevices should be 0");
- is(result.desktopDevices, 0, "desktopDevices should be 0");
- is(result.totalDevices, 9, "totalDevices should be set");
-
- Services.prefs.clearUserPref("services.sync.numClients");
- result = yield getConfigurationPromise("sync");
- is(result.mobileDevices, 0, "mobileDevices should be 0");
- is(result.desktopDevices, 0, "desktopDevices should be 0");
- is(result.totalDevices, 0, "totalDevices should be 0");
-});
-
-// The showFirefoxAccounts API is sync related, so we test that here too...
-add_UITour_task(function* test_firefoxAccountsNoParams() {
- yield gContentAPI.showFirefoxAccounts();
- yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false,
- "about:accounts?action=signup&entrypoint=uitour");
-});
-
-add_UITour_task(function* test_firefoxAccountsValidParams() {
- yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", utm_bar: "bar" });
- yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false,
- "about:accounts?action=signup&entrypoint=uitour&utm_foo=foo&utm_bar=bar");
-});
-
-add_UITour_task(function* test_firefoxAccountsNonAlphaValue() {
- // All characters in the value are allowed, but they must be automatically escaped.
- // (we throw a unicode character in there too - it's not auto-utf8 encoded,
- // but that's ok, so long as it is escaped correctly.)
- let value = "foo& /=?:\\\xa9";
- // encodeURIComponent encodes spaces to %20 but we want "+"
- let expected = encodeURIComponent(value).replace(/%20/g, "+");
- yield gContentAPI.showFirefoxAccounts({ utm_foo: value });
- yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false,
- "about:accounts?action=signup&entrypoint=uitour&utm_foo=" + expected);
-});
-
-// A helper to check the request was ignored due to invalid params.
-function* checkAboutAccountsNotLoaded() {
- try {
- yield waitForConditionPromise(() => {
- return gBrowser.selectedBrowser.currentURI.spec.startsWith("about:accounts");
- }, "Check if about:accounts opened");
- ok(false, "No about:accounts tab should have opened");
- } catch (ex) {
- ok(true, "No about:accounts tab opened");
- }
-}
-
-add_UITour_task(function* test_firefoxAccountsNonObject() {
- // non-string should be rejected.
- yield gContentAPI.showFirefoxAccounts(99);
- yield checkAboutAccountsNotLoaded();
-});
-
-add_UITour_task(function* test_firefoxAccountsNonUtmPrefix() {
- // Any non "utm_" name should should be rejected.
- yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", bar: "bar" });
- yield checkAboutAccountsNotLoaded();
-});
-
-add_UITour_task(function* test_firefoxAccountsNonAlphaName() {
- // Any "utm_" name which includes non-alpha chars should be rejected.
- yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", "utm_bar=": "bar" });
- yield checkAboutAccountsNotLoaded();
-});
diff --git a/browser/components/uitour/test/browser_UITour_toggleReaderMode.js b/browser/components/uitour/test/browser_UITour_toggleReaderMode.js
deleted file mode 100644
index 58313e74b..000000000
--- a/browser/components/uitour/test/browser_UITour_toggleReaderMode.js
+++ /dev/null
@@ -1,16 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function*() {
- ok(!gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader"),
- "Should not be in reader mode at start of test.");
- yield gContentAPI.toggleReaderMode();
- yield waitForConditionPromise(() => gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader"));
- ok(gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader"),
- "Should be in reader mode now.");
-});
diff --git a/browser/components/uitour/test/browser_backgroundTab.js b/browser/components/uitour/test/browser_backgroundTab.js
deleted file mode 100644
index c4117c698..000000000
--- a/browser/components/uitour/test/browser_backgroundTab.js
+++ /dev/null
@@ -1,46 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-requestLongerTimeout(2);
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_bg_getConfiguration() {
- info("getConfiguration is on the allowed list so should work");
- yield* loadForegroundTab();
- let data = yield getConfigurationPromise("availableTargets");
- ok(data, "Got data from getConfiguration");
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-add_UITour_task(function* test_bg_showInfo() {
- info("showInfo isn't on the allowed action list so should be denied");
- yield* loadForegroundTab();
-
- yield showInfoPromise("appMenu", "Hello from the background", "Surprise!").then(
- () => ok(false, "panel shouldn't have shown from a background tab"),
- () => ok(true, "panel wasn't shown from a background tab"));
-
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
-
-function* loadForegroundTab() {
- // Spawn a content task that resolves once we're sure the visibilityState was
- // changed. This state is what the tests in this file rely on.
- let promise = ContentTask.spawn(gBrowser.selectedTab.linkedBrowser, null, function* () {
- return new Promise(resolve => {
- let document = content.document;
- document.addEventListener("visibilitychange", function onStateChange() {
- Assert.equal(document.visibilityState, "hidden", "UITour page should be hidden now.");
- document.removeEventListener("visibilitychange", onStateChange);
- resolve();
- });
- });
- });
- yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- yield promise;
- isnot(gBrowser.selectedTab, gTestTab, "Make sure tour tab isn't selected");
-}
diff --git a/browser/components/uitour/test/browser_closeTab.js b/browser/components/uitour/test/browser_closeTab.js
deleted file mode 100644
index 2b998347a..000000000
--- a/browser/components/uitour/test/browser_closeTab.js
+++ /dev/null
@@ -1,18 +0,0 @@
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_closeTab() {
- // Setting gTestTab to null indicates that the tab has already been closed,
- // and if this does not happen the test run will fail.
- let closePromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabClose");
- yield gContentAPI.closeTab();
- yield closePromise;
- gTestTab = null;
-});
diff --git a/browser/components/uitour/test/browser_fxa.js b/browser/components/uitour/test/browser_fxa.js
deleted file mode 100644
index 36ac45a62..000000000
--- a/browser/components/uitour/test/browser_fxa.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
- "resource://gre/modules/FxAccounts.jsm");
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-function test() {
- UITourTest();
-}
-
-registerCleanupFunction(function*() {
- yield signOut();
- gFxAccounts.updateAppMenuItem();
-});
-
-var tests = [
- taskify(function* test_highlight_accountStatus_loggedOut() {
- let userData = yield fxAccounts.getSignedInUser();
- is(userData, null, "Not logged in initially");
- yield showMenuPromise("appMenu");
- yield showHighlightPromise("accountStatus");
- let highlight = document.getElementById("UITourHighlightContainer");
- is(highlight.getAttribute("targetName"), "accountStatus", "Correct highlight target");
- }),
-
- taskify(function* test_highlight_accountStatus_loggedIn() {
- yield setSignedInUser();
- let userData = yield fxAccounts.getSignedInUser();
- isnot(userData, null, "Logged in now");
- gFxAccounts.updateAppMenuItem(); // Causes a leak
- yield showMenuPromise("appMenu");
- yield showHighlightPromise("accountStatus");
- let highlight = document.getElementById("UITourHighlightContainer");
- is(highlight.popupBoxObject.anchorNode.id, "PanelUI-fxa-avatar", "Anchored on avatar");
- is(highlight.getAttribute("targetName"), "accountStatus", "Correct highlight target");
- }),
-];
-
-// Helpers copied from browser_aboutAccounts.js
-// watch out - these will fire observers which if you aren't careful, may
-// interfere with the tests.
-function setSignedInUser(data) {
- if (!data) {
- data = {
- email: "foo@example.com",
- uid: "1234@lcip.org",
- assertion: "foobar",
- sessionToken: "dead",
- kA: "beef",
- kB: "cafe",
- verified: true
- };
- }
- return fxAccounts.setSignedInUser(data);
-}
-
-function signOut() {
- // we always want a "localOnly" signout here...
- return fxAccounts.signOut(true);
-}
diff --git a/browser/components/uitour/test/browser_no_tabs.js b/browser/components/uitour/test/browser_no_tabs.js
deleted file mode 100644
index 62048b156..000000000
--- a/browser/components/uitour/test/browser_no_tabs.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var HiddenFrame = Cu.import("resource:///modules/HiddenFrame.jsm", {}).HiddenFrame;
-
-const HTML_NS = "http://www.w3.org/1999/xhtml";
-const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
-
-/**
- * Create a frame in the |hiddenDOMWindow| to host a |browser|, then load the URL in the
- * latter.
- *
- * @param aURL
- * The URL to open in the browser.
- **/
-function createHiddenBrowser(aURL) {
- let frame = new HiddenFrame();
- return new Promise(resolve =>
- frame.get().then(aFrame => {
- let doc = aFrame.document;
- let browser = doc.createElementNS(XUL_NS, "browser");
- browser.setAttribute("type", "content");
- browser.setAttribute("disableglobalhistory", "true");
- browser.setAttribute("src", aURL);
-
- doc.documentElement.appendChild(browser);
- resolve({frame: frame, browser: browser});
- }));
-}
-
-/**
- * Remove the browser and the HiddenFrame.
- *
- * @param aFrame
- * The HiddenFrame to dismiss.
- * @param aBrowser
- * The browser to dismiss.
- */
-function destroyHiddenBrowser(aFrame, aBrowser) {
- // Dispose of the hidden browser.
- aBrowser.remove();
-
- // Take care of the frame holding our invisible browser.
- aFrame.destroy();
-}
-
-/**
- * Test that UITour works when called when no tabs are available (e.g., when using windowless
- * browsers).
- */
-add_task(function* test_windowless_UITour() {
- // Get the URL for the test page.
- let pageURL = getRootDirectory(gTestPath) + "uitour.html";
-
- // Allow the URL to use the UITour.
- info("Adding UITour permission to the test page.");
- let pageURI = Services.io.newURI(pageURL, null, null);
- Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION);
-
- // UITour's ping will resolve this promise.
- let deferredPing = Promise.defer();
-
- // Create a windowless browser and test that UITour works in it.
- let browserPromise = createHiddenBrowser(pageURL);
- browserPromise.then(frameInfo => {
- isnot(frameInfo.browser, null, "The browser must exist and not be null.");
-
- // Load UITour frame script.
- frameInfo.browser.messageManager.loadFrameScript(
- "chrome://browser/content/content-UITour.js", false);
-
- // When the page loads, try to use UITour API.
- frameInfo.browser.addEventListener("load", function loadListener() {
- info("The test page was correctly loaded.");
-
- frameInfo.browser.removeEventListener("load", loadListener, true);
-
- // Get a reference to the UITour API.
- info("Testing access to the UITour API.");
- let contentWindow = Cu.waiveXrays(frameInfo.browser.contentDocument.defaultView);
- isnot(contentWindow, null, "The content window must exist and not be null.");
-
- let uitourAPI = contentWindow.Mozilla.UITour;
-
- // Test the UITour API with a ping.
- uitourAPI.ping(function() {
- info("Ping response received from the UITour API.");
-
- // Make sure to clean up.
- destroyHiddenBrowser(frameInfo.frame, frameInfo.browser);
-
- // Resolve our promise.
- deferredPing.resolve();
- });
- }, true);
- });
-
- // Wait for the UITour ping to complete.
- yield deferredPing.promise;
-});
diff --git a/browser/components/uitour/test/browser_openPreferences.js b/browser/components/uitour/test/browser_openPreferences.js
deleted file mode 100644
index c41865120..000000000
--- a/browser/components/uitour/test/browser_openPreferences.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_openPreferences() {
- let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences");
- yield gContentAPI.openPreferences();
- let tab = yield promiseTabOpened;
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_UITour_task(function* test_openInvalidPreferences() {
- yield gContentAPI.openPreferences(999);
-
- try {
- yield waitForConditionPromise(() => {
- return gBrowser.selectedBrowser.currentURI.spec.startsWith("about:preferences");
- }, "Check if about:preferences opened");
- ok(false, "No about:preferences tab should have opened");
- } catch (ex) {
- ok(true, "No about:preferences tab opened: " + ex);
- }
-});
-
-add_UITour_task(function* test_openPrivacyPreferences() {
- let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#privacy");
- yield gContentAPI.openPreferences("privacy");
- let tab = yield promiseTabOpened;
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/components/uitour/test/browser_openSearchPanel.js b/browser/components/uitour/test/browser_openSearchPanel.js
deleted file mode 100644
index 5faa9db02..000000000
--- a/browser/components/uitour/test/browser_openSearchPanel.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-function test() {
- UITourTest();
-}
-
-var tests = [
- function test_openSearchPanel(done) {
- let searchbar = document.getElementById("searchbar");
-
- // If suggestions are enabled, the panel will attempt to use the network to connect
- // to the suggestions provider, causing the test suite to fail.
- Services.prefs.setBoolPref("browser.search.suggest.enabled", false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("browser.search.suggest.enabled");
- });
-
- ok(!searchbar.textbox.open, "Popup starts as closed");
- gContentAPI.openSearchPanel(() => {
- ok(searchbar.textbox.open, "Popup was opened");
- searchbar.textbox.closePopup();
- ok(!searchbar.textbox.open, "Popup was closed");
- done();
- });
- },
-];
diff --git a/browser/components/uitour/test/browser_showMenu_controlCenter.js b/browser/components/uitour/test/browser_showMenu_controlCenter.js
deleted file mode 100644
index 0faa5f862..000000000
--- a/browser/components/uitour/test/browser_showMenu_controlCenter.js
+++ /dev/null
@@ -1,44 +0,0 @@
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const CONTROL_CENTER_PANEL = gIdentityHandler._identityPopup;
-const CONTROL_CENTER_MENU_NAME = "controlCenter";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-add_task(setup_UITourTest);
-
-add_UITour_task(function* test_showMenu() {
- is_element_hidden(CONTROL_CENTER_PANEL, "Panel should initially be hidden");
- yield showMenuPromise(CONTROL_CENTER_MENU_NAME);
- is_element_visible(CONTROL_CENTER_PANEL, "Panel should be visible after showMenu");
-
- yield gURLBar.focus();
- is_element_visible(CONTROL_CENTER_PANEL, "Panel should remain visible after focus outside");
-
- yield showMenuPromise(CONTROL_CENTER_MENU_NAME);
- is_element_visible(CONTROL_CENTER_PANEL,
- "Panel should remain visible and callback called after a 2nd showMenu");
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "about:blank"
- }, function*() {
- ok(true, "Tab opened");
- });
-
- is_element_hidden(CONTROL_CENTER_PANEL, "Panel should hide upon tab switch");
-});
-
-add_UITour_task(function* test_hideMenu() {
- is_element_hidden(CONTROL_CENTER_PANEL, "Panel should initially be hidden");
- yield showMenuPromise(CONTROL_CENTER_MENU_NAME);
- is_element_visible(CONTROL_CENTER_PANEL, "Panel should be visible after showMenu");
- let hidePromise = promisePanelElementHidden(window, CONTROL_CENTER_PANEL);
- yield gContentAPI.hideMenu(CONTROL_CENTER_MENU_NAME);
- yield hidePromise;
-
- is_element_hidden(CONTROL_CENTER_PANEL, "Panel should hide after hideMenu");
-});
diff --git a/browser/components/uitour/test/browser_trackingProtection.js b/browser/components/uitour/test/browser_trackingProtection.js
deleted file mode 100644
index 32a9920ec..000000000
--- a/browser/components/uitour/test/browser_trackingProtection.js
+++ /dev/null
@@ -1,90 +0,0 @@
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-const PREF_INTRO_COUNT = "privacy.trackingprotection.introCount";
-const PREF_TP_ENABLED = "privacy.trackingprotection.enabled";
-const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html";
-const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html";
-const TOOLTIP_PANEL = document.getElementById("UITourTooltip");
-const TOOLTIP_ANCHOR = document.getElementById("tracking-protection-icon");
-
-var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-registerCleanupFunction(function() {
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.prefs.clearUserPref(PREF_TP_ENABLED);
- Services.prefs.clearUserPref(PREF_INTRO_COUNT);
-});
-
-function allowOneIntro() {
- Services.prefs.setIntPref(PREF_INTRO_COUNT, TrackingProtection.MAX_INTROS - 1);
-}
-
-add_task(function* setup_test() {
- Services.prefs.setBoolPref(PREF_TP_ENABLED, true);
- yield UrlClassifierTestUtils.addTestTrackers();
-});
-
-add_task(function* test_benignPage() {
- info("Load a test page not containing tracking elements");
- allowOneIntro();
- yield BrowserTestUtils.withNewTab({gBrowser, url: BENIGN_PAGE}, function*() {
- yield waitForConditionPromise(() => {
- return is_visible(TOOLTIP_PANEL);
- }, "Info panel shouldn't appear on a benign page").
- then(() => ok(false, "Info panel shouldn't appear"),
- () => {
- ok(true, "Info panel didn't appear on a benign page");
- });
-
- });
-});
-
-add_task(function* test_trackingPages() {
- info("Load a test page containing tracking elements");
- allowOneIntro();
- yield BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, function*() {
- yield new Promise((resolve, reject) => {
- waitForPopupAtAnchor(TOOLTIP_PANEL, TOOLTIP_ANCHOR, resolve,
- "Intro panel should appear");
- });
-
- is(Services.prefs.getIntPref(PREF_INTRO_COUNT), TrackingProtection.MAX_INTROS, "Check intro count increased");
-
- let step2URL = Services.urlFormatter.formatURLPref("privacy.trackingprotection.introURL") +
- "?step=2&newtab=true";
- let buttons = document.getElementById("UITourTooltipButtons");
-
- info("Click the step text and nothing should happen");
- let tabCount = gBrowser.tabs.length;
- yield EventUtils.synthesizeMouseAtCenter(buttons.children[0], {});
- is(gBrowser.tabs.length, tabCount, "Same number of tabs should be open");
-
- info("Resetting count to test that viewing the tour prevents future panels");
- allowOneIntro();
-
- let panelHiddenPromise = promisePanelElementHidden(window, TOOLTIP_PANEL);
- let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, step2URL);
- info("Clicking the main button");
- EventUtils.synthesizeMouseAtCenter(buttons.children[1], {});
- let tab = yield tabPromise;
- is(Services.prefs.getIntPref(PREF_INTRO_COUNT), TrackingProtection.MAX_INTROS,
- "Check intro count is at the max after opening step 2");
- is(gBrowser.tabs.length, tabCount + 1, "Tour step 2 tab opened");
- yield panelHiddenPromise;
- ok(true, "Panel hid when the button was clicked");
- yield BrowserTestUtils.removeTab(tab);
- });
-
- info("Open another tracking page and make sure we don't show the panel again");
- yield BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, function*() {
- yield waitForConditionPromise(() => {
- return is_visible(TOOLTIP_PANEL);
- }, "Info panel shouldn't appear more than MAX_INTROS").
- then(() => ok(false, "Info panel shouldn't appear again"),
- () => {
- ok(true, "Info panel didn't appear more than MAX_INTROS on tracking pages");
- });
-
- });
-});
diff --git a/browser/components/uitour/test/browser_trackingProtection_tour.js b/browser/components/uitour/test/browser_trackingProtection_tour.js
deleted file mode 100644
index 0ee0e1686..000000000
--- a/browser/components/uitour/test/browser_trackingProtection_tour.js
+++ /dev/null
@@ -1,77 +0,0 @@
-"use strict";
-
-var gTestTab;
-var gContentAPI;
-var gContentWindow;
-
-const { UrlClassifierTestUtils } = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {});
-
-const TP_ENABLED_PREF = "privacy.trackingprotection.enabled";
-
-add_task(setup_UITourTest);
-
-add_task(function* test_setup() {
- Services.prefs.setBoolPref("privacy.trackingprotection.enabled", true);
- yield UrlClassifierTestUtils.addTestTrackers();
-
- registerCleanupFunction(function() {
- UrlClassifierTestUtils.cleanupTestTrackers();
- Services.prefs.clearUserPref("privacy.trackingprotection.enabled");
- });
-});
-
-add_UITour_task(function* test_unblock_target() {
- yield* checkToggleTarget("controlCenter-trackingUnblock");
-});
-
-add_UITour_task(function* setup_block_target() {
- // Preparation for test_block_target. These are separate since the reload
- // interferes with UITour as it does a teardown. All we really care about
- // is the permission manager entry but UITour tests shouldn't rely on that
- // implementation detail.
- TrackingProtection.disableForCurrentPage();
-});
-
-add_UITour_task(function* test_block_target() {
- yield* checkToggleTarget("controlCenter-trackingBlock");
- TrackingProtection.enableForCurrentPage();
-});
-
-
-function* checkToggleTarget(targetID) {
- let popup = document.getElementById("UITourTooltip");
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function () {
- let doc = content.document;
- let iframe = doc.createElement("iframe");
- iframe.setAttribute("id", "tracking-element");
- iframe.setAttribute("src", "https://tracking.example.com/");
- doc.body.insertBefore(iframe, doc.body.firstChild);
- });
-
- let testTargetAvailability = function* (expectedAvailable) {
- let data = yield getConfigurationPromise("availableTargets");
- let available = (data.targets.indexOf(targetID) != -1);
- is(available, expectedAvailable, "Target has expected availability.");
- };
- yield testTargetAvailability(false);
- yield showMenuPromise("controlCenter");
- yield testTargetAvailability(true);
-
- yield showInfoPromise(targetID, "This is " + targetID,
- "My arrow should be on the side");
- is(popup.popupBoxObject.alignmentPosition, "end_before",
- "Check " + targetID + " position");
-
- let hideMenuPromise =
- promisePanelElementHidden(window, gIdentityHandler._identityPopup);
- yield gContentAPI.hideMenu("controlCenter");
- yield hideMenuPromise;
-
- ok(!is_visible(popup), "The tooltip should now be hidden.");
- yield testTargetAvailability(false);
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function () {
- content.document.getElementById("tracking-element").remove();
- });
-}
diff --git a/browser/components/uitour/test/head.js b/browser/components/uitour/test/head.js
deleted file mode 100644
index 2b5b994ae..000000000
--- a/browser/components/uitour/test/head.js
+++ /dev/null
@@ -1,449 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "UITour",
- "resource:///modules/UITour.jsm");
-
-
-const SINGLE_TRY_TIMEOUT = 100;
-const NUMBER_OF_TRIES = 30;
-
-function waitForConditionPromise(condition, timeoutMsg, tryCount=NUMBER_OF_TRIES) {
- let defer = Promise.defer();
- let tries = 0;
- function checkCondition() {
- if (tries >= tryCount) {
- defer.reject(timeoutMsg);
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- return defer.reject(e);
- }
- if (conditionPassed) {
- return defer.resolve();
- }
- tries++;
- setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
- return undefined;
- }
- setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
- return defer.promise;
-}
-
-function waitForCondition(condition, nextTest, errorMsg) {
- waitForConditionPromise(condition, errorMsg).then(nextTest, (reason) => {
- ok(false, reason + (reason.stack ? "\n" + reason.stack : ""));
- });
-}
-
-/**
- * Wrapper to partially transition tests to Task. Use `add_UITour_task` instead for new tests.
- */
-function taskify(fun) {
- return (done) => {
- // Output the inner function name otherwise no name will be output.
- info("\t" + fun.name);
- return Task.spawn(fun).then(done, (reason) => {
- ok(false, reason);
- done();
- });
- };
-}
-
-function is_hidden(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
- if (style.display == "-moz-popup")
- return ["hiding", "closed"].indexOf(element.state) != -1;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_hidden(element.parentNode);
-
- return false;
-}
-
-function is_visible(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return false;
- if (style.visibility != "visible")
- return false;
- if (style.display == "-moz-popup" && element.state != "open")
- return false;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_visible(element.parentNode);
-
- return true;
-}
-
-function is_element_visible(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_visible(element), msg);
-}
-
-function waitForElementToBeVisible(element, nextTest, msg) {
- waitForCondition(() => is_visible(element),
- () => {
- ok(true, msg);
- nextTest();
- },
- "Timeout waiting for visibility: " + msg);
-}
-
-function waitForElementToBeHidden(element, nextTest, msg) {
- waitForCondition(() => is_hidden(element),
- () => {
- ok(true, msg);
- nextTest();
- },
- "Timeout waiting for invisibility: " + msg);
-}
-
-function elementVisiblePromise(element, msg) {
- return waitForConditionPromise(() => is_visible(element), "Timeout waiting for visibility: " + msg);
-}
-
-function elementHiddenPromise(element, msg) {
- return waitForConditionPromise(() => is_hidden(element), "Timeout waiting for invisibility: " + msg);
-}
-
-function waitForPopupAtAnchor(popup, anchorNode, nextTest, msg) {
- waitForCondition(() => is_visible(popup) && popup.popupBoxObject.anchorNode == anchorNode,
- () => {
- ok(true, msg);
- is_element_visible(popup, "Popup should be visible");
- nextTest();
- },
- "Timeout waiting for popup at anchor: " + msg);
-}
-
-function getConfigurationPromise(configName) {
- return ContentTask.spawn(gTestTab.linkedBrowser, configName, configName => {
- return new Promise((resolve) => {
- let contentWin = Components.utils.waiveXrays(content);
- contentWin.Mozilla.UITour.getConfiguration(configName, resolve);
- });
- });
-}
-
-function hideInfoPromise(...args) {
- let popup = document.getElementById("UITourTooltip");
- gContentAPI.hideInfo.apply(gContentAPI, args);
- return promisePanelElementHidden(window, popup);
-}
-
-/**
- * `buttons` and `options` require functions from the content scope so we take a
- * function name to call to generate the buttons/options instead of the
- * buttons/options themselves. This makes the signature differ from the content one.
- */
-function showInfoPromise(target, title, text, icon, buttonsFunctionName, optionsFunctionName) {
- let popup = document.getElementById("UITourTooltip");
- let shownPromise = promisePanelElementShown(window, popup);
- return ContentTask.spawn(gTestTab.linkedBrowser, [...arguments], args => {
- let contentWin = Components.utils.waiveXrays(content);
- let [target, title, text, icon, buttonsFunctionName, optionsFunctionName] = args;
- let buttons = buttonsFunctionName ? contentWin[buttonsFunctionName]() : null;
- let options = optionsFunctionName ? contentWin[optionsFunctionName]() : null;
- contentWin.Mozilla.UITour.showInfo(target, title, text, icon, buttons, options);
- }).then(() => shownPromise);
-}
-
-function showHighlightPromise(...args) {
- let popup = document.getElementById("UITourHighlightContainer");
- gContentAPI.showHighlight.apply(gContentAPI, args);
- return promisePanelElementShown(window, popup);
-}
-
-function showMenuPromise(name) {
- return ContentTask.spawn(gTestTab.linkedBrowser, name, name => {
- return new Promise((resolve) => {
- let contentWin = Components.utils.waiveXrays(content);
- contentWin.Mozilla.UITour.showMenu(name, resolve);
- });
- });
-}
-
-function waitForCallbackResultPromise() {
- return ContentTask.spawn(gTestTab.linkedBrowser, null, function*() {
- let contentWin = Components.utils.waiveXrays(content);
- yield ContentTaskUtils.waitForCondition(() => {
- return contentWin.callbackResult;
- }, "callback should be called");
- return {
- data: contentWin.callbackData,
- result: contentWin.callbackResult,
- };
- });
-}
-
-function promisePanelShown(win) {
- let panelEl = win.PanelUI.panel;
- return promisePanelElementShown(win, panelEl);
-}
-
-function promisePanelElementEvent(win, aPanel, aEvent) {
- return new Promise((resolve, reject) => {
- let timeoutId = win.setTimeout(() => {
- aPanel.removeEventListener(aEvent, onPanelEvent);
- reject(aEvent + " event did not happen within 5 seconds.");
- }, 5000);
-
- function onPanelEvent(e) {
- aPanel.removeEventListener(aEvent, onPanelEvent);
- win.clearTimeout(timeoutId);
- // Wait one tick to let UITour.jsm process the event as well.
- executeSoon(resolve);
- }
-
- aPanel.addEventListener(aEvent, onPanelEvent);
- });
-}
-
-function promisePanelElementShown(win, aPanel) {
- return promisePanelElementEvent(win, aPanel, "popupshown");
-}
-
-function promisePanelElementHidden(win, aPanel) {
- return promisePanelElementEvent(win, aPanel, "popuphidden");
-}
-
-function is_element_hidden(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_hidden(element), msg);
-}
-
-function isTourBrowser(aBrowser) {
- let chromeWindow = aBrowser.ownerGlobal;
- return UITour.tourBrowsersByWindow.has(chromeWindow) &&
- UITour.tourBrowsersByWindow.get(chromeWindow).has(aBrowser);
-}
-
-function promisePageEvent() {
- return new Promise((resolve) => {
- Services.mm.addMessageListener("UITour:onPageEvent", function onPageEvent(aMessage) {
- Services.mm.removeMessageListener("UITour:onPageEvent", onPageEvent);
- SimpleTest.executeSoon(resolve);
- });
- });
-}
-
-function loadUITourTestPage(callback, host = "https://example.org/") {
- if (gTestTab)
- gBrowser.removeTab(gTestTab);
-
- let url = getRootDirectory(gTestPath) + "uitour.html";
- url = url.replace("chrome://mochitests/content/", host);
-
- gTestTab = gBrowser.addTab(url);
- gBrowser.selectedTab = gTestTab;
-
- gTestTab.linkedBrowser.addEventListener("load", function onLoad() {
- gTestTab.linkedBrowser.removeEventListener("load", onLoad, true);
-
- if (gMultiProcessBrowser) {
- // When e10s is enabled, make gContentAPI and gContentWindow proxies which has every property
- // return a function which calls the method of the same name on
- // contentWin.Mozilla.UITour/contentWin in a ContentTask.
- let contentWinHandler = {
- get(target, prop, receiver) {
- return (...args) => {
- let taskArgs = {
- methodName: prop,
- args,
- };
- return ContentTask.spawn(gTestTab.linkedBrowser, taskArgs, args => {
- let contentWin = Components.utils.waiveXrays(content);
- return contentWin[args.methodName].apply(contentWin, args.args);
- });
- };
- },
- };
- gContentWindow = new Proxy({}, contentWinHandler);
-
- let UITourHandler = {
- get(target, prop, receiver) {
- return (...args) => {
- let browser = gTestTab.linkedBrowser;
- const proxyFunctionName = "UITourHandler:proxiedfunction-";
- // We need to proxy any callback functions using messages:
- let callbackMap = new Map();
- let fnIndices = [];
- args = args.map((arg, index) => {
- // Replace function arguments with "", and add them to the list of
- // forwarded functions. We'll construct a function on the content-side
- // that forwards all its arguments to a message, and we'll listen for
- // those messages on our side and call the corresponding function with
- // the arguments we got from the content side.
- if (typeof arg == "function") {
- callbackMap.set(index, arg);
- fnIndices.push(index);
- let handler = function(msg) {
- // Please note that this handler assumes that the callback is used only once.
- // That means that a single gContentAPI.observer() call can't be used to observe
- // multiple events.
- browser.messageManager.removeMessageListener(proxyFunctionName + index, handler);
- callbackMap.get(index).apply(null, msg.data);
- };
- browser.messageManager.addMessageListener(proxyFunctionName + index, handler);
- return "";
- }
- return arg;
- });
- let taskArgs = {
- methodName: prop,
- args,
- fnIndices,
- };
- return ContentTask.spawn(browser, taskArgs, function*(args) {
- let contentWin = Components.utils.waiveXrays(content);
- let callbacksCalled = 0;
- let resolveCallbackPromise;
- let allCallbacksCalledPromise = new Promise(resolve => resolveCallbackPromise = resolve);
- let argumentsWithFunctions = args.args.map((arg, index) => {
- if (arg === "" && args.fnIndices.includes(index)) {
- return function() {
- callbacksCalled++;
- sendAsyncMessage("UITourHandler:proxiedfunction-" + index, Array.from(arguments));
- if (callbacksCalled >= args.fnIndices.length) {
- resolveCallbackPromise();
- }
- };
- }
- return arg;
- });
- let rv = contentWin.Mozilla.UITour[args.methodName].apply(contentWin.Mozilla.UITour,
- argumentsWithFunctions);
- if (args.fnIndices.length) {
- yield allCallbacksCalledPromise;
- }
- return rv;
- });
- };
- },
- };
- gContentAPI = new Proxy({}, UITourHandler);
- } else {
- gContentWindow = Components.utils.waiveXrays(gTestTab.linkedBrowser.contentDocument.defaultView);
- gContentAPI = gContentWindow.Mozilla.UITour;
- }
-
- waitForFocus(callback, gTestTab.linkedBrowser);
- }, true);
-}
-
-// Wrapper for UITourTest to be used by add_task tests.
-function* setup_UITourTest() {
- return UITourTest(true);
-}
-
-// Use `add_task(setup_UITourTest);` instead as we will fold this into `setup_UITourTest` once all tests are using `add_UITour_task`.
-function UITourTest(usingAddTask = false) {
- Services.prefs.setBoolPref("browser.uitour.enabled", true);
- let testHttpsUri = Services.io.newURI("https://example.org", null, null);
- let testHttpUri = Services.io.newURI("http://example.org", null, null);
- Services.perms.add(testHttpsUri, "uitour", Services.perms.ALLOW_ACTION);
- Services.perms.add(testHttpUri, "uitour", Services.perms.ALLOW_ACTION);
-
- // If a test file is using add_task, we don't need to have a test function or
- // call `waitForExplicitFinish`.
- if (!usingAddTask) {
- waitForExplicitFinish();
- }
-
- registerCleanupFunction(function() {
- delete window.gContentWindow;
- delete window.gContentAPI;
- if (gTestTab)
- gBrowser.removeTab(gTestTab);
- delete window.gTestTab;
- Services.prefs.clearUserPref("browser.uitour.enabled");
- Services.perms.remove(testHttpsUri, "uitour");
- Services.perms.remove(testHttpUri, "uitour");
- });
-
- // When using tasks, the harness will call the next added task for us.
- if (!usingAddTask) {
- nextTest();
- }
-}
-
-function done(usingAddTask = false) {
- info("== Done test, doing shared checks before teardown ==");
- return new Promise((resolve) => {
- executeSoon(() => {
- if (gTestTab)
- gBrowser.removeTab(gTestTab);
- gTestTab = null;
-
- let highlight = document.getElementById("UITourHighlightContainer");
- is_element_hidden(highlight, "Highlight should be closed/hidden after UITour tab is closed");
-
- let tooltip = document.getElementById("UITourTooltip");
- is_element_hidden(tooltip, "Tooltip should be closed/hidden after UITour tab is closed");
-
- ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up");
- ok(!PanelUI.panel.hasAttribute("panelopen"), "The panel shouldn't have @panelopen");
- isnot(PanelUI.panel.state, "open", "The panel shouldn't be open");
- is(document.getElementById("PanelUI-menu-button").hasAttribute("open"), false, "Menu button should know that the menu is closed");
-
- info("Done shared checks");
- if (usingAddTask) {
- executeSoon(resolve);
- } else {
- executeSoon(nextTest);
- }
- });
- });
-}
-
-function nextTest() {
- if (tests.length == 0) {
- info("finished tests in this file");
- finish();
- return;
- }
- let test = tests.shift();
- info("Starting " + test.name);
- waitForFocus(function() {
- loadUITourTestPage(function() {
- test(done);
- });
- });
-}
-
-/**
- * All new tests that need the help of `loadUITourTestPage` should use this
- * wrapper around their test's generator function to reduce boilerplate.
- */
-function add_UITour_task(func) {
- let genFun = function*() {
- yield new Promise((resolve) => {
- waitForFocus(function() {
- loadUITourTestPage(function() {
- let funcPromise = Task.spawn(func)
- .then(() => done(true),
- (reason) => {
- ok(false, reason);
- return done(true);
- });
- resolve(funcPromise);
- });
- });
- });
- };
- Object.defineProperty(genFun, "name", {
- configurable: true,
- value: func.name,
- });
- add_task(genFun);
-}
diff --git a/browser/components/uitour/test/image.png b/browser/components/uitour/test/image.png
deleted file mode 100644
index 597c7fd2c..000000000
--- a/browser/components/uitour/test/image.png
+++ /dev/null
Binary files differ
diff --git a/browser/components/uitour/test/uitour.html b/browser/components/uitour/test/uitour.html
deleted file mode 100644
index 6c42ac7f8..000000000
--- a/browser/components/uitour/test/uitour.html
+++ /dev/null
@@ -1,42 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8" />
- <title>UITour test</title>
- <script type="application/javascript" src="UITour-lib.js">
- </script>
- <script type="application/javascript">
- var callbackResult, callbackData;
- function makeCallback(name) {
- return (function(data) {
- callbackResult = name;
- callbackData = data;
- });
- }
-
- // Defined in content to avoid weird issues when crossing between chrome/content.
- function makeButtons() {
- return [
- {label: "Regular text", style: "text"},
- {label: "Link", callback: makeCallback("link"), style: "link"},
- {label: "Button 1", callback: makeCallback("button1")},
- {label: "Button 2", callback: makeCallback("button2"), icon: "image.png",
- style: "primary"}
- ];
- }
-
- function makeInfoOptions() {
- return {
- closeButtonCallback: makeCallback("closeButton"),
- targetCallback: makeCallback("target"),
- };
- }
- </script>
- </head>
- <body>
- <h1>UITour tests</h1>
- <p>Because Firefox is...</p>
- <p>Never gonna let you down</p>
- <p>Never gonna give you up</p>
- </body>
-</html>
diff --git a/browser/extensions/formautofill/test/browser/.eslintrc.js b/browser/extensions/formautofill/test/browser/.eslintrc.js
deleted file mode 100644
index 52a2004c9..000000000
--- a/browser/extensions/formautofill/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js",
- ],
-};
diff --git a/browser/extensions/formautofill/test/browser/browser.ini b/browser/extensions/formautofill/test/browser/browser.ini
deleted file mode 100644
index 500224636..000000000
--- a/browser/extensions/formautofill/test/browser/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[browser_check_installed.js]
diff --git a/browser/extensions/formautofill/test/browser/browser_check_installed.js b/browser/extensions/formautofill/test/browser/browser_check_installed.js
deleted file mode 100644
index b018c0f71..000000000
--- a/browser/extensions/formautofill/test/browser/browser_check_installed.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-
-add_task(function* test_enabled() {
- let addon = yield new Promise(
- resolve => AddonManager.getAddonByID("formautofill@mozilla.org", resolve)
- );
- isnot(addon, null, "Check addon exists");
- is(addon.version, "1.0", "Check version");
- is(addon.name, "Form Autofill", "Check name");
- ok(addon.isCompatible, "Check application compatibility");
- ok(!addon.appDisabled, "Check not app disabled");
- ok(addon.isActive, "Check addon is active");
- is(addon.type, "extension", "Check type is 'extension'");
-});
diff --git a/browser/extensions/formautofill/test/unit/.eslintrc b/browser/extensions/formautofill/test/unit/.eslintrc
deleted file mode 100644
index 8e33fb0c6..000000000
--- a/browser/extensions/formautofill/test/unit/.eslintrc
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ],
-}
diff --git a/browser/extensions/formautofill/test/unit/head.js b/browser/extensions/formautofill/test/unit/head.js
deleted file mode 100644
index 67e3bd60b..000000000
--- a/browser/extensions/formautofill/test/unit/head.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Provides infrastructure for automated login components tests.
- */
-
- /* exported importAutofillModule, getTempFile */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://testing-common/MockDocument.jsm");
-
-// Redirect the path of the resouce in addon to the exact file path.
-let defineLazyModuleGetter = XPCOMUtils.defineLazyModuleGetter;
-XPCOMUtils.defineLazyModuleGetter = function() {
- let result = /^resource\:\/\/formautofill\/(.+)$/.exec(arguments[2]);
- if (result) {
- arguments[2] = Services.io.newFileURI(do_get_file(result[1])).spec;
- }
- return defineLazyModuleGetter.apply(this, arguments);
-};
-
-// Load the module by Service newFileURI API for running extension's XPCShell test
-function importAutofillModule(module) {
- return Cu.import(Services.io.newFileURI(do_get_file(module)).spec);
-}
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-// While the previous test file should have deleted all the temporary files it
-// used, on Windows these might still be pending deletion on the physical file
-// system. Thus, start from a new base number every time, to make a collision
-// with a file that is still pending deletion highly unlikely.
-let gFileCounter = Math.floor(Math.random() * 1000000);
-
-/**
- * Returns a reference to a temporary file, that is guaranteed not to exist, and
- * to have never been created before.
- *
- * @param {string} leafName
- * Suggested leaf name for the file to be created.
- *
- * @returns {nsIFile} pointing to a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the file
- * after calling nsIFile.createUnique, because on Windows the delete
- * operation in the file system may still be pending, preventing a new
- * file with the same name to be created.
- */
-function getTempFile(leafName) {
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(leafName);
- let finalLeafName = base + "-" + gFileCounter + ext;
- gFileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let file = FileUtils.getFile("TmpD", [finalLeafName]);
- do_check_false(file.exists());
-
- do_register_cleanup(function() {
- if (file.exists()) {
- file.remove(false);
- }
- });
-
- return file;
-}
-
-add_task(function* test_common_initialize() {
- Services.prefs.setBoolPref("dom.forms.autocomplete.experimental", true);
-
- // Clean up after every test.
- do_register_cleanup(() => {
- Services.prefs.setBoolPref("dom.forms.autocomplete.experimental", false);
- });
-});
diff --git a/browser/extensions/formautofill/test/unit/test_autofillFormFields.js b/browser/extensions/formautofill/test/unit/test_autofillFormFields.js
deleted file mode 100644
index a842e84e8..000000000
--- a/browser/extensions/formautofill/test/unit/test_autofillFormFields.js
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Test for form auto fill content helper fill all inputs function.
- */
-
-"use strict";
-
-let {FormAutofillHandler} = importAutofillModule("FormAutofillContent.jsm");
-
-const TESTCASES = [
- {
- description: "Form without autocomplete property",
- document: `<form><input id="given-name"><input id="family-name">
- <input id="street-addr"><input id="city"><input id="country">
- <input id='email'><input id="tel"></form>`,
- fieldDetails: [],
- profileData: [],
- expectedResult: {
- "given-name": "",
- "family-name": "",
- "street-addr": "",
- "city": "",
- "country": "",
- "email": "",
- "tel": "",
- },
- },
- {
- description: "Form with autocomplete properties and 1 token",
- document: `<form><input id="given-name" autocomplete="given-name">
- <input id="family-name" autocomplete="family-name">
- <input id="street-addr" autocomplete="street-address">
- <input id="city" autocomplete="address-level2">
- <input id="country" autocomplete="country">
- <input id="email" autocomplete="email">
- <input id="tel" autocomplete="tel"></form>`,
- fieldDetails: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
- {
- description: "Form with autocomplete properties and 2 tokens",
- document: `<form><input id="given-name" autocomplete="shipping given-name">
- <input id="family-name" autocomplete="shipping family-name">
- <input id="street-addr" autocomplete="shipping street-address">
- <input id="city" autocomplete="shipping address-level2">
- <input id="country" autocomplete="shipping country">
- <input id='email' autocomplete="shipping email">
- <input id="tel" autocomplete="shipping tel"></form>`,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
- {
- description: "Form with autocomplete properties and profile is partly matched",
- document: `<form><input id="given-name" autocomplete="shipping given-name">
- <input id="family-name" autocomplete="shipping family-name">
- <input id="street-addr" autocomplete="shipping street-address">
- <input id="city" autocomplete="shipping address-level2">
- <input id="country" autocomplete="shipping country">
- <input id='email' autocomplete="shipping email">
- <input id="tel" autocomplete="shipping tel"></form>`,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "",
- "tel": "",
- },
- },
- {
- description: "Form with autocomplete properties but mismatched",
- document: `<form><input id="given-name" autocomplete="shipping given-name">
- <input id="family-name" autocomplete="shipping family-name">
- <input id="street-addr" autocomplete="billing street-address">
- <input id="city" autocomplete="billing address-level2">
- <input id="country" autocomplete="billing country">
- <input id='email' autocomplete="shipping email">
- <input id="tel" autocomplete="shipping tel"></form>`,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "",
- "city": "",
- "country": "",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
-];
-
-for (let tc of TESTCASES) {
- (function() {
- let testcase = tc;
- add_task(function* () {
- do_print("Starting testcase: " + testcase.description);
-
- let doc = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
- let form = doc.querySelector("form");
- let handler = new FormAutofillHandler(form);
-
- handler.fieldDetails = testcase.fieldDetails;
- handler.fieldDetails.forEach((field, index) => {
- field.element = doc.querySelectorAll("input")[index];
- });
-
- handler.autofillFormFields(testcase.profileData);
- for (let id in testcase.expectedResult) {
- Assert.equal(doc.getElementById(id).value, testcase.expectedResult[id],
- "Check the " + id + " fields were filled with correct data");
- }
- });
- })();
-}
diff --git a/browser/extensions/formautofill/test/unit/test_collectFormFields.js b/browser/extensions/formautofill/test/unit/test_collectFormFields.js
deleted file mode 100644
index 52549b746..000000000
--- a/browser/extensions/formautofill/test/unit/test_collectFormFields.js
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Test for form auto fill content helper collectFormFields functions.
- */
-
-"use strict";
-
-let {FormAutofillHandler} = importAutofillModule("FormAutofillContent.jsm");
-
-const TESTCASES = [
- {
- description: "Form without autocomplete property",
- document: `<form><input id="given-name"><input id="family-name">
- <input id="street-addr"><input id="city"><input id="country">
- <input id='email'><input id="tel"></form>`,
- returnedFormat: [],
- fieldDetails: [],
- },
- {
- description: "Form with autocomplete properties and 1 token",
- document: `<form><input id="given-name" autocomplete="given-name">
- <input id="family-name" autocomplete="family-name">
- <input id="street-addr" autocomplete="street-address">
- <input id="city" autocomplete="address-level2">
- <input id="country" autocomplete="country">
- <input id="email" autocomplete="email">
- <input id="tel" autocomplete="tel"></form>`,
- returnedFormat: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
- {
- description: "Form with autocomplete properties and 2 tokens",
- document: `<form><input id="given-name" autocomplete="shipping given-name">
- <input id="family-name" autocomplete="shipping family-name">
- <input id="street-addr" autocomplete="shipping street-address">
- <input id="city" autocomplete="shipping address-level2">
- <input id="country" autocomplete="shipping country">
- <input id='email' autocomplete="shipping email">
- <input id="tel" autocomplete="shipping tel"></form>`,
- returnedFormat: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
- {
- description: "Form with autocomplete properties and profile is partly matched",
- document: `<form><input id="given-name" autocomplete="shipping given-name">
- <input id="family-name" autocomplete="shipping family-name">
- <input id="street-addr" autocomplete="shipping street-address">
- <input id="city" autocomplete="shipping address-level2">
- <input id="country" autocomplete="shipping country">
- <input id='email' autocomplete="shipping email">
- <input id="tel" autocomplete="shipping tel"></form>`,
- returnedFormat: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
-];
-
-for (let tc of TESTCASES) {
- (function() {
- let testcase = tc;
- add_task(function* () {
- do_print("Starting testcase: " + testcase.description);
-
- let doc = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
- let form = doc.querySelector("form");
- let handler = new FormAutofillHandler(form);
-
- Assert.deepEqual(handler.collectFormFields(), testcase.returnedFormat,
- "Check the format of form autofill were returned correctly");
-
- Assert.deepEqual(handler.fieldDetails, testcase.fieldDetails,
- "Check the fieldDetails were set correctly");
- });
- })();
-}
diff --git a/browser/extensions/formautofill/test/unit/test_populateFieldValues.js b/browser/extensions/formautofill/test/unit/test_populateFieldValues.js
deleted file mode 100644
index 1215cbd16..000000000
--- a/browser/extensions/formautofill/test/unit/test_populateFieldValues.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Test for populating field values in Form Autofill Parent.
- */
-
-/* global FormAutofillParent */
-
-"use strict";
-
-importAutofillModule("FormAutofillParent.jsm");
-
-do_get_profile();
-
-const TEST_FIELDS = [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "organization"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level1"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "postal-code"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email"},
-];
-
-const TEST_GUID = "test-guid";
-
-const TEST_PROFILE = {
- guid: TEST_GUID,
- organization: "World Wide Web Consortium",
- streetAddress: "32 Vassar Street\nMIT Room 32-G524",
- addressLevel2: "Cambridge",
- addressLevel1: "MA",
- postalCode: "02139",
- country: "US",
- tel: "+1 617 253 5702",
- email: "timbl@w3.org",
-};
-
-function camelCase(str) {
- return str.toLowerCase().replace(/-([a-z])/g, s => s[1].toUpperCase());
-}
-
-add_task(function* test_populateFieldValues() {
- FormAutofillParent.init();
-
- let store = FormAutofillParent.getProfileStore();
- do_check_neq(store, null);
-
- store.get = function(guid) {
- do_check_eq(guid, TEST_GUID);
- return store._clone(TEST_PROFILE);
- };
-
- let notifyUsedCalledCount = 0;
- store.notifyUsed = function(guid) {
- do_check_eq(guid, TEST_GUID);
- notifyUsedCalledCount++;
- };
-
- yield new Promise((resolve) => {
- FormAutofillParent.receiveMessage({
- name: "FormAutofill:PopulateFieldValues",
- data: {
- guid: TEST_GUID,
- fields: TEST_FIELDS,
- },
- target: {
- sendAsyncMessage: function(name, data) {
- do_check_eq(name, "FormAutofill:fillForm");
-
- let fields = data.fields;
- do_check_eq(fields.length, TEST_FIELDS.length);
-
- for (let i = 0; i < fields.length; i++) {
- do_check_eq(fields[i].fieldName, TEST_FIELDS[i].fieldName);
- do_check_eq(fields[i].value,
- TEST_PROFILE[camelCase(fields[i].fieldName)]);
- }
-
- resolve();
- },
- },
- });
- });
-
- do_check_eq(notifyUsedCalledCount, 1);
-
- FormAutofillParent._uninit();
- do_check_null(FormAutofillParent.getProfileStore());
-});
-
-add_task(function* test_populateFieldValues_with_invalid_guid() {
- FormAutofillParent.init();
-
- Assert.throws(() => {
- FormAutofillParent.receiveMessage({
- name: "FormAutofill:PopulateFieldValues",
- data: {
- guid: "invalid-guid",
- fields: TEST_FIELDS,
- },
- target: {},
- });
- }, /No matching profile\./);
-
- FormAutofillParent._uninit();
-});
diff --git a/browser/extensions/formautofill/test/unit/test_profileStorage.js b/browser/extensions/formautofill/test/unit/test_profileStorage.js
deleted file mode 100644
index 018adedb8..000000000
--- a/browser/extensions/formautofill/test/unit/test_profileStorage.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * Tests ProfileStorage object.
- */
-
-/* global ProfileStorage */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import(Services.io.newFileURI(do_get_file("ProfileStorage.jsm")).spec);
-
-const TEST_STORE_FILE_NAME = "test-profile.json";
-
-const TEST_PROFILE_1 = {
- organization: "World Wide Web Consortium",
- streetAddress: "32 Vassar Street\nMIT Room 32-G524",
- addressLevel2: "Cambridge",
- addressLevel1: "MA",
- postalCode: "02139",
- country: "US",
- tel: "+1 617 253 5702",
- email: "timbl@w3.org",
-};
-
-const TEST_PROFILE_2 = {
- streetAddress: "Some Address",
- country: "US",
-};
-
-const TEST_PROFILE_3 = {
- streetAddress: "Other Address",
- postalCode: "12345",
-};
-
-const TEST_PROFILE_WITH_INVALID_FIELD = {
- streetAddress: "Another Address",
- invalidField: "INVALID",
-};
-
-let prepareTestProfiles = Task.async(function* (path) {
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- profileStorage.add(TEST_PROFILE_1);
- profileStorage.add(TEST_PROFILE_2);
- yield profileStorage._saveImmediately();
-});
-
-let do_check_profile_matches = (profileWithMeta, profile) => {
- for (let key in profile) {
- do_check_eq(profileWithMeta[key], profile[key]);
- }
-};
-
-add_task(function* test_initialize() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- do_check_eq(profileStorage._store.data.version, 1);
- do_check_eq(profileStorage._store.data.profiles.length, 0);
-
- let data = profileStorage._store.data;
-
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- Assert.deepEqual(profileStorage._store.data, data);
-});
-
-add_task(function* test_getAll() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 2);
- do_check_profile_matches(profiles[0], TEST_PROFILE_1);
- do_check_profile_matches(profiles[1], TEST_PROFILE_2);
-
- // Modifying output shouldn't affect the storage.
- profiles[0].organization = "test";
- do_check_profile_matches(profileStorage.getAll()[0], TEST_PROFILE_1);
-});
-
-add_task(function* test_get() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[0].guid;
-
- let profile = profileStorage.get(guid);
- do_check_profile_matches(profile, TEST_PROFILE_1);
-
- // Modifying output shouldn't affect the storage.
- profile.organization = "test";
- do_check_profile_matches(profileStorage.get(guid), TEST_PROFILE_1);
-
- Assert.throws(() => profileStorage.get("INVALID_GUID"),
- /No matching profile\./);
-});
-
-add_task(function* test_add() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 2);
-
- do_check_profile_matches(profiles[0], TEST_PROFILE_1);
- do_check_profile_matches(profiles[1], TEST_PROFILE_2);
-
- do_check_neq(profiles[0].guid, undefined);
- do_check_neq(profiles[0].timeCreated, undefined);
- do_check_eq(profiles[0].timeLastModified, profiles[0].timeCreated);
- do_check_eq(profiles[0].timeLastUsed, 0);
- do_check_eq(profiles[0].timesUsed, 0);
-
- Assert.throws(() => profileStorage.add(TEST_PROFILE_WITH_INVALID_FIELD),
- /"invalidField" is not a valid field\./);
-});
-
-add_task(function* test_update() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
- let timeLastModified = profiles[1].timeLastModified;
-
- do_check_neq(profiles[1].country, undefined);
-
- profileStorage.update(guid, TEST_PROFILE_3);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profile = profileStorage.get(guid);
-
- do_check_eq(profile.country, undefined);
- do_check_neq(profile.timeLastModified, timeLastModified);
- do_check_profile_matches(profile, TEST_PROFILE_3);
-
- Assert.throws(
- () => profileStorage.update("INVALID_GUID", TEST_PROFILE_3),
- /No matching profile\./
- );
-
- Assert.throws(
- () => profileStorage.update(guid, TEST_PROFILE_WITH_INVALID_FIELD),
- /"invalidField" is not a valid field\./
- );
-});
-
-add_task(function* test_notifyUsed() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
- let timeLastUsed = profiles[1].timeLastUsed;
- let timesUsed = profiles[1].timesUsed;
-
- profileStorage.notifyUsed(guid);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profile = profileStorage.get(guid);
-
- do_check_eq(profile.timesUsed, timesUsed + 1);
- do_check_neq(profile.timeLastUsed, timeLastUsed);
-
- Assert.throws(() => profileStorage.notifyUsed("INVALID_GUID"),
- /No matching profile\./);
-});
-
-add_task(function* test_remove() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
-
- do_check_eq(profiles.length, 2);
-
- profileStorage.remove(guid);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 1);
-
- Assert.throws(() => profileStorage.get(guid), /No matching profile\./);
-});
diff --git a/browser/extensions/formautofill/test/unit/xpcshell.ini b/browser/extensions/formautofill/test/unit/xpcshell.ini
deleted file mode 100644
index 2c5763681..000000000
--- a/browser/extensions/formautofill/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-support-files =
- ../../content/FormAutofillContent.jsm
- ../../content/FormAutofillParent.jsm
- ../../content/ProfileStorage.jsm
-
-[test_autofillFormFields.js]
-[test_collectFormFields.js]
-[test_populateFieldValues.js]
-[test_profileStorage.js]
diff --git a/browser/extensions/pdfjs/test/.eslintrc.js b/browser/extensions/pdfjs/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/extensions/pdfjs/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/pdfjs/test/browser.ini b/browser/extensions/pdfjs/test/browser.ini
deleted file mode 100644
index fb4aa9afc..000000000
--- a/browser/extensions/pdfjs/test/browser.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-support-files =
- file_pdfjs_test.pdf
- head.js
-
-[browser_pdfjs_main.js]
-[browser_pdfjs_navigation.js]
-[browser_pdfjs_savedialog.js]
-[browser_pdfjs_views.js]
-[browser_pdfjs_zoom.js]
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_main.js b/browser/extensions/pdfjs/test/browser_pdfjs_main.js
deleted file mode 100644
index 9660e92c1..000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_main.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser: gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf");
-
- ok(gBrowser.isFindBarInitialized(), "Browser FindBar initialized!");
-
- yield ContentTask.spawn(newTabBrowser, null, function* () {
- //
- // Overall sanity tests
- //
- Assert.ok(content.document.querySelector('div#viewer'), "document content has viewer UI");
- Assert.ok('PDFJS' in content.wrappedJSObject, "window content has PDFJS object");
-
- //
- // Sidebar: open
- //
- var sidebar = content.document.querySelector('button#sidebarToggle'),
- outerContainer = content.document.querySelector('div#outerContainer');
-
- sidebar.click();
- Assert.ok(outerContainer.classList.contains('sidebarOpen'), "sidebar opens on click");
-
- //
- // Sidebar: close
- //
- sidebar.click();
- Assert.ok(!outerContainer.classList.contains('sidebarOpen'), "sidebar closes on click");
-
- //
- // Page change from prev/next buttons
- //
- var prevPage = content.document.querySelector('button#previous'),
- nextPage = content.document.querySelector('button#next');
-
- var pgNumber = content.document.querySelector('input#pageNumber').value;
- Assert.equal(parseInt(pgNumber, 10), 1, "initial page is 1");
-
- //
- // Bookmark button
- //
- var viewBookmark = content.document.querySelector('a#viewBookmark');
- viewBookmark.click();
-
- Assert.ok(viewBookmark.href.length > 0, "viewBookmark button has href");
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js b/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js
deleted file mode 100644
index b01a87ec8..000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js
+++ /dev/null
@@ -1,283 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-const PDF_OUTLINE_ITEMS = 17;
-const TESTS = [
- {
- action: {
- selector: "button#next",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to next page using NEXT button"
-
- },
- {
- action: {
- selector: "button#previous",
- event: "click"
- },
- expectedPage: 1,
- message: "navigated to previous page using PREV button"
- },
- {
- action: {
- selector: "button#next",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to next page using NEXT button"
- },
- {
- action: {
- selector: "input#pageNumber",
- value: 1,
- event: "change"
- },
- expectedPage: 1,
- message: "navigated to first page using pagenumber"
- },
- {
- action: {
- selector: "#thumbnailView a:nth-child(4)",
- event: "click"
- },
- expectedPage: 4,
- message: "navigated to 4th page using thumbnail view"
- },
- {
- action: {
- selector: "#thumbnailView a:nth-child(2)",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to 2nd page using thumbnail view"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 36
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'home' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 34
- },
- expectedPage: 2,
- message: "navigated to 2nd page using 'Page Down' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 33
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'Page Up' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 39
- },
- expectedPage: 2,
- message: "navigated to 2nd page using 'right' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 37
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'left' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 35
- },
- expectedPage: 5,
- message: "navigated to last page using 'home' key"
- },
- {
- action: {
- selector: ".outlineItem:nth-child(1) a",
- event: "click"
- },
- expectedPage: 1,
- message: "navigated to 1st page using outline view"
- },
- {
- action: {
- selector: ".outlineItem:nth-child(" + PDF_OUTLINE_ITEMS + ") a",
- event: "click"
- },
- expectedPage: 4,
- message: "navigated to 4th page using outline view"
- },
- {
- action: {
- selector: "input#pageNumber",
- value: 5,
- event: "change"
- },
- expectedPage: 5,
- message: "navigated to 5th page using pagenumber"
- }
-];
-
-add_task(function* test() {
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf");
-
- yield ContentTask.spawn(newTabBrowser, null, function* () {
- // Check if PDF is opened with internal viewer
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
- });
-
- yield ContentTask.spawn(newTabBrowser, null, contentSetUp);
-
- yield Task.spawn(runTests(newTabBrowser));
-
- yield ContentTask.spawn(newTabBrowser, null, function*() {
- let pageNumber = content.document.querySelector('input#pageNumber');
- Assert.equal(pageNumber.value, pageNumber.max, "Document is left on the last page");
- });
- });
-});
-
-function* contentSetUp() {
- /**
- * Outline Items gets appended to the document later on we have to
- * wait for them before we start to navigate though document
- *
- * @param document
- * @returns {deferred.promise|*}
- */
- function waitForOutlineItems(document) {
- return new Promise((resolve, reject) => {
- document.addEventListener("outlineloaded", function outlineLoaded(evt) {
- document.removeEventListener("outlineloaded", outlineLoaded);
- var outlineCount = evt.detail.outlineCount;
-
- if (document.querySelectorAll(".outlineItem").length === outlineCount) {
- resolve();
- } else {
- reject();
- }
- });
- });
- }
-
- /**
- * The key navigation has to happen in page-fit, otherwise it won't scroll
- * through a complete page
- *
- * @param document
- * @returns {deferred.promise|*}
- */
- function setZoomToPageFit(document) {
- return new Promise((resolve) => {
- document.addEventListener("pagerendered", function onZoom(e) {
- document.removeEventListener("pagerendered", onZoom);
- document.querySelector("#viewer").click();
- resolve();
- });
-
- var select = document.querySelector("select#scaleSelect");
- select.selectedIndex = 2;
- select.dispatchEvent(new Event("change"));
- });
- }
-
- yield waitForOutlineItems(content.document);
- yield setZoomToPageFit(content.document);
-}
-
-/**
- * As the page changes asynchronously, we have to wait for the event after
- * we trigger the action so we will be at the expected page number after each action
- *
- * @param document
- * @param window
- * @param test
- * @param callback
- */
-function* runTests(browser) {
- yield ContentTask.spawn(browser, TESTS, function* (TESTS) {
- let window = content;
- let document = window.document;
-
- for (let test of TESTS) {
- let deferred = {};
- deferred.promise = new Promise((resolve, reject) => {
- deferred.resolve = resolve;
- deferred.reject = reject;
- });
-
- let pageNumber = document.querySelector('input#pageNumber');
-
- // Add an event-listener to wait for page to change, afterwards resolve the promise
- let timeout = window.setTimeout(() => deferred.reject(), 5000);
- window.addEventListener('pagechange', function pageChange() {
- if (pageNumber.value == test.expectedPage) {
- window.removeEventListener('pagechange', pageChange);
- window.clearTimeout(timeout);
- deferred.resolve(+pageNumber.value);
- }
- });
-
- // Get the element and trigger the action for changing the page
- var el = document.querySelector(test.action.selector);
- Assert.ok(el, "Element '" + test.action.selector + "' has been found");
-
- // The value option is for input case
- if (test.action.value)
- el.value = test.action.value;
-
- // Dispatch the event for changing the page
- if (test.action.event == "keydown") {
- var ev = document.createEvent("KeyboardEvent");
- ev.initKeyEvent("keydown", true, true, null, false, false, false, false,
- test.action.keyCode, 0);
- el.dispatchEvent(ev);
- }
- else {
- var ev = new Event(test.action.event);
- }
- el.dispatchEvent(ev);
-
- let pgNumber = yield deferred.promise;
- Assert.equal(pgNumber, test.expectedPage, test.message);
- }
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
-}
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js b/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js
deleted file mode 100644
index a6564e591..000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-function test() {
- var oldAction = changeMimeHandler(Ci.nsIHandlerInfo.useSystemDefault, true);
- var tab = gBrowser.addTab(TESTROOT + "file_pdfjs_test.pdf");
- //
- // Test: "Open with" dialog comes up when pdf.js is not selected as the default
- // handler.
- //
- addWindowListener('chrome://mozapps/content/downloads/unknownContentType.xul', finish);
-
- waitForExplicitFinish();
- registerCleanupFunction(function() {
- changeMimeHandler(oldAction[0], oldAction[1]);
- gBrowser.removeTab(tab);
- });
-}
-
-function changeMimeHandler(preferredAction, alwaysAskBeforeHandling) {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
- var oldAction = [handlerInfo.preferredAction, handlerInfo.alwaysAskBeforeHandling];
-
- // Change and save mime handler settings
- handlerInfo.alwaysAskBeforeHandling = alwaysAskBeforeHandling;
- handlerInfo.preferredAction = preferredAction;
- handlerService.store(handlerInfo);
-
- Services.obs.notifyObservers(null, 'pdfjs:handlerChanged', null);
-
- // Refresh data
- handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- //
- // Test: Mime handler was updated
- //
- is(handlerInfo.alwaysAskBeforeHandling, alwaysAskBeforeHandling, 'always-ask prompt change successful');
- is(handlerInfo.preferredAction, preferredAction, 'mime handler change successful');
-
- return oldAction;
-}
-
-function addWindowListener(aURL, aCallback) {
- Services.wm.addListener({
- onOpenWindow: function(aXULWindow) {
- info("window opened, waiting for focus");
- Services.wm.removeListener(this);
-
- var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- waitForFocus(function() {
- is(domwindow.document.location.href, aURL, "should have seen the right window open");
- domwindow.close();
- aCallback();
- }, domwindow);
- },
- onCloseWindow: function(aXULWindow) { },
- onWindowTitleChange: function(aXULWindow, aNewTitle) { }
- });
-}
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_views.js b/browser/extensions/pdfjs/test/browser_pdfjs_views.js
deleted file mode 100644
index d14503e41..000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_views.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (browser) {
- // check that PDF is opened with internal viewer
- yield waitForPdfJS(browser, TESTROOT + "file_pdfjs_test.pdf");
-
- yield ContentTask.spawn(browser, null, function* () {
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
-
- //open sidebar
- var sidebar = content.document.querySelector('button#sidebarToggle');
- var outerContainer = content.document.querySelector('div#outerContainer');
-
- sidebar.click();
- Assert.ok(outerContainer.classList.contains("sidebarOpen"), "sidebar opens on click");
-
- // check that thumbnail view is open
- var thumbnailView = content.document.querySelector('div#thumbnailView');
- var outlineView = content.document.querySelector('div#outlineView');
-
- Assert.equal(thumbnailView.getAttribute("class"), null,
- "Initial view is thumbnail view");
- Assert.equal(outlineView.getAttribute("class"), "hidden",
- "Outline view is hidden initially");
-
- //switch to outline view
- var viewOutlineButton = content.document.querySelector('button#viewOutline');
- viewOutlineButton.click();
-
- Assert.equal(thumbnailView.getAttribute("class"), "hidden",
- "Thumbnail view is hidden when outline is selected");
- Assert.equal(outlineView.getAttribute("class"), "",
- "Outline view is visible when selected");
-
- //switch back to thumbnail view
- var viewThumbnailButton = content.document.querySelector('button#viewThumbnail');
- viewThumbnailButton.click();
-
- Assert.equal(thumbnailView.getAttribute("class"), "",
- "Thumbnail view is visible when selected");
- Assert.equal(outlineView.getAttribute("class"), "hidden",
- "Outline view is hidden when thumbnail is selected");
-
- sidebar.click();
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js b/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js
deleted file mode 100644
index f2b73fd99..000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js
+++ /dev/null
@@ -1,154 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-const TESTS = [
- {
- action: {
- selector: "button#zoomIn",
- event: "click"
- },
- expectedZoom: 1, // 1 - zoom in
- message: "Zoomed in using the '+' (zoom in) button"
- },
-
- {
- action: {
- selector: "button#zoomOut",
- event: "click"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed out using the '-' (zoom out) button"
- },
-
- {
- action: {
- keyboard: true,
- keyCode: 61,
- event: "+"
- },
- expectedZoom: 1, // 1 - zoom in
- message: "Zoomed in using the CTRL++ keys"
- },
-
- {
- action: {
- keyboard: true,
- keyCode: 109,
- event: "-"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed out using the CTRL+- keys"
- },
-
- {
- action: {
- selector: "select#scaleSelect",
- index: 5,
- event: "change"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed using the zoom picker"
- }
-];
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"]
- .getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false,
- 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally,
- 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf" + "#zoom=100");
-
- yield ContentTask.spawn(newTabBrowser, TESTS, function* (TESTS) {
- let document = content.document;
-
- function waitForRender() {
- return new Promise((resolve) => {
- document.addEventListener("pagerendered", function onPageRendered(e) {
- if(e.detail.pageNumber !== 1) {
- return;
- }
-
- document.removeEventListener("pagerendered", onPageRendered, true);
- resolve();
- }, true);
- });
- }
-
- // check that PDF is opened with internal viewer
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
-
- let initialWidth, previousWidth;
- initialWidth = previousWidth =
- parseInt(content.document.querySelector("div#pageContainer1").style.width);
-
- for (let test of TESTS) {
- // We zoom using an UI element
- var ev;
- if (test.action.selector) {
- // Get the element and trigger the action for changing the zoom
- var el = document.querySelector(test.action.selector);
- Assert.ok(el, "Element '" + test.action.selector + "' has been found");
-
- if (test.action.index){
- el.selectedIndex = test.action.index;
- }
-
- // Dispatch the event for changing the zoom
- ev = new Event(test.action.event);
- }
- // We zoom using keyboard
- else {
- // Simulate key press
- ev = new content.KeyboardEvent("keydown",
- { key: test.action.event,
- keyCode: test.action.keyCode,
- ctrlKey: true });
- el = content;
- }
-
- el.dispatchEvent(ev);
- yield waitForRender();
-
- var pageZoomScale = content.document.querySelector('select#scaleSelect');
-
- // The zoom value displayed in the zoom select
- var zoomValue = pageZoomScale.options[pageZoomScale.selectedIndex].innerHTML;
-
- let pageContainer = content.document.querySelector('div#pageContainer1');
- let actualWidth = parseInt(pageContainer.style.width);
-
- // the actual zoom of the PDF document
- let computedZoomValue = parseInt(((actualWidth/initialWidth).toFixed(2))*100) + "%";
- Assert.equal(computedZoomValue, zoomValue, "Content has correct zoom");
-
- // Check that document zooms in the expected way (in/out)
- let zoom = (actualWidth - previousWidth) * test.expectedZoom;
- Assert.ok(zoom > 0, test.message);
-
- previousWidth = actualWidth;
- }
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/file_pdfjs_test.pdf b/browser/extensions/pdfjs/test/file_pdfjs_test.pdf
deleted file mode 100644
index 7ad87e3c2..000000000
--- a/browser/extensions/pdfjs/test/file_pdfjs_test.pdf
+++ /dev/null
Binary files differ
diff --git a/browser/extensions/pdfjs/test/head.js b/browser/extensions/pdfjs/test/head.js
deleted file mode 100644
index d980bceb1..000000000
--- a/browser/extensions/pdfjs/test/head.js
+++ /dev/null
@@ -1,15 +0,0 @@
-function waitForPdfJS(browser, url) {
- // Runs tests after all 'load' event handlers have fired off
- return ContentTask.spawn(browser, url, function* (url) {
- yield new Promise((resolve) => {
- // NB: Add the listener to the global object so that we receive the
- // event fired from the new window.
- addEventListener("documentload", function listener() {
- removeEventListener("documentload", listener, false);
- resolve();
- }, false, true);
-
- content.location = url;
- });
- });
-}
diff --git a/browser/extensions/pocket/test/.eslintrc.js b/browser/extensions/pocket/test/.eslintrc.js
deleted file mode 100644
index c764b133d..000000000
--- a/browser/extensions/pocket/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/pocket/test/browser.ini b/browser/extensions/pocket/test/browser.ini
deleted file mode 100644
index 3e0be8736..000000000
--- a/browser/extensions/pocket/test/browser.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- test.html
-
-[browser_pocket_ui_check.js]
diff --git a/browser/extensions/pocket/test/browser_pocket_ui_check.js b/browser/extensions/pocket/test/browser_pocket_ui_check.js
deleted file mode 100644
index 12aeaffd6..000000000
--- a/browser/extensions/pocket/test/browser_pocket_ui_check.js
+++ /dev/null
@@ -1,61 +0,0 @@
-"use strict";
-
-function checkWindowProperties(expectPresent, l) {
- for (let name of l) {
- is(!!window.hasOwnProperty(name), expectPresent, "property " + name + (expectPresent ? " is" : " is not") + " present");
- }
-}
-function checkElements(expectPresent, l) {
- for (let id of l) {
- is(!!document.getElementById(id), expectPresent, "element " + id + (expectPresent ? " is" : " is not") + " present");
- }
-}
-
-add_task(function* test_setup() {
- let clearValue = Services.prefs.prefHasUserValue("extensions.pocket.enabled");
- let enabledOnStartup = Services.prefs.getBoolPref("extensions.pocket.enabled");
- registerCleanupFunction(() => {
- if (clearValue) {
- Services.prefs.clearUserPref("extensions.pocket.enabled");
- } else {
- Services.prefs.setBoolPref("extensions.pocket.enabled", enabledOnStartup);
- }
- });
-});
-
-add_task(function*() {
- yield promisePocketEnabled();
-
- checkWindowProperties(true, ["Pocket", "pktUI", "pktUIMessaging"]);
- checkElements(true, ["pocket-button", "panelMenu_pocket", "menu_pocket", "BMB_pocket",
- "panelMenu_pocketSeparator", "menu_pocketSeparator",
- "BMB_pocketSeparator"]);
-
- // check context menu exists
- info("checking content context menu");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "https://example.com/browser/browser/extensions/pocket/test/test.html");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let popupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- let popupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- yield BrowserTestUtils.synthesizeMouseAtCenter("body", {
- type: "contextmenu",
- button: 2
- }, tab.linkedBrowser);
- yield popupShown;
-
- checkElements(true, ["context-pocket", "context-savelinktopocket"]);
-
- contextMenu.hidePopup();
- yield popupHidden;
- yield BrowserTestUtils.removeTab(tab);
-
- yield promisePocketDisabled();
-
- checkWindowProperties(false, ["Pocket", "pktUI", "pktUIMessaging"]);
- checkElements(false, ["pocket-button", "panelMenu_pocket", "menu_pocket", "BMB_pocket",
- "panelMenu_pocketSeparator", "menu_pocketSeparator",
- "BMB_pocketSeparator", "context-pocket", "context-savelinktopocket"]);
-
- yield promisePocketReset();
-});
diff --git a/browser/extensions/pocket/test/head.js b/browser/extensions/pocket/test/head.js
deleted file mode 100644
index e044a42c7..000000000
--- a/browser/extensions/pocket/test/head.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Currently Pocket is disabled in tests. We want these tests to work under
-// either case that Pocket is disabled or enabled on startup of the browser,
-// and that at the end we're reset to the correct state.
-let enabledOnStartup = false;
-
-// PocketEnabled/Disabled promises return true if it was already
-// Enabled/Disabled, and false if it need to Enable/Disable.
-function promisePocketEnabled() {
- if (Services.prefs.getPrefType("extensions.pocket.enabled") != Services.prefs.PREF_INVALID &&
- Services.prefs.getBoolPref("extensions.pocket.enabled")) {
- info( "pocket was already enabled, assuming enabled by default for tests");
- enabledOnStartup = true;
- return Promise.resolve(true);
- }
- info( "pocket is not enabled");
- return new Promise((resolve, reject) => {
- let listener = {
- onWidgetAfterCreation(widgetid) {
- if (widgetid == "pocket-button") {
- info("pocket-button created");
- CustomizableUI.removeListener(listener);
- resolve(false);
- }
- }
- }
- CustomizableUI.addListener(listener);
- Services.prefs.setBoolPref("extensions.pocket.enabled", true);
- });
-}
-
-function promisePocketDisabled() {
- if (Services.prefs.getPrefType("extensions.pocket.enabled") == Services.prefs.PREF_INVALID ||
- !Services.prefs.getBoolPref("extensions.pocket.enabled")) {
- info("pocket-button already disabled");
- return Promise.resolve(true);
- }
- return new Promise((resolve, reject) => {
- let listener = {
- onWidgetDestroyed: function(widgetid) {
- if (widgetid == "pocket-button") {
- CustomizableUI.removeListener(listener);
- info( "pocket-button destroyed");
- // wait for a full unload of pocket
- BrowserTestUtils.waitForCondition(() => {
- return !window.hasOwnProperty("pktUI");
- }, "pocket properties removed from window").then(() => {
- resolve(false);
- })
- }
- }
- }
- CustomizableUI.addListener(listener);
- info("reset pocket enabled pref");
- // testing/profiles/prefs_general.js uses user_pref to disable pocket, set
- // back to false.
- Services.prefs.setBoolPref("extensions.pocket.enabled", false);
- });
-}
-
-function promisePocketReset() {
- if (enabledOnStartup) {
- info("reset is enabling pocket addon");
- return promisePocketEnabled();
- }
- info("reset is disabling pocket addon");
- return promisePocketDisabled();
-}
diff --git a/browser/extensions/pocket/test/test.html b/browser/extensions/pocket/test/test.html
deleted file mode 100644
index aa08cd566..000000000
--- a/browser/extensions/pocket/test/test.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<head>
- <title>Page Title</title>
- <meta charset="utf-8" />
-</head>
-
-<body>
-</body>
-</html>
diff --git a/browser/extensions/webcompat/test/browser/.eslintrc.js b/browser/extensions/webcompat/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/browser/extensions/webcompat/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/webcompat/test/browser/browser.ini b/browser/extensions/webcompat/test/browser/browser.ini
deleted file mode 100644
index 500224636..000000000
--- a/browser/extensions/webcompat/test/browser/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[browser_check_installed.js]
diff --git a/browser/extensions/webcompat/test/browser/browser_check_installed.js b/browser/extensions/webcompat/test/browser/browser_check_installed.js
deleted file mode 100644
index b77458054..000000000
--- a/browser/extensions/webcompat/test/browser/browser_check_installed.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-add_task(function* test_enabled() {
- let addon = yield new Promise(
- resolve => AddonManager.getAddonByID("webcompat@mozilla.org", resolve)
- );
- isnot(addon, null, "Check addon exists");
- is(addon.version, "1.0", "Check version");
- is(addon.name, "Web Compat", "Check name");
- ok(addon.isCompatible, "Check application compatibility");
- ok(!addon.appDisabled, "Check not app disabled");
- ok(addon.isActive, "Check addon is active");
-});
diff --git a/browser/modules/test/.eslintrc.js b/browser/modules/test/.eslintrc.js
deleted file mode 100644
index e2d7896f8..000000000
--- a/browser/modules/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/browser.ini b/browser/modules/test/browser.ini
deleted file mode 100644
index af624439c..000000000
--- a/browser/modules/test/browser.ini
+++ /dev/null
@@ -1,42 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-
-[browser_BrowserUITelemetry_buckets.js]
-[browser_BrowserUITelemetry_defaults.js]
-[browser_BrowserUITelemetry_sidebar.js]
-[browser_BrowserUITelemetry_syncedtabs.js]
-[browser_ContentSearch.js]
-skip-if = true # Bug 1308343
-support-files =
- contentSearch.js
- contentSearchBadImage.xml
- contentSearchSuggestions.sjs
- contentSearchSuggestions.xml
- !/browser/components/search/test/head.js
- !/browser/components/search/test/testEngine.xml
-[browser_NetworkPrioritizer.js]
-[browser_PermissionUI.js]
-[browser_ProcessHangNotifications.js]
-skip-if = !e10s
-[browser_SelfSupportBackend.js]
-support-files =
- ../../components/uitour/test/uitour.html
- ../../components/uitour/UITour-lib.js
-[browser_taskbar_preview.js]
-skip-if = os != "win"
-[browser_UnsubmittedCrashHandler.js]
-run-if = crashreporter
-[browser_UsageTelemetry.js]
-[browser_UsageTelemetry_private_and_restore.js]
-[browser_UsageTelemetry_urlbar.js]
-support-files =
- usageTelemetrySearchSuggestions.sjs
- usageTelemetrySearchSuggestions.xml
-[browser_UsageTelemetry_searchbar.js]
-support-files =
- usageTelemetrySearchSuggestions.sjs
- usageTelemetrySearchSuggestions.xml
-[browser_UsageTelemetry_content.js]
-[browser_UsageTelemetry_content_aboutHome.js]
-[browser_urlBar_zoom.js]
diff --git a/browser/modules/test/browser_BrowserUITelemetry_buckets.js b/browser/modules/test/browser_BrowserUITelemetry_buckets.js
deleted file mode 100644
index f55761705..000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_buckets.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- WHERE'S MAH BUCKET?!
- \
- ___
- .-9 9 `\
- =(:(::)= ;
- |||| \
- |||| `-.
- ,\|\| `,
- / \
- ; `'---.,
- | `\
- ; / |
- \ | /
- ) \ __,.--\ /
- .-' \,..._\ \` .-' .-'
- `-=`` `: | /-/-/`
- `.__/
-*/
-
-"use strict";
-
-
-add_task(function* testBUIT() {
- let s = {};
- Components.utils.import("resource:///modules/BrowserUITelemetry.jsm", s);
- let BUIT = s.BrowserUITelemetry;
-
- registerCleanupFunction(function() {
- BUIT.setBucket(null);
- });
-
-
- // setBucket
- is(BUIT.currentBucket, BUIT.BUCKET_DEFAULT, "Bucket should be default bucket");
- BUIT.setBucket("mah-bucket");
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "mah-bucket", "Bucket should have correct name");
- BUIT.setBucket(null);
- is(BUIT.currentBucket, BUIT.BUCKET_DEFAULT, "Bucket should be reset to default");
-
-
- // _toTimeStr
- is(BUIT._toTimeStr(10), "10ms", "Checking time string reprentation, 10ms");
- is(BUIT._toTimeStr(1000 + 10), "1s10ms", "Checking time string reprentation, 1s10ms");
- is(BUIT._toTimeStr((20 * 1000) + 10), "20s10ms", "Checking time string reprentation, 20s10ms");
- is(BUIT._toTimeStr(60 * 1000), "1m", "Checking time string reprentation, 1m");
- is(BUIT._toTimeStr(3 * 60 * 1000), "3m", "Checking time string reprentation, 3m");
- is(BUIT._toTimeStr((3 * 60 * 1000) + 1), "3m1ms", "Checking time string reprentation, 3m1ms");
- is(BUIT._toTimeStr((60 * 60 * 1000) + (10 * 60 * 1000)), "1h10m", "Checking time string reprentation, 1h10m");
- is(BUIT._toTimeStr(100 * 60 * 60 * 1000), "100h", "Checking time string reprentation, 100h");
-
-
- // setExpiringBucket
- BUIT.setExpiringBucket("walrus", [1001, 2001, 3001, 10001]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "1s1ms",
- "Bucket should be expiring and have time step of 1s1ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "2s1ms");
- }, "Bucket should be expiring and have time step of 2s1ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "3s1ms");
- }, "Bucket should be expiring and have time step of 3s1ms");
-
-
- // Interupt previous expiring bucket
- BUIT.setExpiringBucket("walrus2", [1002, 2002]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus2" + BUIT.BUCKET_SEPARATOR + "1s2ms",
- "Should be new expiring bucket, with time step of 1s2ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus2" + BUIT.BUCKET_SEPARATOR + "2s2ms");
- }, "Should be new expiring bucket, with time step of 2s2ms");
-
-
- // Let expiring bucket expire
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == BUIT.BUCKET_DEFAULT;
- }, "Bucket should have expired, default bucket should now be active");
-
-
- // Interupt expiring bucket with normal bucket
- BUIT.setExpiringBucket("walrus3", [1003, 2003]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus3" + BUIT.BUCKET_SEPARATOR + "1s3ms",
- "Should be new expiring bucket, with time step of 1s3ms");
-
- BUIT.setBucket("mah-bucket");
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "mah-bucket", "Bucket should have correct name");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "mah-bucket");
- }, "Next step of old expiring bucket shouldn't have progressed");
-});
diff --git a/browser/modules/test/browser_BrowserUITelemetry_defaults.js b/browser/modules/test/browser_BrowserUITelemetry_defaults.js
deleted file mode 100644
index ced1bbce0..000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_defaults.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// The purpose of this test is to ensure that by default, BrowserUITelemetry
-// isn't reporting any UI customizations. This is primarily so changes to
-// customizableUI (eg, new buttons, button location changes) also have a
-// corresponding BrowserUITelemetry change.
-
-function test() {
- let s = {};
- Cu.import("resource:///modules/CustomizableUI.jsm", s);
- Cu.import("resource:///modules/BrowserUITelemetry.jsm", s);
-
- let { CustomizableUI, BrowserUITelemetry } = s;
-
- // Bug 1278176 - DevEdition never has the UI in a default state by default.
- if (!AppConstants.MOZ_DEV_EDITION) {
- Assert.ok(CustomizableUI.inDefaultState,
- "No other test should have left CUI in a dirty state.");
- }
-
- let result = BrowserUITelemetry._getWindowMeasurements(window, 0);
-
- // Bug 1278176 - DevEdition always reports the developer-button is moved.
- if (!AppConstants.MOZ_DEV_EDITION) {
- Assert.deepEqual(result.defaultMoved, []);
- }
- Assert.deepEqual(result.nondefaultAdded, []);
- // This one is a bit weird - the "social-share-button" is dynamically added
- // to the toolbar as the feature is first used - but it's listed as being in
- // the toolbar by default so it doesn't end up in nondefaultAdded once it
- // is created. The end result is that it ends up in defaultRemoved before
- // the feature has been activated.
- // Bug 1273358 exists to fix this.
- Assert.deepEqual(result.defaultRemoved, ["social-share-button"]);
-
- // And mochi insists there's only a single window with a single tab when
- // starting a test, so check that for good measure.
- Assert.deepEqual(result.visibleTabs, [1]);
-}
diff --git a/browser/modules/test/browser_BrowserUITelemetry_sidebar.js b/browser/modules/test/browser_BrowserUITelemetry_sidebar.js
deleted file mode 100644
index 5f19eabd5..000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_sidebar.js
+++ /dev/null
@@ -1,56 +0,0 @@
-// Test the sidebar counters in BrowserUITelemetry.
-"use strict";
-
-const { BrowserUITelemetry: BUIT } = Cu.import("resource:///modules/BrowserUITelemetry.jsm", {});
-
-add_task(function* testSidebarOpenClose() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- yield SidebarUI.show("viewTabsSidebar");
-
- let counts = BUIT._countableEvents[BUIT.currentBucket];
-
- Assert.deepEqual(counts, { sidebar: { viewTabsSidebar: { show: 1 } } });
- yield SidebarUI.hide();
- Assert.deepEqual(counts, { sidebar: { viewTabsSidebar: { show: 1, hide: 1 } } });
-
- yield SidebarUI.show("viewBookmarksSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 1, hide: 1 },
- viewBookmarksSidebar: { show: 1 },
- }
- });
- // Re-open the tabs sidebar while bookmarks is open - bookmarks should
- // record a close.
- yield SidebarUI.show("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 2, hide: 1 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- yield SidebarUI.hide();
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 2, hide: 2 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- // Toggle - this will re-open viewTabsSidebar
- yield SidebarUI.toggle("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 3, hide: 2 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- yield SidebarUI.toggle("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 3, hide: 3 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
-});
diff --git a/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js b/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
deleted file mode 100644
index d3e1eac57..000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
+++ /dev/null
@@ -1,114 +0,0 @@
-// Test the SyncedTabs counters in BrowserUITelemetry.
-"use strict";
-
-const { BrowserUITelemetry: BUIT } = Cu.import("resource:///modules/BrowserUITelemetry.jsm", {});
-const {SyncedTabs} = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-
-function mockSyncedTabs() {
- // Mock SyncedTabs.jsm
- let mockedInternal = {
- get isConfiguredToSyncTabs() { return true; },
- getTabClients() {
- return Promise.resolve([
- {
- id: "guid_desktop",
- type: "client",
- name: "My Desktop",
- tabs: [
- {
- title: "http://example.com/10",
- lastUsed: 10, // the most recent
- },
- ],
- }
- ]);
- },
- syncTabs() {
- return Promise.resolve();
- },
- hasSyncedThisSession: true,
- };
-
- let oldInternal = SyncedTabs._internal;
- SyncedTabs._internal = mockedInternal;
-
- // configure our broadcasters so we are in the right state.
- document.getElementById("sync-reauth-state").hidden = true;
- document.getElementById("sync-setup-state").hidden = true;
- document.getElementById("sync-syncnow-state").hidden = false;
-
- registerCleanupFunction(() => {
- SyncedTabs._internal = oldInternal;
-
- document.getElementById("sync-reauth-state").hidden = true;
- document.getElementById("sync-setup-state").hidden = false;
- document.getElementById("sync-syncnow-state").hidden = true;
- });
-}
-
-mockSyncedTabs();
-
-function promiseTabsUpdated() {
- return new Promise(resolve => {
- Services.obs.addObserver(function onNotification(aSubject, aTopic, aData) {
- Services.obs.removeObserver(onNotification, aTopic);
- resolve();
- }, "synced-tabs-menu:test:tabs-updated", false);
- });
-}
-
-add_task(function* test_menu() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- let tabsUpdated = promiseTabsUpdated();
-
- // check the button's functionality
- yield PanelUI.show();
-
- let syncButton = document.getElementById("sync-button");
- syncButton.click();
-
- yield tabsUpdated;
- // Get our 1 tab and click on it.
- let tabList = document.getElementById("PanelUI-remotetabs-tabslist");
- let tabEntry = tabList.firstChild.nextSibling;
- tabEntry.click();
-
- let counts = BUIT._countableEvents[BUIT.currentBucket];
- Assert.deepEqual(counts, {
- "click-builtin-item": { "sync-button": { left: 1 } },
- "synced-tabs": { open: { "toolbarbutton-subview": 1 } },
- });
-});
-
-add_task(function* test_sidebar() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- yield SidebarUI.show('viewTabsSidebar');
-
- let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
-
- syncedTabsDeckComponent._accountStatus = () => Promise.resolve(true);
-
- // Once the tabs container has been selected (which here means "'selected'
- // added to the class list") we are ready to test.
- let container = SidebarUI.browser.contentDocument.querySelector(".tabs-container");
- let promiseUpdated = BrowserTestUtils.waitForAttribute("class", container);
-
- yield syncedTabsDeckComponent.updatePanel();
- yield promiseUpdated;
-
- let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- let tab = selectedPanel.querySelector(".tab");
- tab.click();
- let counts = BUIT._countableEvents[BUIT.currentBucket];
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 1 },
- },
- "synced-tabs": { open: { sidebar: 1 } }
- });
- yield SidebarUI.hide();
-});
diff --git a/browser/modules/test/browser_ContentSearch.js b/browser/modules/test/browser_ContentSearch.js
deleted file mode 100644
index 97bd6ac51..000000000
--- a/browser/modules/test/browser_ContentSearch.js
+++ /dev/null
@@ -1,425 +0,0 @@
-/* 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/. */
-
-const TEST_MSG = "ContentSearchTest";
-const CONTENT_SEARCH_MSG = "ContentSearch";
-const TEST_CONTENT_SCRIPT_BASENAME = "contentSearch.js";
-
-// This timeout is absurdly high to avoid random failures like bug 1087120.
-// That bug was reported when the timeout was 5 seconds, so let's try 10.
-const SUGGESTIONS_TIMEOUT = 10000;
-
-var gMsgMan;
-/* eslint no-undef:"error" */
-/* import-globals-from ../../components/search/test/head.js */
-Services.scriptloader.loadSubScript(
- "chrome://mochitests/content/browser/browser/components/search/test/head.js",
- this);
-
-let originalEngine = Services.search.currentEngine;
-
-add_task(function* setup() {
- yield promiseNewEngine("testEngine.xml", {
- setAsCurrent: true,
- testPath: "chrome://mochitests/content/browser/browser/components/search/test/",
- });
-
- registerCleanupFunction(() => {
- Services.search.currentEngine = originalEngine;
- });
-});
-
-add_task(function* GetState() {
- yield addTab();
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetState",
- });
- let msg = yield waitForTestMsg("State");
- checkMsg(msg, {
- type: "State",
- data: yield currentStateObj(),
- });
-});
-
-add_task(function* SetCurrentEngine() {
- yield addTab();
- let newCurrentEngine = null;
- let oldCurrentEngine = Services.search.currentEngine;
- let engines = Services.search.getVisibleEngines();
- for (let engine of engines) {
- if (engine != oldCurrentEngine) {
- newCurrentEngine = engine;
- break;
- }
- }
- if (!newCurrentEngine) {
- info("Couldn't find a non-selected search engine, " +
- "skipping this part of the test");
- return;
- }
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "SetCurrentEngine",
- data: newCurrentEngine.name,
- });
- let deferred = Promise.defer();
- Services.obs.addObserver(function obs(subj, topic, data) {
- info("Test observed " + data);
- if (data == "engine-current") {
- ok(true, "Test observed engine-current");
- Services.obs.removeObserver(obs, "browser-search-engine-modified");
- deferred.resolve();
- }
- }, "browser-search-engine-modified", false);
- let searchPromise = waitForTestMsg("CurrentEngine");
- info("Waiting for test to observe engine-current...");
- yield deferred.promise;
- let msg = yield searchPromise;
- checkMsg(msg, {
- type: "CurrentEngine",
- data: yield currentEngineObj(newCurrentEngine),
- });
-
- Services.search.currentEngine = oldCurrentEngine;
- msg = yield waitForTestMsg("CurrentEngine");
- checkMsg(msg, {
- type: "CurrentEngine",
- data: yield currentEngineObj(oldCurrentEngine),
- });
-});
-
-add_task(function* modifyEngine() {
- yield addTab();
- let engine = Services.search.currentEngine;
- let oldAlias = engine.alias;
- engine.alias = "ContentSearchTest";
- let msg = yield waitForTestMsg("CurrentState");
- checkMsg(msg, {
- type: "CurrentState",
- data: yield currentStateObj(),
- });
- engine.alias = oldAlias;
- msg = yield waitForTestMsg("CurrentState");
- checkMsg(msg, {
- type: "CurrentState",
- data: yield currentStateObj(),
- });
-});
-
-add_task(function* search() {
- yield addTab();
- let engine = Services.search.currentEngine;
- let data = {
- engineName: engine.name,
- searchString: "ContentSearchTest",
- healthReportKey: "ContentSearchTest",
- searchPurpose: "ContentSearchTest",
- };
- let submissionURL =
- engine.getSubmission(data.searchString, "", data.whence).uri.spec;
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "Search",
- data: data,
- expectedURL: submissionURL,
- });
- let msg = yield waitForTestMsg("loadStopped");
- Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
-});
-
-add_task(function* searchInBackgroundTab() {
- // This test is like search(), but it opens a new tab after starting a search
- // in another. In other words, it performs a search in a background tab. The
- // search page should be loaded in the same tab that performed the search, in
- // the background tab.
- yield addTab();
- let engine = Services.search.currentEngine;
- let data = {
- engineName: engine.name,
- searchString: "ContentSearchTest",
- healthReportKey: "ContentSearchTest",
- searchPurpose: "ContentSearchTest",
- };
- let submissionURL =
- engine.getSubmission(data.searchString, "", data.whence).uri.spec;
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "Search",
- data: data,
- expectedURL: submissionURL,
- });
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- registerCleanupFunction(() => gBrowser.removeTab(newTab));
-
- let msg = yield waitForTestMsg("loadStopped");
- Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
-});
-
-add_task(function* badImage() {
- yield addTab();
- // If the bad image URI caused an exception to be thrown within ContentSearch,
- // then we'll hang waiting for the CurrentState responses triggered by the new
- // engine. That's what we're testing, and obviously it shouldn't happen.
- let vals = yield waitForNewEngine("contentSearchBadImage.xml", 1);
- let engine = vals[0];
- let finalCurrentStateMsg = vals[vals.length - 1];
- let expectedCurrentState = yield currentStateObj();
- let expectedEngine =
- expectedCurrentState.engines.find(e => e.name == engine.name);
- ok(!!expectedEngine, "Sanity check: engine should be in expected state");
- ok(expectedEngine.iconBuffer === null,
- "Sanity check: icon array buffer of engine in expected state " +
- "should be null: " + expectedEngine.iconBuffer);
- checkMsg(finalCurrentStateMsg, {
- type: "CurrentState",
- data: expectedCurrentState,
- });
- // Removing the engine triggers a final CurrentState message. Wait for it so
- // it doesn't trip up subsequent tests.
- Services.search.removeEngine(engine);
- yield waitForTestMsg("CurrentState");
-});
-
-add_task(function* GetSuggestions_AddFormHistoryEntry_RemoveFormHistoryEntry() {
- yield addTab();
-
- // Add the test engine that provides suggestions.
- let vals = yield waitForNewEngine("contentSearchSuggestions.xml", 0);
- let engine = vals[0];
-
- let searchStr = "browser_ContentSearch.js-suggestions-";
-
- // Add a form history suggestion and wait for Satchel to notify about it.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "AddFormHistoryEntry",
- data: searchStr + "form",
- });
- let deferred = Promise.defer();
- Services.obs.addObserver(function onAdd(subj, topic, data) {
- if (data == "formhistory-add") {
- Services.obs.removeObserver(onAdd, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
- yield deferred.promise;
-
- // Send GetSuggestions using the test engine. Its suggestions should appear
- // in the remote suggestions in the Suggestions response below.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetSuggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- remoteTimeout: SUGGESTIONS_TIMEOUT,
- },
- });
-
- // Check the Suggestions response.
- let msg = yield waitForTestMsg("Suggestions");
- checkMsg(msg, {
- type: "Suggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- formHistory: [searchStr + "form"],
- remote: [searchStr + "foo", searchStr + "bar"],
- },
- });
-
- // Delete the form history suggestion and wait for Satchel to notify about it.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "RemoveFormHistoryEntry",
- data: searchStr + "form",
- });
- deferred = Promise.defer();
- Services.obs.addObserver(function onRemove(subj, topic, data) {
- if (data == "formhistory-remove") {
- Services.obs.removeObserver(onRemove, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
- yield deferred.promise;
-
- // Send GetSuggestions again.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetSuggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- remoteTimeout: SUGGESTIONS_TIMEOUT,
- },
- });
-
- // The formHistory suggestions in the Suggestions response should be empty.
- msg = yield waitForTestMsg("Suggestions");
- checkMsg(msg, {
- type: "Suggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- formHistory: [],
- remote: [searchStr + "foo", searchStr + "bar"],
- },
- });
-
- // Finally, clean up by removing the test engine.
- Services.search.removeEngine(engine);
- yield waitForTestMsg("CurrentState");
-});
-
-function buffersEqual(actualArrayBuffer, expectedArrayBuffer) {
- let expectedView = new Int8Array(expectedArrayBuffer);
- let actualView = new Int8Array(actualArrayBuffer);
- for (let i = 0; i < expectedView.length; i++) {
- if (actualView[i] != expectedView[i]) {
- return false;
- }
- }
- return true;
-}
-
-function arrayBufferEqual(actualArrayBuffer, expectedArrayBuffer) {
- ok(actualArrayBuffer instanceof ArrayBuffer, "Actual value is ArrayBuffer.");
- ok(expectedArrayBuffer instanceof ArrayBuffer, "Expected value is ArrayBuffer.");
- Assert.equal(actualArrayBuffer.byteLength, expectedArrayBuffer.byteLength,
- "Array buffers have the same length.");
- ok(buffersEqual(actualArrayBuffer, expectedArrayBuffer), "Buffers are equal.");
-}
-
-function checkArrayBuffers(actual, expected) {
- if (actual instanceof ArrayBuffer) {
- arrayBufferEqual(actual, expected);
- }
- if (typeof actual == "object") {
- for (let i in actual) {
- checkArrayBuffers(actual[i], expected[i]);
- }
- }
-}
-
-function checkMsg(actualMsg, expectedMsgData) {
- let actualMsgData = actualMsg.data;
- SimpleTest.isDeeply(actualMsg.data, expectedMsgData, "Checking message");
-
- // Engines contain ArrayBuffers which we have to compare byte by byte and
- // not as Objects (like SimpleTest.isDeeply does).
- checkArrayBuffers(actualMsgData, expectedMsgData);
-}
-
-function waitForMsg(name, type) {
- let deferred = Promise.defer();
- info("Waiting for " + name + " message " + type + "...");
- gMsgMan.addMessageListener(name, function onMsg(msg) {
- info("Received " + name + " message " + msg.data.type + "\n");
- if (msg.data.type == type) {
- gMsgMan.removeMessageListener(name, onMsg);
- deferred.resolve(msg);
- }
- });
- return deferred.promise;
-}
-
-function waitForTestMsg(type) {
- return waitForMsg(TEST_MSG, type);
-}
-
-function waitForNewEngine(basename, numImages) {
- info("Waiting for engine to be added: " + basename);
-
- // Wait for the search events triggered by adding the new engine.
- // engine-added engine-loaded
- let expectedSearchEvents = ["CurrentState", "CurrentState"];
- // engine-changed for each of the images
- for (let i = 0; i < numImages; i++) {
- expectedSearchEvents.push("CurrentState");
- }
- let eventPromises = expectedSearchEvents.map(e => waitForTestMsg(e));
-
- // Wait for addEngine().
- let addDeferred = Promise.defer();
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- addDeferred.resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- addDeferred.reject();
- },
- });
-
- return Promise.all([addDeferred.promise].concat(eventPromises));
-}
-
-function addTab() {
- let deferred = Promise.defer();
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- let url = getRootDirectory(gTestPath) + TEST_CONTENT_SCRIPT_BASENAME;
- gMsgMan = tab.linkedBrowser.messageManager;
- gMsgMan.sendAsyncMessage(CONTENT_SEARCH_MSG, {
- type: "AddToWhitelist",
- data: ["about:blank"],
- });
- waitForMsg(CONTENT_SEARCH_MSG, "AddToWhitelistAck").then(() => {
- gMsgMan.loadFrameScript(url, false);
- deferred.resolve();
- });
- }, true);
- registerCleanupFunction(() => gBrowser.removeTab(tab));
- return deferred.promise;
-}
-
-var currentStateObj = Task.async(function* () {
- let state = {
- engines: [],
- currentEngine: yield currentEngineObj(),
- };
- for (let engine of Services.search.getVisibleEngines()) {
- let uri = engine.getIconURLBySize(16, 16);
- state.engines.push({
- name: engine.name,
- iconBuffer: yield arrayBufferFromDataURI(uri),
- hidden: false,
- });
- }
- return state;
-});
-
-var currentEngineObj = Task.async(function* () {
- let engine = Services.search.currentEngine;
- let uriFavicon = engine.getIconURLBySize(16, 16);
- let bundle = Services.strings.createBundle("chrome://global/locale/autocomplete.properties");
- return {
- name: engine.name,
- placeholder: bundle.formatStringFromName("searchWithEngine", [engine.name], 1),
- iconBuffer: yield arrayBufferFromDataURI(uriFavicon),
- };
-});
-
-function arrayBufferFromDataURI(uri) {
- if (!uri) {
- return Promise.resolve(null);
- }
- let deferred = Promise.defer();
- let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
- createInstance(Ci.nsIXMLHttpRequest);
- xhr.open("GET", uri, true);
- xhr.responseType = "arraybuffer";
- xhr.onerror = () => {
- deferred.resolve(null);
- };
- xhr.onload = () => {
- deferred.resolve(xhr.response);
- };
- try {
- xhr.send();
- }
- catch (err) {
- return Promise.resolve(null);
- }
- return deferred.promise;
-}
diff --git a/browser/modules/test/browser_NetworkPrioritizer.js b/browser/modules/test/browser_NetworkPrioritizer.js
deleted file mode 100644
index 91557b0fd..000000000
--- a/browser/modules/test/browser_NetworkPrioritizer.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/* 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/. */
-
-/** Tests for NetworkPrioritizer.jsm (Bug 514490) **/
-
-const LOWEST = Ci.nsISupportsPriority.PRIORITY_LOWEST;
-const LOW = Ci.nsISupportsPriority.PRIORITY_LOW;
-const NORMAL = Ci.nsISupportsPriority.PRIORITY_NORMAL;
-const HIGH = Ci.nsISupportsPriority.PRIORITY_HIGH;
-const HIGHEST = Ci.nsISupportsPriority.PRIORITY_HIGHEST;
-
-const DELTA = NORMAL - LOW; // lower value means higher priority
-
-// Test helper functions.
-// getPriority and setPriority can take a tab or a Browser
-function* getPriority(aBrowser) {
- if (aBrowser.localName == "tab")
- aBrowser = aBrowser.linkedBrowser;
-
- return yield ContentTask.spawn(aBrowser, null, function* () {
- return docShell.QueryInterface(Components.interfaces.nsIWebNavigation)
- .QueryInterface(Components.interfaces.nsIDocumentLoader)
- .loadGroup
- .QueryInterface(Components.interfaces.nsISupportsPriority)
- .priority;
- });
-}
-
-function* setPriority(aBrowser, aPriority) {
- if (aBrowser.localName == "tab")
- aBrowser = aBrowser.linkedBrowser;
-
- yield ContentTask.spawn(aBrowser, aPriority, function* (aPriority) {
- docShell.QueryInterface(Components.interfaces.nsIWebNavigation)
- .QueryInterface(Components.interfaces.nsIDocumentLoader)
- .loadGroup
- .QueryInterface(Ci.nsISupportsPriority)
- .priority = aPriority;
- });
-}
-
-function* isWindowState(aWindow, aTabPriorities) {
- let browsers = aWindow.gBrowser.browsers;
- // Make sure we have the right number of tabs & priorities
- is(browsers.length, aTabPriorities.length,
- "Window has expected number of tabs");
- // aState should be in format [ priority, priority, priority ]
- for (let i = 0; i < browsers.length; i++) {
- is(yield getPriority(browsers[i]), aTabPriorities[i],
- "Tab " + i + " had expected priority");
- }
-}
-
-function promiseWaitForFocus(aWindow) {
- return new Promise((resolve) => {
- waitForFocus(resolve, aWindow);
- });
-}
-
-add_task(function*() {
- // This is the real test. It creates multiple tabs & windows, changes focus,
- // closes windows/tabs to make sure we behave correctly.
- // This test assumes that no priorities have been adjusted and the loadgroup
- // priority starts at 0.
-
- // Call window "window_A" to make the test easier to follow
- let window_A = window;
-
- // Test 1 window, 1 tab case.
- yield isWindowState(window_A, [HIGH]);
-
- // Exising tab is tab_A1
- let tab_A2 = window_A.gBrowser.addTab("http://example.com");
- let tab_A3 = window_A.gBrowser.addTab("about:config");
- yield BrowserTestUtils.browserLoaded(tab_A3.linkedBrowser);
-
- // tab_A2 isn't focused yet
- yield isWindowState(window_A, [HIGH, NORMAL, NORMAL]);
-
- // focus tab_A2 & make sure priority got updated
- window_A.gBrowser.selectedTab = tab_A2;
- yield isWindowState(window_A, [NORMAL, HIGH, NORMAL]);
-
- window_A.gBrowser.removeTab(tab_A2);
- // Next tab is auto selected synchronously as part of removeTab, and we
- // expect the priority to be updated immediately.
- yield isWindowState(window_A, [NORMAL, HIGH]);
-
- // Open another window then play with focus
- let window_B = yield BrowserTestUtils.openNewBrowserWindow();
-
- yield promiseWaitForFocus(window_B);
- yield isWindowState(window_A, [LOW, NORMAL]);
- yield isWindowState(window_B, [HIGH]);
-
- yield promiseWaitForFocus(window_A);
- yield isWindowState(window_A, [NORMAL, HIGH]);
- yield isWindowState(window_B, [NORMAL]);
-
- yield promiseWaitForFocus(window_B);
- yield isWindowState(window_A, [LOW, NORMAL]);
- yield isWindowState(window_B, [HIGH]);
-
- // Cleanup
- window_A.gBrowser.removeTab(tab_A3);
- yield BrowserTestUtils.closeWindow(window_B);
-});
-
-add_task(function*() {
- // This is more a test of nsLoadGroup and how it handles priorities. But since
- // we depend on its behavior, it's good to test it. This is testing that there
- // are no errors if we adjust beyond nsISupportsPriority's bounds.
-
- yield promiseWaitForFocus();
-
- let tab1 = gBrowser.tabs[0];
- let oldPriority = yield getPriority(tab1);
-
- // Set the priority of tab1 to the lowest possible. Selecting the other tab
- // will try to lower it
- yield setPriority(tab1, LOWEST);
-
- let tab2 = gBrowser.addTab("http://example.com");
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
- gBrowser.selectedTab = tab2;
- is(yield getPriority(tab1), LOWEST - DELTA, "Can adjust priority beyond 'lowest'");
-
- // Now set priority to "highest" and make sure that no errors occur.
- yield setPriority(tab1, HIGHEST);
- gBrowser.selectedTab = tab1;
-
- is(yield getPriority(tab1), HIGHEST + DELTA, "Can adjust priority beyond 'highest'");
-
- // Cleanup
- gBrowser.removeTab(tab2);
- yield setPriority(tab1, oldPriority);
-});
-
-add_task(function*() {
- // This tests that the priority doesn't get lost when switching the browser's remoteness
-
- if (!gMultiProcessBrowser) {
- return;
- }
-
- let browser = gBrowser.selectedBrowser;
-
- browser.loadURI("http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(browser.isRemoteBrowser, "web page should be loaded in remote browser");
- is(yield getPriority(browser), HIGH, "priority of selected tab should be 'high'");
-
- browser.loadURI("about:rights");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(!browser.isRemoteBrowser, "about:rights should switch browser to non-remote");
- is(yield getPriority(browser), HIGH,
- "priority of selected tab should be 'high' when going from remote to non-remote");
-
- browser.loadURI("http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(browser.isRemoteBrowser, "going from about:rights to web page should switch browser to remote");
- is(yield getPriority(browser), HIGH,
- "priority of selected tab should be 'high' when going from non-remote to remote");
-});
diff --git a/browser/modules/test/browser_PermissionUI.js b/browser/modules/test/browser_PermissionUI.js
deleted file mode 100644
index 006bc5e66..000000000
--- a/browser/modules/test/browser_PermissionUI.js
+++ /dev/null
@@ -1,445 +0,0 @@
-/**
- * These tests test the ability for the PermissionUI module to open
- * permission prompts to the user. It also tests to ensure that
- * add-ons can introduce their own permission prompts.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Integration.jsm", this);
-Cu.import("resource:///modules/PermissionUI.jsm", this);
-
-/**
- * Given a <xul:browser> at some non-internal web page,
- * return something that resembles an nsIContentPermissionRequest,
- * using the browsers currently loaded document to get a principal.
- *
- * @param browser (<xul:browser>)
- * The browser that we'll create a nsIContentPermissionRequest
- * for.
- * @returns A nsIContentPermissionRequest-ish object.
- */
-function makeMockPermissionRequest(browser) {
- let result = {
- types: null,
- principal: browser.contentPrincipal,
- requester: null,
- _cancelled: false,
- cancel() {
- this._cancelled = true;
- },
- _allowed: false,
- allow() {
- this._allowed = true;
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionRequest]),
- };
-
- // In the e10s-case, nsIContentPermissionRequest will have
- // element defined. window is defined otherwise.
- if (browser.isRemoteBrowser) {
- result.element = browser;
- } else {
- result.window = browser.contentWindow;
- }
-
- return result;
-}
-
-/**
- * For an opened PopupNotification, clicks on the main action,
- * and waits for the panel to fully close.
- *
- * @return {Promise}
- * Resolves once the panel has fired the "popuphidden"
- * event.
- */
-function clickMainAction() {
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- let popupNotification = getPopupNotificationNode();
- popupNotification.button.click();
- return removePromise;
-}
-
-/**
- * For an opened PopupNotification, clicks on a secondary action,
- * and waits for the panel to fully close.
- *
- * @param {int} index
- * The 0-indexed index of the secondary menuitem to choose.
- * @return {Promise}
- * Resolves once the panel has fired the "popuphidden"
- * event.
- */
-function clickSecondaryAction(index) {
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- let popupNotification = getPopupNotificationNode();
- let menuitems = popupNotification.children;
- menuitems[index].click();
- return removePromise;
-}
-
-/**
- * Makes sure that 1 (and only 1) <xul:popupnotification> is being displayed
- * by PopupNotification, and then returns that <xul:popupnotification>.
- *
- * @return {<xul:popupnotification>}
- */
-function getPopupNotificationNode() {
- // PopupNotification is a bit overloaded here, so to be
- // clear, popupNotifications is a list of <xul:popupnotification>
- // nodes.
- let popupNotifications = PopupNotifications.panel.childNodes;
- Assert.equal(popupNotifications.length, 1,
- "Should be showing a <xul:popupnotification>");
- return popupNotifications[0];
-}
-
-/**
- * Tests the PermissionPromptForRequest prototype to ensure that a prompt
- * can be displayed. Does not test permission handling.
- */
-add_task(function* test_permission_prompt_for_request() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- let mainAction = {
- label: "Main",
- accessKey: "M",
- };
- let secondaryAction = {
- label: "Secondary",
- accessKey: "S",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
- Assert.ok(notification, "Should have gotten the notification");
-
- Assert.equal(notification.message, kTestMessage,
- "Should be showing the right message");
- Assert.equal(notification.mainAction.label, mainAction.label,
- "The main action should have the right label");
- Assert.equal(notification.mainAction.accessKey, mainAction.accessKey,
- "The main action should have the right access key");
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- Assert.equal(notification.secondaryActions[0].label, secondaryAction.label,
- "The secondary action should have the right label");
- Assert.equal(notification.secondaryActions[0].accessKey,
- secondaryAction.accessKey,
- "The secondary action should have the right access key");
- Assert.ok(notification.options.displayURI.equals(mockRequest.principal.URI),
- "Should be showing the URI of the requesting page");
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that if the PermissionPrompt sets displayURI to false in popupOptions,
- * then there is no URI shown on the popupnotification.
- */
-add_task(function* test_permission_prompt_for_popupOptions() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- let mainAction = {
- label: "Main",
- accessKey: "M",
- };
- let secondaryAction = {
- label: "Secondary",
- accessKey: "S",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- popupOptions: {
- displayURI: false,
- },
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- Assert.ok(!notification.options.displayURI,
- "Should not show the URI of the requesting page");
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that if the PermissionPrompt has the permissionKey
- * set that permissions can be set properly by the user. Also
- * ensures that callbacks for promptActions are properly fired.
- */
-add_task(function* test_with_permission_key() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- const kTestPermissionKey = "test-permission-key";
-
- let allowed = false;
- let mainAction = {
- label: "Allow",
- accessKey: "M",
- action: Ci.nsIPermissionManager.ALLOW_ACTION,
- expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION,
- callback: function() {
- allowed = true;
- }
- };
-
- let denied = false;
- let secondaryAction = {
- label: "Deny",
- accessKey: "D",
- action: Ci.nsIPermissionManager.DENY_ACTION,
- expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION,
- callback: function() {
- denied = true;
- }
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let principal = mockRequest.principal;
- registerCleanupFunction(function() {
- Services.perms.removeFromPrincipal(principal, kTestPermissionKey);
- });
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- permissionKey: kTestPermissionKey,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
- Assert.ok(notification, "Should have gotten the notification");
-
- let curPerm =
- Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.UNKNOWN_ACTION,
- "Should be no permission set to begin with.");
-
- // First test denying the permission request.
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- yield clickSecondaryAction(0);
- curPerm = Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.DENY_ACTION,
- "Should have denied the action");
- Assert.ok(denied, "The secondaryAction callback should have fired");
- Assert.ok(!allowed, "The mainAction callback should not have fired");
- Assert.ok(mockRequest._cancelled,
- "The request should have been cancelled");
- Assert.ok(!mockRequest._allowed,
- "The request should not have been allowed");
-
- // Clear the permission and pretend we never denied
- Services.perms.removeFromPrincipal(principal, kTestPermissionKey);
- denied = false;
- mockRequest._cancelled = false;
-
- // Bring the PopupNotification back up now...
- shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
-
- // Next test allowing the permission request.
- yield clickMainAction();
- curPerm = Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.ALLOW_ACTION,
- "Should have allowed the action");
- Assert.ok(!denied, "The secondaryAction callback should not have fired");
- Assert.ok(allowed, "The mainAction callback should have fired");
- Assert.ok(!mockRequest._cancelled,
- "The request should not have been cancelled");
- Assert.ok(mockRequest._allowed,
- "The request should have been allowed");
- });
-});
-
-/**
- * Tests that the onBeforeShow method will be called before
- * the popup appears.
- */
-add_task(function* test_on_before_show() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
-
- let mainAction = {
- label: "Test action",
- accessKey: "T",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let beforeShown = false;
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction],
- onBeforeShow() {
- beforeShown = true;
- }
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- Assert.ok(beforeShown, "Should have called onBeforeShown");
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that we can open a PermissionPrompt without wrapping a
- * nsIContentPermissionRequest.
- */
-add_task(function* test_no_request() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- let allowed = false;
- let mainAction = {
- label: "Allow",
- accessKey: "M",
- callback: function() {
- allowed = true;
- }
- };
-
- let denied = false;
- let secondaryAction = {
- label: "Deny",
- accessKey: "D",
- callback: function() {
- denied = true;
- }
- };
-
- const kTestMessage = "Test message with no request";
- let principal = browser.contentPrincipal;
- let beforeShown = false;
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptPrototype,
- notificationID: kTestNotificationID,
- principal,
- browser,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- onBeforeShow() {
- beforeShown = true;
- }
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- Assert.ok(beforeShown, "Should have called onBeforeShown");
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- Assert.equal(notification.message, kTestMessage,
- "Should be showing the right message");
- Assert.equal(notification.mainAction.label, mainAction.label,
- "The main action should have the right label");
- Assert.equal(notification.mainAction.accessKey, mainAction.accessKey,
- "The main action should have the right access key");
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- Assert.equal(notification.secondaryActions[0].label, secondaryAction.label,
- "The secondary action should have the right label");
- Assert.equal(notification.secondaryActions[0].accessKey,
- secondaryAction.accessKey,
- "The secondary action should have the right access key");
- Assert.ok(notification.options.displayURI.equals(principal.URI),
- "Should be showing the URI of the requesting page");
-
- // First test denying the permission request.
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- yield clickSecondaryAction(0);
- Assert.ok(denied, "The secondaryAction callback should have fired");
- Assert.ok(!allowed, "The mainAction callback should not have fired");
-
- shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
-
- // Next test allowing the permission request.
- yield clickMainAction();
- Assert.ok(allowed, "The mainAction callback should have fired");
- });
-});
diff --git a/browser/modules/test/browser_ProcessHangNotifications.js b/browser/modules/test/browser_ProcessHangNotifications.js
deleted file mode 100644
index 597be611a..000000000
--- a/browser/modules/test/browser_ProcessHangNotifications.js
+++ /dev/null
@@ -1,189 +0,0 @@
-
-Cu.import("resource://gre/modules/UpdateUtils.jsm");
-
-function getNotificationBox(aWindow) {
- return aWindow.document.getElementById("high-priority-global-notificationbox");
-}
-
-function promiseNotificationShown(aWindow, aName) {
- return new Promise((resolve) => {
- let notification = getNotificationBox(aWindow);
- notification.addEventListener("AlertActive", function active() {
- notification.removeEventListener("AlertActive", active, true);
- is(notification.allNotifications.length, 1, "Notification Displayed.");
- resolve(notification);
- });
- });
-}
-
-function promiseReportCallMade(aValue) {
- return new Promise((resolve) => {
- let old = gTestHangReport.testCallback;
- gTestHangReport.testCallback = function (val) {
- gTestHangReport.testCallback = old;
- is(aValue, val, "was the correct method call made on the hang report object?");
- resolve();
- };
- });
-}
-
-function pushPrefs(...aPrefs) {
- return new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
- resolve();
- });
-}
-
-function popPrefs() {
- return new Promise((resolve) => {
- SpecialPowers.popPrefEnv(resolve);
- resolve();
- });
-}
-
-let gTestHangReport = {
- SLOW_SCRIPT: 1,
- PLUGIN_HANG: 2,
-
- TEST_CALLBACK_CANCELED: 1,
- TEST_CALLBACK_TERMSCRIPT: 2,
- TEST_CALLBACK_TERMPLUGIN: 3,
-
- _hangType: 1,
- _tcb: function (aCallbackType) {},
-
- get hangType() {
- return this._hangType;
- },
-
- set hangType(aValue) {
- this._hangType = aValue;
- },
-
- set testCallback(aValue) {
- this._tcb = aValue;
- },
-
- QueryInterface: function (aIID) {
- if (aIID.equals(Components.interfaces.nsIHangReport) ||
- aIID.equals(Components.interfaces.nsISupports))
- return this;
- throw Components.results.NS_NOINTERFACE;
- },
-
- userCanceled: function () {
- this._tcb(this.TEST_CALLBACK_CANCELED);
- },
-
- terminateScript: function () {
- this._tcb(this.TEST_CALLBACK_TERMSCRIPT);
- },
-
- terminatePlugin: function () {
- this._tcb(this.TEST_CALLBACK_TERMPLUGIN);
- },
-
- isReportForBrowser: function(aFrameLoader) {
- return true;
- }
-};
-
-// on dev edition we add a button for js debugging of hung scripts.
-let buttonCount = (UpdateUtils.UpdateChannel == "aurora" ? 3 : 2);
-
-/**
- * Test if hang reports receive a terminate script callback when the user selects
- * stop in response to a script hang.
- */
-
-add_task(function* terminateScriptTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- // Click the "Stop It" button, we should get a terminate script callback
- gTestHangReport.hangType = gTestHangReport.SLOW_SCRIPT;
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_TERMSCRIPT);
- buttons[0].click();
- yield promise;
-});
-
-/**
- * Test if hang reports receive user canceled callbacks after a user selects wait
- * and the browser frees up from a script hang on its own.
- */
-
-add_task(function* waitForScriptTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- yield pushPrefs(["browser.hangNotification.waitPeriod", 1000]);
-
- function nocbcheck() {
- ok(false, "received a callback?");
- }
- let oldcb = gTestHangReport.testCallback;
- gTestHangReport.testCallback = nocbcheck;
- // Click the "Wait" button this time, we shouldn't get a callback at all.
- buttons[1].click();
- gTestHangReport.testCallback = oldcb;
-
- // send another hang pulse, we should not get a notification here
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- is(notification.currentNotification, null, "no notification should be visible");
-
- gTestHangReport.testCallback = function() {};
- Services.obs.notifyObservers(gTestHangReport, "clear-hang-report", null);
- gTestHangReport.testCallback = oldcb;
-
- yield popPrefs();
-});
-
-/**
- * Test if hang reports receive user canceled callbacks after the content
- * process stops sending hang notifications.
- */
-
-add_task(function* hangGoesAwayTest() {
- yield pushPrefs(["browser.hangNotification.expiration", 1000]);
-
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- yield promise;
-
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_CANCELED);
- Services.obs.notifyObservers(gTestHangReport, "clear-hang-report", null);
- yield promise;
-
- yield popPrefs();
-});
-
-/**
- * Tests if hang reports receive a terminate plugin callback when the user selects
- * stop in response to a plugin hang.
- */
-
-add_task(function* terminatePluginTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- // Click the "Stop It" button, we should get a terminate script callback
- gTestHangReport.hangType = gTestHangReport.PLUGIN_HANG;
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_TERMPLUGIN);
- buttons[0].click();
- yield promise;
-});
diff --git a/browser/modules/test/browser_SelfSupportBackend.js b/browser/modules/test/browser_SelfSupportBackend.js
deleted file mode 100644
index 9e2c1d181..000000000
--- a/browser/modules/test/browser_SelfSupportBackend.js
+++ /dev/null
@@ -1,214 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-// Pass an empty scope object to the import to prevent "leaked window property"
-// errors in tests.
-var Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-var PromiseUtils = Cu.import("resource://gre/modules/PromiseUtils.jsm", {}).PromiseUtils;
-var SelfSupportBackend =
- Cu.import("resource:///modules/SelfSupportBackend.jsm", {}).SelfSupportBackend;
-
-const PREF_SELFSUPPORT_ENABLED = "browser.selfsupport.enabled";
-const PREF_SELFSUPPORT_URL = "browser.selfsupport.url";
-const PREF_UITOUR_ENABLED = "browser.uitour.enabled";
-
-const TEST_WAIT_RETRIES = 60;
-
-const TEST_PAGE_URL = getRootDirectory(gTestPath) + "uitour.html";
-const TEST_PAGE_URL_HTTPS = TEST_PAGE_URL.replace("chrome://mochitests/content/", "https://example.com/");
-
-function sendSessionRestoredNotification() {
- let selfSupportBackendImpl =
- Cu.import("resource:///modules/SelfSupportBackend.jsm", {}).SelfSupportBackendInternal;
- selfSupportBackendImpl.observe(null, "sessionstore-windows-restored", null);
-}
-
-/**
- * Find a browser, with an IFRAME as parent, who has aURL as the source attribute.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Object} The browser element or null on failure.
- */
-function findSelfSupportBrowser(aURL) {
- let frames = Services.appShell.hiddenDOMWindow.document.querySelectorAll('iframe');
- for (let frame of frames) {
- try {
- let browser = frame.contentDocument.getElementById("win").querySelectorAll('browser')[0];
- let url = browser.getAttribute("src");
- if (url == aURL) {
- return browser;
- }
- } catch (e) {
- continue;
- }
- }
- return null;
-}
-
-/**
- * Wait for self support page to load.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Promise} Return a promise which is resolved when SelfSupport page is fully
- * loaded.
- */
-function promiseSelfSupportLoad(aURL) {
- return new Promise((resolve, reject) => {
- // Find the SelfSupport browser.
- let browserPromise = waitForConditionPromise(() => !!findSelfSupportBrowser(aURL),
- "SelfSupport browser not found.",
- TEST_WAIT_RETRIES);
-
- // Once found, append a "load" listener to catch page loads.
- browserPromise.then(() => {
- let browser = findSelfSupportBrowser(aURL);
- if (browser.contentDocument.readyState === "complete") {
- resolve(browser);
- } else {
- let handler = () => {
- browser.removeEventListener("load", handler, true);
- resolve(browser);
- };
- browser.addEventListener("load", handler, true);
- }
- }, reject);
- });
-}
-
-/**
- * Wait for self support to close.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Promise} Return a promise which is resolved when SelfSupport browser cannot
- * be found anymore.
- */
-function promiseSelfSupportClose(aURL) {
- return waitForConditionPromise(() => !findSelfSupportBrowser(aURL),
- "SelfSupport browser is still open.", TEST_WAIT_RETRIES);
-}
-
-/**
- * Prepare the test environment.
- */
-add_task(function* setupEnvironment() {
- // We always run the SelfSupportBackend in tests to check for weird behaviours.
- // Disable it to test its start-up.
- SelfSupportBackend.uninit();
-
- // Testing prefs are set via |user_pref|, so we need to get their value in order
- // to restore them.
- let selfSupportEnabled = Preferences.get(PREF_SELFSUPPORT_ENABLED, true);
- let uitourEnabled = Preferences.get(PREF_UITOUR_ENABLED, false);
- let selfSupportURL = Preferences.get(PREF_SELFSUPPORT_URL, "");
-
- // Enable the SelfSupport backend and set the page URL. We also make sure UITour
- // is enabled.
- Preferences.set(PREF_SELFSUPPORT_ENABLED, true);
- Preferences.set(PREF_UITOUR_ENABLED, true);
- Preferences.set(PREF_SELFSUPPORT_URL, TEST_PAGE_URL_HTTPS);
-
- // Whitelist the HTTPS page to use UITour.
- let pageURI = Services.io.newURI(TEST_PAGE_URL_HTTPS, null, null);
- Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION);
-
- registerCleanupFunction(() => {
- Services.perms.remove(pageURI, "uitour");
- Preferences.set(PREF_SELFSUPPORT_ENABLED, selfSupportEnabled);
- Preferences.set(PREF_UITOUR_ENABLED, uitourEnabled);
- Preferences.set(PREF_SELFSUPPORT_URL, selfSupportURL);
- });
-});
-
-/**
- * Test that the self support page can use the UITour API and close itself.
- */
-add_task(function* test_selfSupport() {
- // Initialise the SelfSupport backend and trigger the load.
- SelfSupportBackend.init();
-
- // SelfSupportBackend waits for "sessionstore-windows-restored" to start loading. Send it.
- info("Sending sessionstore-windows-restored");
- sendSessionRestoredNotification();
-
- // Wait for the SelfSupport page to load.
- info("Waiting for the SelfSupport local page to load.");
- let selfSupportBrowser = yield promiseSelfSupportLoad(TEST_PAGE_URL_HTTPS);
- Assert.ok(!!selfSupportBrowser, "SelfSupport browser must exist.");
-
- // Get a reference to the UITour API.
- info("Testing access to the UITour API.");
- let contentWindow =
- Cu.waiveXrays(selfSupportBrowser.contentDocument.defaultView);
- let uitourAPI = contentWindow.Mozilla.UITour;
-
- // Test the UITour API with a ping.
- let pingPromise = new Promise((resolve) => {
- uitourAPI.ping(resolve);
- });
- yield pingPromise;
- info("Ping succeeded");
-
- let observePromise = ContentTask.spawn(selfSupportBrowser, null, function* checkObserve() {
- yield new Promise(resolve => {
- let win = Cu.waiveXrays(content);
- win.Mozilla.UITour.observe((event, data) => {
- if (event != "Heartbeat:Engaged") {
- return;
- }
- Assert.equal(data.flowId, "myFlowID", "Check flowId");
- Assert.ok(!!data.timestamp, "Check timestamp");
- resolve(data);
- }, () => {});
- });
- });
-
- info("Notifying Heartbeat:Engaged");
- UITour.notify("Heartbeat:Engaged", {
- flowId: "myFlowID",
- timestamp: Date.now(),
- });
- yield observePromise;
- info("Observed in the hidden frame");
-
- // Close SelfSupport from content.
- contentWindow.close();
-
- // Wait until SelfSupport closes.
- info("Waiting for the SelfSupport to close.");
- yield promiseSelfSupportClose(TEST_PAGE_URL_HTTPS);
-
- // Find the SelfSupport browser, again. We don't expect to find it.
- selfSupportBrowser = findSelfSupportBrowser(TEST_PAGE_URL_HTTPS);
- Assert.ok(!selfSupportBrowser, "SelfSupport browser must not exist.");
-
- // We shouldn't need this, but let's keep it to make sure closing SelfSupport twice
- // doesn't create any problem.
- SelfSupportBackend.uninit();
-});
-
-/**
- * Test that SelfSupportBackend only allows HTTPS.
- */
-add_task(function* test_selfSupport_noHTTPS() {
- Preferences.set(PREF_SELFSUPPORT_URL, TEST_PAGE_URL);
-
- SelfSupportBackend.init();
-
- // SelfSupportBackend waits for "sessionstore-windows-restored" to start loading. Send it.
- info("Sending sessionstore-windows-restored");
- sendSessionRestoredNotification();
-
- // Find the SelfSupport browser. We don't expect to find it since we are not using https.
- let selfSupportBrowser = findSelfSupportBrowser(TEST_PAGE_URL);
- Assert.ok(!selfSupportBrowser, "SelfSupport browser must not exist.");
-
- // We shouldn't need this, but let's keep it to make sure closing SelfSupport twice
- // doesn't create any problem.
- SelfSupportBackend.uninit();
-})
diff --git a/browser/modules/test/browser_UnsubmittedCrashHandler.js b/browser/modules/test/browser_UnsubmittedCrashHandler.js
deleted file mode 100644
index 2d78c746b..000000000
--- a/browser/modules/test/browser_UnsubmittedCrashHandler.js
+++ /dev/null
@@ -1,680 +0,0 @@
-"use strict";
-
-/**
- * This suite tests the "unsubmitted crash report" notification
- * that is seen when we detect pending crash reports on startup.
- */
-
-const { UnsubmittedCrashHandler } =
- Cu.import("resource:///modules/ContentCrashHandlers.jsm", this);
-const { FileUtils } =
- Cu.import("resource://gre/modules/FileUtils.jsm", this);
-const { makeFakeAppDir } =
- Cu.import("resource://testing-common/AppData.jsm", this);
-const { OS } =
- Cu.import("resource://gre/modules/osfile.jsm", this);
-
-const DAY = 24 * 60 * 60 * 1000; // milliseconds
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-
-/**
- * Returns the directly where the browsing is storing the
- * pending crash reports.
- *
- * @returns nsIFile
- */
-function getPendingCrashReportDir() {
- // The fake UAppData directory that makeFakeAppDir provides
- // is just UAppData under the profile directory.
- return FileUtils.getDir("ProfD", [
- "UAppData",
- "Crash Reports",
- "pending",
- ], false);
-}
-
-/**
- * Synchronously deletes all entries inside the pending
- * crash report directory.
- */
-function clearPendingCrashReports() {
- let dir = getPendingCrashReportDir();
- let entries = dir.directoryEntries;
-
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Ci.nsIFile);
- if (entry.isFile()) {
- entry.remove(false);
- }
- }
-}
-
-/**
- * Randomly generates howMany crash report .dmp and .extra files
- * to put into the pending crash report directory. We're not
- * actually creating real crash reports here, just stubbing
- * out enough of the files to satisfy our notification and
- * submission code.
- *
- * @param howMany (int)
- * How many pending crash reports to put in the pending
- * crash report directory.
- * @param accessDate (Date, optional)
- * What date to set as the last accessed time on the created
- * crash reports. This defaults to the current date and time.
- * @returns Promise
- */
-function* createPendingCrashReports(howMany, accessDate) {
- let dir = getPendingCrashReportDir();
- if (!accessDate) {
- accessDate = new Date();
- }
-
- /**
- * Helper function for creating a file in the pending crash report
- * directory.
- *
- * @param fileName (string)
- * The filename for the crash report, not including the
- * extension. This is usually a UUID.
- * @param extension (string)
- * The file extension for the created file.
- * @param accessDate (Date)
- * The date to set lastAccessed to.
- * @param contents (string, optional)
- * Set this to whatever the file needs to contain, if anything.
- * @returns Promise
- */
- let createFile = (fileName, extension, accessDate, contents) => {
- let file = dir.clone();
- file.append(fileName + "." + extension);
- file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
- let promises = [OS.File.setDates(file.path, accessDate)];
-
- if (contents) {
- let encoder = new TextEncoder();
- let array = encoder.encode(contents);
- promises.push(OS.File.writeAtomic(file.path, array, {
- tmpPath: file.path + ".tmp",
- }));
- }
- return Promise.all(promises);
- }
-
- let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
- .getService(Ci.nsIUUIDGenerator);
- // CrashSubmit expects there to be a ServerURL key-value
- // pair in the .extra file, so we'll satisfy it.
- let extraFileContents = "ServerURL=" + SERVER_URL;
-
- return Task.spawn(function*() {
- let uuids = [];
- for (let i = 0; i < howMany; ++i) {
- let uuid = uuidGenerator.generateUUID().toString();
- // Strip the {}...
- uuid = uuid.substring(1, uuid.length - 1);
- yield createFile(uuid, "dmp", accessDate);
- yield createFile(uuid, "extra", accessDate, extraFileContents);
- uuids.push(uuid);
- }
- return uuids;
- });
-}
-
-/**
- * Returns a Promise that resolves once CrashSubmit starts sending
- * success notifications for crash submission matching the reportIDs
- * being passed in.
- *
- * @param reportIDs (Array<string>)
- * The IDs for the reports that we expect CrashSubmit to have sent.
- * @returns Promise
- */
-function waitForSubmittedReports(reportIDs) {
- let promises = [];
- for (let reportID of reportIDs) {
- let promise = TestUtils.topicObserved("crash-report-status", (subject, data) => {
- if (data == "success") {
- let propBag = subject.QueryInterface(Ci.nsIPropertyBag2);
- let dumpID = propBag.getPropertyAsAString("minidumpID");
- if (dumpID == reportID) {
- return true;
- }
- }
- return false;
- });
- promises.push(promise);
- }
- return Promise.all(promises);
-}
-
-/**
- * Returns a Promise that resolves once a .dmp.ignore file is created for
- * the crashes in the pending directory matching the reportIDs being
- * passed in.
- *
- * @param reportIDs (Array<string>)
- * The IDs for the reports that we expect CrashSubmit to have been
- * marked for ignoring.
- * @returns Promise
- */
-function waitForIgnoredReports(reportIDs) {
- let dir = getPendingCrashReportDir();
- let promises = [];
- for (let reportID of reportIDs) {
- let file = dir.clone();
- file.append(reportID + ".dmp.ignore");
- promises.push(OS.File.exists(file.path));
- }
- return Promise.all(promises);
-}
-
-let gNotificationBox;
-
-add_task(function* setup() {
- // Pending crash reports are stored in the UAppData folder,
- // which exists outside of the profile folder. In order to
- // not overwrite / clear pending crash reports for the poor
- // soul who runs this test, we use AppData.jsm to point to
- // a special made-up directory inside the profile
- // directory.
- yield makeFakeAppDir();
- // We'll assume that the notifications will be shown in the current
- // browser window's global notification box.
- gNotificationBox = document.getElementById("global-notificationbox");
-
- // If we happen to already be seeing the unsent crash report
- // notification, it's because the developer running this test
- // happened to have some unsent reports in their UAppDir.
- // We'll remove the notification without touching those reports.
- let notification =
- gNotificationBox.getNotificationWithValue("pending-crash-reports");
- if (notification) {
- notification.close();
- }
-
- let env = Cc["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- let oldServerURL = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- // nsBrowserGlue starts up UnsubmittedCrashHandler automatically
- // so at this point, it is initialized. It's possible that it
- // was initialized, but is preffed off, so it's inert, so we
- // shut it down, make sure it's preffed on, and then restart it.
- // Note that making the component initialize even when it's
- // disabled is an intentional choice, as this allows for easier
- // simulation of startup and shutdown.
- UnsubmittedCrashHandler.uninit();
- yield SpecialPowers.pushPrefEnv({
- set: [
- ["browser.crashReports.unsubmittedCheck.enabled", true],
- ],
- });
- UnsubmittedCrashHandler.init();
-
- registerCleanupFunction(function() {
- gNotificationBox = null;
- clearPendingCrashReports();
- env.set("MOZ_CRASHREPORTER_URL", oldServerURL);
- });
-});
-
-/**
- * Tests that if there are no pending crash reports, then the
- * notification will not show up.
- */
-add_task(function* test_no_pending_no_notification() {
- // Make absolutely sure there are no pending crash reports first...
- clearPendingCrashReports();
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should not be a notification if there are no " +
- "pending crash reports");
-});
-
-/**
- * Tests that there is a notification if there is one pending
- * crash report.
- */
-add_task(function* test_one_pending() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that there is a notification if there is more than one
- * pending crash report.
- */
-add_task(function* test_several_pending() {
- yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that there is no notification if the only pending crash
- * reports are over 28 days old. Also checks that if we put a newer
- * crash with that older set, that we can still get a notification.
- */
-add_task(function* test_several_pending() {
- // Let's create some crash reports from 30 days ago.
- let oldDate = new Date(Date.now() - (30 * DAY));
- yield createPendingCrashReports(3, oldDate);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should not be a notification if there are only " +
- "old pending crash reports");
- // Now let's create a new one and check again
- yield createPendingCrashReports(1);
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that the notification can submit a report.
- */
-add_task(function* test_can_submit() {
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the submit
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the first button.
- let submit = buttons[0];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash report");
- submit.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that the notification can submit multiple reports.
- */
-add_task(function* test_can_submit_several() {
- let reportIDs = yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the submit
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the first button.
- let submit = buttons[0];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash reports");
- submit.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that choosing "Send Always" flips the autoSubmit pref
- * and sends the pending crash reports.
- */
-add_task(function* test_can_submit_always() {
- let pref = "browser.crashReports.unsubmittedCheck.autoSubmit2";
- Assert.equal(Services.prefs.getBoolPref(pref), false,
- "We should not be auto-submitting by default");
-
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the send all
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the second button.
- let sendAll = buttons[1];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash reports");
- sendAll.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
-
- // Make sure the pref was set
- Assert.equal(Services.prefs.getBoolPref(pref), true,
- "The autoSubmit pref should have been set");
-
- // And revert back to default now.
- Services.prefs.clearUserPref(pref);
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if the user has chosen to automatically send
- * crash reports that no notification is displayed to the
- * user.
- */
-add_task(function* test_can_auto_submit() {
- yield SpecialPowers.pushPrefEnv({ set: [
- ["browser.crashReports.unsubmittedCheck.autoSubmit2", true],
- ]});
-
- let reportIDs = yield createPendingCrashReports(3);
- let promiseReports = waitForSubmittedReports(reportIDs);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null, "There should be no notification");
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
-
- clearPendingCrashReports();
- yield SpecialPowers.popPrefEnv();
-});
-
-/**
- * Tests that if the user chooses to dismiss the notification,
- * then the current pending requests won't cause the notification
- * to appear again in the future.
- */
-add_task(function* test_can_ignore() {
- let reportIDs = yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Dismiss the notification by clicking on the "X" button.
- let anonyNodes = document.getAnonymousNodes(notification)[0];
- let closeButton = anonyNodes.querySelector(".close-icon");
- closeButton.click();
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
- yield waitForIgnoredReports(reportIDs);
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null, "There should be no notification");
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if the notification is shown, then the
- * lastShownDate is set for today.
- */
-add_task(function* test_last_shown_date() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- let lastShownDate =
- UnsubmittedCrashHandler.prefs.getCharPref("lastShownDate");
- Assert.equal(today, lastShownDate,
- "Last shown date should be today.");
-
- UnsubmittedCrashHandler.prefs.clearUserPref("lastShownDate");
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if UnsubmittedCrashHandler is uninit with a
- * notification still being shown, that
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set to true.
- */
-add_task(function* test_shutdown_while_showing() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
- UnsubmittedCrashHandler.prefs.clearUserPref("shutdownWhileShowing");
- UnsubmittedCrashHandler.init();
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if UnsubmittedCrashHandler is uninit after
- * the notification has been closed, that
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * not set in prefs.
- */
-add_task(function* test_shutdown_while_not_showing() {
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Dismiss the notification by clicking on the "X" button.
- let anonyNodes = document.getAnonymousNodes(notification)[0];
- let closeButton = anonyNodes.querySelector(".close-icon");
- closeButton.click();
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- yield waitForIgnoredReports(reportIDs);
-
- UnsubmittedCrashHandler.uninit();
- Assert.throws(() => {
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- }, "We should have noticed that the notification had closed before " +
- "uninitting.");
- UnsubmittedCrashHandler.init();
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set and the lastShownDate is today, then we don't decrement
- * browser.crashReports.unsubmittedCheck.chancesUntilSuppress.
- */
-add_task(function* test_dont_decrement_chances_on_same_day() {
- let initChances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
- Assert.ok(initChances > 1, "We should start with at least 1 chance.");
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
-
- gNotificationBox.removeNotification(notification, true);
-
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- let lastShownDate =
- UnsubmittedCrashHandler.prefs.getCharPref("lastShownDate");
- Assert.equal(today, lastShownDate,
- "Last shown date should be today.");
-
- UnsubmittedCrashHandler.init();
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should still be a notification");
-
- let chances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
-
- Assert.equal(initChances, chances,
- "We should not have decremented chances.");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set and the lastShownDate is before today, then we decrement
- * browser.crashReports.unsubmittedCheck.chancesUntilSuppress.
- */
-add_task(function* test_decrement_chances_on_other_day() {
- let initChances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
- Assert.ok(initChances > 1, "We should start with at least 1 chance.");
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
-
- gNotificationBox.removeNotification(notification, true);
-
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
-
- // Now pretend that the notification was shown yesterday.
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("lastShownDate", yesterday);
-
- UnsubmittedCrashHandler.init();
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should still be a notification");
-
- let chances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
-
- Assert.equal(initChances - 1, chances,
- "We should have decremented our chances.");
- UnsubmittedCrashHandler.prefs.clearUserPref("chancesUntilSuppress");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if we've shutdown too many times showing the
- * notification, and we've run out of chances, then
- * browser.crashReports.unsubmittedCheck.suppressUntilDate is
- * set for some days into the future.
- */
-add_task(function* test_can_suppress_after_chances() {
- // Pretend that a notification was shown yesterday.
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("lastShownDate", yesterday);
- UnsubmittedCrashHandler.prefs.setBoolPref("shutdownWhileShowing", true);
- UnsubmittedCrashHandler.prefs.setIntPref("chancesUntilSuppress", 0);
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should be no notification if we've run out of chances");
-
- // We should have set suppressUntilDate into the future
- let suppressUntilDate =
- UnsubmittedCrashHandler.prefs.getCharPref("suppressUntilDate");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- Assert.ok(suppressUntilDate > today,
- "We should be suppressing until some days into the future.");
-
- UnsubmittedCrashHandler.prefs.clearUserPref("chancesUntilSuppress");
- UnsubmittedCrashHandler.prefs.clearUserPref("suppressUntilDate");
- UnsubmittedCrashHandler.prefs.clearUserPref("lastShownDate");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if there's a suppression date set, then no notification
- * will be shown even if there are pending crash reports.
- */
-add_task(function* test_suppression() {
- let future = UnsubmittedCrashHandler.dateString(new Date(Date.now() + (DAY * 5)));
- UnsubmittedCrashHandler.prefs.setCharPref("suppressUntilDate", future);
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-
- Assert.ok(UnsubmittedCrashHandler.suppressed,
- "The UnsubmittedCrashHandler should be suppressed.");
- UnsubmittedCrashHandler.prefs.clearUserPref("suppressUntilDate");
-
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-});
-
-/**
- * Tests that if there's a suppression date set, but we've exceeded
- * it, then we can show the notification again.
- */
-add_task(function* test_end_suppression() {
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("suppressUntilDate", yesterday);
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-
- Assert.ok(!UnsubmittedCrashHandler.suppressed,
- "The UnsubmittedCrashHandler should not be suppressed.");
- Assert.ok(!UnsubmittedCrashHandler.prefs.prefHasUserValue("suppressUntilDate"),
- "The suppression date should been cleared from preferences.");
-
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-});
diff --git a/browser/modules/test/browser_UsageTelemetry.js b/browser/modules/test/browser_UsageTelemetry.js
deleted file mode 100644
index a84f33a97..000000000
--- a/browser/modules/test/browser_UsageTelemetry.js
+++ /dev/null
@@ -1,268 +0,0 @@
-"use strict";
-
-const MAX_CONCURRENT_TABS = "browser.engagement.max_concurrent_tab_count";
-const TAB_EVENT_COUNT = "browser.engagement.tab_open_event_count";
-const MAX_CONCURRENT_WINDOWS = "browser.engagement.max_concurrent_window_count";
-const WINDOW_OPEN_COUNT = "browser.engagement.window_open_event_count";
-const TOTAL_URI_COUNT = "browser.engagement.total_uri_count";
-const UNIQUE_DOMAINS_COUNT = "browser.engagement.unique_domains_count";
-const UNFILTERED_URI_COUNT = "browser.engagement.unfiltered_uri_count";
-
-const TELEMETRY_SUBSESSION_TOPIC = "internal-telemetry-after-subsession-split";
-
-/**
- * Waits for the web progress listener associated with this tab to fire an
- * onLocationChange for a non-error page.
- *
- * @param {xul:browser} browser
- * A xul:browser.
- *
- * @return {Promise}
- * @resolves When navigating to a non-error page.
- */
-function browserLocationChanged(browser) {
- return new Promise(resolve => {
- let wpl = {
- onStateChange() {},
- onSecurityChange() {},
- onStatusChange() {},
- onLocationChange(aWebProgress, aRequest, aURI, aFlags) {
- if (!(aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE)) {
- browser.webProgress.removeProgressListener(filter);
- filter.removeProgressListener(wpl);
- resolve();
- }
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIWebProgressListener,
- Ci.nsIWebProgressListener2,
- ]),
- };
- const filter = Cc["@mozilla.org/appshell/component/browser-status-filter;1"]
- .createInstance(Ci.nsIWebProgress);
- filter.addProgressListener(wpl, Ci.nsIWebProgress.NOTIFY_ALL);
- browser.webProgress.addProgressListener(filter, Ci.nsIWebProgress.NOTIFY_ALL);
- });
-}
-
-/**
- * An helper that checks the value of a scalar if it's expected to be > 0,
- * otherwise makes sure that the scalar it's not reported.
- */
-let checkScalar = (scalars, scalarName, value, msg) => {
- if (value > 0) {
- is(scalars[scalarName], value, msg);
- return;
- }
- ok(!(scalarName in scalars), scalarName + " must not be reported.");
-};
-
-/**
- * Get a snapshot of the scalars and check them against the provided values.
- */
-let checkScalars = (countsObject) => {
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- // Check the expected values. Scalars that are never set must not be reported.
- checkScalar(scalars, MAX_CONCURRENT_TABS, countsObject.maxTabs,
- "The maximum tab count must match the expected value.");
- checkScalar(scalars, TAB_EVENT_COUNT, countsObject.tabOpenCount,
- "The number of open tab event count must match the expected value.");
- checkScalar(scalars, MAX_CONCURRENT_WINDOWS, countsObject.maxWindows,
- "The maximum window count must match the expected value.");
- checkScalar(scalars, WINDOW_OPEN_COUNT, countsObject.windowsOpenCount,
- "The number of window open event count must match the expected value.");
- checkScalar(scalars, TOTAL_URI_COUNT, countsObject.totalURIs,
- "The total URI count must match the expected value.");
- checkScalar(scalars, UNIQUE_DOMAINS_COUNT, countsObject.domainCount,
- "The unique domains count must match the expected value.");
- checkScalar(scalars, UNFILTERED_URI_COUNT, countsObject.totalUnfilteredURIs,
- "The unfiltered URI count must match the expected value.");
-};
-
-add_task(function* test_tabsAndWindows() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- let openedTabs = [];
- let expectedTabOpenCount = 0;
- let expectedWinOpenCount = 0;
- let expectedMaxTabs = 0;
- let expectedMaxWins = 0;
-
- // Add a new tab and check that the count is right.
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- expectedTabOpenCount = 1;
- expectedMaxTabs = 2;
- // This, and all the checks below, also check that initial pages (about:newtab, about:blank, ..)
- // are not counted by the total_uri_count and the unfiltered_uri_count probes.
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Add two new tabs in the same window.
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- expectedTabOpenCount += 2;
- expectedMaxTabs += 2;
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Add a new window and then some tabs in it. An empty new windows counts as a tab.
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- // The new window started with a new tab, so account for it.
- expectedTabOpenCount += 4;
- expectedWinOpenCount += 1;
- expectedMaxWins = 2;
- expectedMaxTabs += 4;
-
- // Remove a tab from the first window, the max shouldn't change.
- yield BrowserTestUtils.removeTab(openedTabs.pop());
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Remove all the extra windows and tabs.
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(win);
-
- // Make sure all the scalars still have the expected values.
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-});
-
-add_task(function* test_subsessionSplit() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // Add a new window (that will have 4 tabs).
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let openedTabs = [];
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:mozilla"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "http://www.example.com"));
-
- // Check that the scalars have the right values. We expect 2 unfiltered URI loads
- // (about:mozilla and www.example.com, but no about:blank) and 1 URI totalURIs
- // (only www.example.com).
- checkScalars({maxTabs: 5, tabOpenCount: 4, maxWindows: 2, windowsOpenCount: 1,
- totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 2});
-
- // Remove a tab.
- yield BrowserTestUtils.removeTab(openedTabs.pop());
-
- // Simulate a subsession split by clearing the scalars (via |snapshotScalars|) and
- // notifying the subsession split topic.
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN,
- true /* clearScalars */);
- Services.obs.notifyObservers(null, TELEMETRY_SUBSESSION_TOPIC, "");
-
- // After a subsession split, only the MAX_CONCURRENT_* scalars must be available
- // and have the correct value. No tabs, windows or URIs were opened so other scalars
- // must not be reported.
- checkScalars({maxTabs: 4, tabOpenCount: 0, maxWindows: 2, windowsOpenCount: 0,
- totalURIs: 0, domainCount: 0, totalUnfilteredURIs: 0});
-
- // Remove all the extra windows and tabs.
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(win);
-});
-
-add_task(function* test_URIAndDomainCounts() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- let checkCounts = (countsObject) => {
- // Get a snapshot of the scalars and then clear them.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- checkScalar(scalars, TOTAL_URI_COUNT, countsObject.totalURIs,
- "The URI scalar must contain the expected value.");
- checkScalar(scalars, UNIQUE_DOMAINS_COUNT, countsObject.domainCount,
- "The unique domains scalar must contain the expected value.");
- checkScalar(scalars, UNFILTERED_URI_COUNT, countsObject.totalUnfilteredURIs,
- "The unfiltered URI scalar must contain the expected value.");
- };
-
- // Check that about:blank doesn't get counted in the URI total.
- let firstTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- checkCounts({totalURIs: 0, domainCount: 0, totalUnfilteredURIs: 0});
-
- // Open a different page and check the counts.
- yield BrowserTestUtils.loadURI(firstTab.linkedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(firstTab.linkedBrowser);
- checkCounts({totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 1});
-
- // Activating a different tab must not increase the URI count.
- let secondTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- yield BrowserTestUtils.switchTab(gBrowser, firstTab);
- checkCounts({totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 1});
- yield BrowserTestUtils.removeTab(secondTab);
-
- // Open a new window and set the tab to a new address.
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 2, domainCount: 1, totalUnfilteredURIs: 2});
-
- // We should not count AJAX requests.
- const XHR_URL = "http://example.com/r";
- yield ContentTask.spawn(newWin.gBrowser.selectedBrowser, XHR_URL, function(url) {
- return new Promise(resolve => {
- var xhr = new content.window.XMLHttpRequest();
- xhr.open("GET", url);
- xhr.onload = () => resolve();
- xhr.send();
- });
- });
- checkCounts({totalURIs: 2, domainCount: 1, totalUnfilteredURIs: 2});
-
- // Check that we're counting page fragments.
- let loadingStopped = browserLocationChanged(newWin.gBrowser.selectedBrowser);
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://example.com/#2");
- yield loadingStopped;
- checkCounts({totalURIs: 3, domainCount: 1, totalUnfilteredURIs: 3});
-
- // Check that a different URI from the example.com domain doesn't increment the unique count.
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://test1.example.com/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 4, domainCount: 1, totalUnfilteredURIs: 4});
-
- // Make sure that the unique domains counter is incrementing for a different domain.
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "https://example.org/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 5});
-
- // Check that we only account for top level loads (e.g. we don't count URIs from
- // embedded iframes).
- yield ContentTask.spawn(newWin.gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let iframe = doc.createElement("iframe");
- let promiseIframeLoaded = ContentTaskUtils.waitForEvent(iframe, "load", false);
- iframe.src = "https://example.org/test";
- doc.body.insertBefore(iframe, doc.body.firstChild);
- yield promiseIframeLoaded;
- });
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 5});
-
- // Check that uncommon protocols get counted in the unfiltered URI probe.
- const TEST_PAGE =
- "data:text/html,<a id='target' href='%23par1'>Click me</a><a name='par1'>The paragraph.</a>";
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, TEST_PAGE);
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 6});
-
- // Clean up.
- yield BrowserTestUtils.removeTab(firstTab);
- yield BrowserTestUtils.closeWindow(newWin);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_content.js b/browser/modules/test/browser_UsageTelemetry_content.js
deleted file mode 100644
index 35c6b5a6d..000000000
--- a/browser/modules/test/browser_UsageTelemetry_content.js
+++ /dev/null
@@ -1,121 +0,0 @@
-"use strict";
-
-const BASE_PROBE_NAME = "browser.engagement.navigation.";
-const SCALAR_CONTEXT_MENU = BASE_PROBE_NAME + "contextmenu";
-const SCALAR_ABOUT_NEWTAB = BASE_PROBE_NAME + "about_newtab";
-
-add_task(function* setup() {
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // in content doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- yield SpecialPowers.pushPrefEnv({"set": [
- ["dom.select_events.enabled", true], // We want select events to be fired.
- ["toolkit.telemetry.enabled", true] // And Extended Telemetry to be enabled.
- ]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_context_menu() {
- // Let's reset the Telemetry data.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Open a new tab with a page containing some text.
- let tab =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/plain;charset=utf8,test%20search");
-
- info("Select all the text in the page.");
- yield ContentTask.spawn(tab.linkedBrowser, "", function*() {
- return new Promise(resolve => {
- content.document.addEventListener("selectionchange", () => resolve(), { once: true });
- content.document.getSelection().selectAllChildren(content.document.body);
- });
- });
-
- info("Open the context menu.");
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- BrowserTestUtils.synthesizeMouseAtCenter("body", { type: "contextmenu", button: 2 },
- gBrowser.selectedBrowser);
- yield popupPromise;
-
- info("Click on search.");
- let searchItem = contextMenu.getElementsByAttribute("id", "context-searchselect")[0];
- searchItem.click();
-
- info("Validate the search metrics.");
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_CONTEXT_MENU, "search", 1);
- Assert.equal(Object.keys(scalars[SCALAR_CONTEXT_MENU]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.contextmenu', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "contextmenu", null, {engine: "other-MozSearch"}]]);
-
- contextMenu.hidePopup();
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_about_newtab() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab", false);
- yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- yield ContentTaskUtils.waitForCondition(() => !content.document.hidden);
- });
-
- info("Trigger a simple serch, just text + enter.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield typeInSearchField(tab.linkedBrowser, "test query", "newtab-search-text");
- yield BrowserTestUtils.synthesizeKey("VK_RETURN", {}, tab.linkedBrowser);
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_ABOUT_NEWTAB, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_ABOUT_NEWTAB]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.newtab', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "about_newtab", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js b/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
deleted file mode 100644
index 1818ae5fd..000000000
--- a/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
+++ /dev/null
@@ -1,84 +0,0 @@
-"use strict";
-
-const SCALAR_ABOUT_HOME = "browser.engagement.navigation.about_home";
-
-add_task(function* setup() {
- // about:home uses IndexedDB. However, the test finishes too quickly and doesn't
- // allow it enougth time to save. So it throws. This disables all the uncaught
- // exception in this file and that's the reason why we split about:home tests
- // out of the other UsageTelemetry files.
- ignoreAllUncaughtExceptions();
-
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // in content doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_abouthome_simpleQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- info("Setup waiting for AboutHomeLoadSnippetsCompleted.");
- let promiseAboutHomeLoaded = new Promise(resolve => {
- tab.linkedBrowser.addEventListener("AboutHomeLoadSnippetsCompleted", function loadListener(event) {
- tab.linkedBrowser.removeEventListener("AboutHomeLoadSnippetsCompleted", loadListener, true);
- resolve();
- }, true, true);
- });
-
- info("Load about:home.");
- tab.linkedBrowser.loadURI("about:home");
- info("Wait for AboutHomeLoadSnippetsCompleted.");
- yield promiseAboutHomeLoaded;
-
- info("Trigger a simple serch, just test + enter.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield typeInSearchField(tab.linkedBrowser, "test query", "searchText");
- yield BrowserTestUtils.synthesizeKey("VK_RETURN", {}, tab.linkedBrowser);
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_ABOUT_HOME, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_ABOUT_HOME]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.abouthome', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "about_home", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_private_and_restore.js b/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
deleted file mode 100644
index 144a4a03f..000000000
--- a/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
+++ /dev/null
@@ -1,90 +0,0 @@
-"use strict";
-
-const MAX_CONCURRENT_TABS = "browser.engagement.max_concurrent_tab_count";
-const TAB_EVENT_COUNT = "browser.engagement.tab_open_event_count";
-const MAX_CONCURRENT_WINDOWS = "browser.engagement.max_concurrent_window_count";
-const WINDOW_OPEN_COUNT = "browser.engagement.window_open_event_count";
-const TOTAL_URI_COUNT = "browser.engagement.total_uri_count";
-const UNFILTERED_URI_COUNT = "browser.engagement.unfiltered_uri_count";
-const UNIQUE_DOMAINS_COUNT = "browser.engagement.unique_domains_count";
-
-function promiseBrowserStateRestored() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- Services.obs.removeObserver(observer, "sessionstore-browser-state-restored");
- resolve();
- }, "sessionstore-browser-state-restored", false);
- });
-}
-
-add_task(function* test_privateMode() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // Open a private window and load a website in it.
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield BrowserTestUtils.loadURI(privateWin.gBrowser.selectedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(privateWin.gBrowser.selectedBrowser);
-
- // Check that tab and window count is recorded.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- ok(!(TOTAL_URI_COUNT in scalars), "We should not track URIs in private mode.");
- ok(!(UNFILTERED_URI_COUNT in scalars), "We should not track URIs in private mode.");
- ok(!(UNIQUE_DOMAINS_COUNT in scalars), "We should not track unique domains in private mode.");
- is(scalars[TAB_EVENT_COUNT], 1, "The number of open tab event count must match the expected value.");
- is(scalars[MAX_CONCURRENT_TABS], 2, "The maximum tab count must match the expected value.");
- is(scalars[WINDOW_OPEN_COUNT], 1, "The number of window open event count must match the expected value.");
- is(scalars[MAX_CONCURRENT_WINDOWS], 2, "The maximum window count must match the expected value.");
-
- // Clean up.
- yield BrowserTestUtils.closeWindow(privateWin);
-});
-
-add_task(function* test_sessionRestore() {
- const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // The first window will be put into the already open window and the second
- // window will be opened with _openWindowWithState, which is the source of the problem.
- const state = {
- windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org" }], extData: { "uniq": 3785 } }
- ],
- selected: 1
- }
- ]
- };
-
- // Save the current session.
- let SessionStore =
- Cu.import("resource:///modules/sessionstore/SessionStore.jsm", {}).SessionStore;
-
- // Load the custom state and wait for SSTabRestored, as we want to make sure
- // that the URI counting code was hit.
- let tabRestored = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "SSTabRestored");
- SessionStore.setBrowserState(JSON.stringify(state));
- yield tabRestored;
-
- // Check that the URI is not recorded.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- ok(!(TOTAL_URI_COUNT in scalars), "We should not track URIs from restored sessions.");
- ok(!(UNFILTERED_URI_COUNT in scalars), "We should not track URIs from restored sessions.");
- ok(!(UNIQUE_DOMAINS_COUNT in scalars), "We should not track unique domains from restored sessions.");
-
- // Restore the original session and cleanup.
- let sessionRestored = promiseBrowserStateRestored();
- SessionStore.setBrowserState(JSON.stringify(state));
- yield sessionRestored;
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_searchbar.js b/browser/modules/test/browser_UsageTelemetry_searchbar.js
deleted file mode 100644
index 8aa3ceaee..000000000
--- a/browser/modules/test/browser_UsageTelemetry_searchbar.js
+++ /dev/null
@@ -1,195 +0,0 @@
-"use strict";
-
-const SCALAR_SEARCHBAR = "browser.engagement.navigation.searchbar";
-
-let searchInSearchbar = Task.async(function* (inputText) {
- let win = window;
- yield new Promise(r => waitForFocus(r, win));
- let sb = BrowserSearch.searchBar;
- // Write the search query in the searchbar.
- sb.focus();
- sb.value = inputText;
- sb.textbox.controller.startSearch(inputText);
- // Wait for the popup to show.
- yield BrowserTestUtils.waitForEvent(sb.textbox.popup, "popupshown");
- // And then for the search to complete.
- yield BrowserTestUtils.waitForCondition(() => sb.textbox.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH,
- "The search in the searchbar must complete.");
-});
-
-/**
- * Click one of the entries in the search suggestion popup.
- *
- * @param {String} entryName
- * The name of the elemet to click on.
- */
-function clickSearchbarSuggestion(entryName) {
- let popup = BrowserSearch.searchBar.textbox.popup;
- let column = popup.tree.columns[0];
-
- for (let rowID = 0; rowID < popup.tree.view.rowCount; rowID++) {
- const suggestion = popup.tree.view.getValueAt(rowID, column);
- if (suggestion !== entryName) {
- continue;
- }
-
- // Make sure the suggestion is visible, just in case.
- let tbo = popup.tree.treeBoxObject;
- tbo.ensureRowIsVisible(rowID);
- // Calculate the click coordinates.
- let rect = tbo.getCoordsForCellItem(rowID, column, "text");
- let x = rect.x + rect.width / 2;
- let y = rect.y + rect.height / 2;
- // Simulate the click.
- EventUtils.synthesizeMouse(popup.tree.body, x, y, {},
- popup.tree.ownerGlobal);
- break;
- }
-}
-
-add_task(function* setup() {
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_plainQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Simulate entering a simple search.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("simple query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_oneOff() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("query");
-
- info("Pressing Alt+Down to highlight the first one off engine.");
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true });
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_oneoff", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch2.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "oneoff", {engine: "other-MozSearch2"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_suggestion() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Create an engine to generate search suggestions and add it as default
- // for this test.
- const url = getRootDirectory(gTestPath) + "usageTelemetrySearchSuggestions.xml";
- let suggestionEngine = yield new Promise((resolve, reject) => {
- Services.search.addEngine(url, null, "", false, {
- onSuccess(engine) { resolve(engine) },
- onError() { reject() }
- });
- });
-
- let previousEngine = Services.search.currentEngine;
- Services.search.currentEngine = suggestionEngine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("query");
- info("Clicking the searchbar suggestion.");
- clickSearchbarSuggestion("queryfoo");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_suggestion", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "suggestion", {engine: searchEngineId}]]);
-
- Services.search.currentEngine = previousEngine;
- Services.search.removeEngine(suggestionEngine);
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_urlbar.js b/browser/modules/test/browser_UsageTelemetry_urlbar.js
deleted file mode 100644
index 81d3e28ba..000000000
--- a/browser/modules/test/browser_UsageTelemetry_urlbar.js
+++ /dev/null
@@ -1,220 +0,0 @@
-"use strict";
-
-const SCALAR_URLBAR = "browser.engagement.navigation.urlbar";
-
-// The preference to enable suggestions in the urlbar.
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-// The name of the search engine used to generate suggestions.
-const SUGGESTION_ENGINE_NAME = "browser_UsageTelemetry usageTelemetrySearchSuggestions.xml";
-const ONEOFF_URLBAR_PREF = "browser.urlbar.oneOffSearches";
-
-let searchInAwesomebar = Task.async(function* (inputText, win=window) {
- yield new Promise(r => waitForFocus(r, win));
- // Write the search query in the urlbar.
- win.gURLBar.focus();
- win.gURLBar.value = inputText;
- win.gURLBar.controller.startSearch(inputText);
- // Wait for the popup to show.
- yield BrowserTestUtils.waitForEvent(win.gURLBar.popup, "popupshown");
- // And then for the search to complete.
- yield BrowserTestUtils.waitForCondition(() => win.gURLBar.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
-});
-
-/**
- * Click one of the entries in the urlbar suggestion popup.
- *
- * @param {String} entryName
- * The name of the elemet to click on.
- */
-function clickURLBarSuggestion(entryName) {
- // The entry in the suggestion list should follow the format:
- // "<search term> <engine name> Search"
- const expectedSuggestionName = entryName + " " + SUGGESTION_ENGINE_NAME + " Search";
- for (let child of gURLBar.popup.richlistbox.children) {
- if (child.label === expectedSuggestionName) {
- // This entry is the search suggestion we're looking for.
- child.click();
- return;
- }
- }
-}
-
-add_task(function* setup() {
- // Create a new search engine.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make it the default search engine.
- let engine = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- // And the first one-off engine.
- Services.search.moveEngine(engine, 0);
-
- // Enable search suggestions in the urlbar.
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
-
- // Enable the urlbar one-off buttons.
- Services.prefs.setBoolPref(ONEOFF_URLBAR_PREF, true);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engine);
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF, true);
- Services.prefs.clearUserPref(ONEOFF_URLBAR_PREF);
- });
-});
-
-add_task(function* test_simpleQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Simulate entering a simple search.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("simple query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_searchAlias() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Search using a search alias.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("mozalias query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_alias", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "alias", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_oneOff() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("query");
-
- info("Pressing Alt+Down to take us to the first one-off engine.");
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true });
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_oneoff", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "oneoff", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_suggestion() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Create an engine to generate search suggestions and add it as default
- // for this test.
- const url = getRootDirectory(gTestPath) + "usageTelemetrySearchSuggestions.xml";
- let suggestionEngine = yield new Promise((resolve, reject) => {
- Services.search.addEngine(url, null, "", false, {
- onSuccess(engine) { resolve(engine) },
- onError() { reject() }
- });
- });
-
- let previousEngine = Services.search.currentEngine;
- Services.search.currentEngine = suggestionEngine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("query");
- info("Clicking the urlbar suggestion.");
- clickURLBarSuggestion("queryfoo");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_suggestion", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "suggestion", {engine: searchEngineId}]]);
-
- Services.search.currentEngine = previousEngine;
- Services.search.removeEngine(suggestionEngine);
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_taskbar_preview.js b/browser/modules/test/browser_taskbar_preview.js
deleted file mode 100644
index 89295b9e0..000000000
--- a/browser/modules/test/browser_taskbar_preview.js
+++ /dev/null
@@ -1,100 +0,0 @@
-function test() {
- var isWin7OrHigher = false;
- try {
- let version = Cc["@mozilla.org/system-info;1"]
- .getService(Ci.nsIPropertyBag2)
- .getProperty("version");
- isWin7OrHigher = (parseFloat(version) >= 6.1);
- } catch (ex) { }
-
- is(!!Win7Features, isWin7OrHigher, "Win7Features available when it should be");
- if (!isWin7OrHigher)
- return;
-
- const ENABLE_PREF_NAME = "browser.taskbar.previews.enable";
-
- let temp = {};
- Cu.import("resource:///modules/WindowsPreviewPerTab.jsm", temp);
- let AeroPeek = temp.AeroPeek;
-
- waitForExplicitFinish();
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, true);
-
- is(1, AeroPeek.windows.length, "Got the expected number of windows");
-
- checkPreviews(1, "Browser starts with one preview");
-
- gBrowser.addTab();
- gBrowser.addTab();
- gBrowser.addTab();
-
- checkPreviews(4, "Correct number of previews after adding");
-
- for (let preview of AeroPeek.previews)
- ok(preview.visible, "Preview is shown as expected");
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, false);
- is(0, AeroPeek.previews.length, "Should have 0 previews when disabled");
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, true);
- checkPreviews(4, "Previews are back when re-enabling");
- for (let preview of AeroPeek.previews)
- ok(preview.visible, "Preview is shown as expected after re-enabling");
-
- [1, 2, 3, 4].forEach(function (idx) {
- gBrowser.selectedTab = gBrowser.tabs[idx];
- ok(checkSelectedTab(), "Current tab is correctly selected");
- });
-
- // Close #4
- getPreviewForTab(gBrowser.selectedTab).controller.onClose();
- checkPreviews(3, "Expected number of previews after closing selected tab via controller");
- ok(gBrowser.tabs.length == 3, "Successfully closed a tab");
-
- // Select #1
- ok(getPreviewForTab(gBrowser.tabs[0]).controller.onActivate(), "Activation was accepted");
- ok(gBrowser.tabs[0].selected, "Correct tab was selected");
- checkSelectedTab();
-
- // Remove #3 (non active)
- gBrowser.removeTab(gBrowser.tabContainer.lastChild);
- checkPreviews(2, "Expected number of previews after closing unselected via browser");
-
- // Remove #1 (active)
- gBrowser.removeTab(gBrowser.tabContainer.firstChild);
- checkPreviews(1, "Expected number of previews after closing selected tab via browser");
-
- // Add a new tab
- gBrowser.addTab();
- checkPreviews(2);
- // Check default selection
- checkSelectedTab();
-
- // Change selection
- gBrowser.selectedTab = gBrowser.tabs[0];
- checkSelectedTab();
- // Close nonselected tab via controller
- getPreviewForTab(gBrowser.tabs[1]).controller.onClose();
- checkPreviews(1);
-
- if (gPrefService.prefHasUserValue(ENABLE_PREF_NAME))
- gPrefService.setBoolPref(ENABLE_PREF_NAME, !gPrefService.getBoolPref(ENABLE_PREF_NAME));
-
- finish();
-
- function checkPreviews(aPreviews, msg) {
- let nPreviews = AeroPeek.previews.length;
- is(aPreviews, gBrowser.tabs.length, "Browser has expected number of tabs - " + msg);
- is(nPreviews, gBrowser.tabs.length, "Browser has one preview per tab - " + msg);
- is(nPreviews, aPreviews, msg || "Got expected number of previews");
- }
-
- function getPreviewForTab(tab) {
- return window.gTaskbarTabGroup.previewFromTab(tab);
- }
-
- function checkSelectedTab() {
- return getPreviewForTab(gBrowser.selectedTab).active;
- }
-}
diff --git a/browser/modules/test/browser_urlBar_zoom.js b/browser/modules/test/browser_urlBar_zoom.js
deleted file mode 100644
index 9cb5c96c6..000000000
--- a/browser/modules/test/browser_urlBar_zoom.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* 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/. */
-
-"use strict";
-
-var initialPageZoom = ZoomManager.zoom;
-const kTimeoutInMS = 20000;
-
-add_task(function* () {
- info("Confirm whether the browser zoom is set to the default level");
- is(initialPageZoom, 1, "Page zoom is set to default (100%)");
- let zoomResetButton = document.getElementById("urlbar-zoom-button");
- is(zoomResetButton.hidden, true, "Zoom reset button is currently hidden");
-
- info("Change zoom and confirm zoom button appears");
- let labelUpdatePromise = BrowserTestUtils.waitForAttribute("label", zoomResetButton);
- FullZoom.enlarge();
- yield labelUpdatePromise;
- info("Zoom increased to " + Math.floor(ZoomManager.zoom * 100) + "%");
- is(zoomResetButton.hidden, false, "Zoom reset button is now visible");
- let pageZoomLevel = Math.floor(ZoomManager.zoom * 100);
- let expectedZoomLevel = 110;
- let buttonZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10);
- is(buttonZoomLevel, expectedZoomLevel, ("Button label updated successfully to " + Math.floor(ZoomManager.zoom * 100) + "%"));
-
- let zoomResetPromise = promiseObserverNotification("browser-fullZoom:zoomReset");
- zoomResetButton.click();
- yield zoomResetPromise;
- pageZoomLevel = Math.floor(ZoomManager.zoom * 100);
- expectedZoomLevel = 100;
- is(pageZoomLevel, expectedZoomLevel, "Clicking zoom button successfully resets browser zoom to 100%");
- is(zoomResetButton.hidden, true, "Zoom reset button returns to being hidden");
-
-});
-
-add_task(function* () {
- info("Confirm that URL bar zoom button doesn't appear when customizable zoom widget is added to toolbar");
- CustomizableUI.addWidgetToArea("zoom-controls", CustomizableUI.AREA_NAVBAR);
- let zoomCustomizableWidget = document.getElementById("zoom-reset-button");
- let zoomResetButton = document.getElementById("urlbar-zoom-button");
- let zoomChangePromise = promiseObserverNotification("browser-fullZoom:zoomChange");
- FullZoom.enlarge();
- yield zoomChangePromise;
- is(zoomResetButton.hidden, true, "URL zoom button remains hidden despite zoom increase");
- is(parseInt(zoomCustomizableWidget.label, 10), 110, "Customizable zoom widget's label has updated to " + zoomCustomizableWidget.label);
-});
-
-add_task(function* asyncCleanup() {
- // reset zoom level and customizable widget
- ZoomManager.zoom = initialPageZoom;
- is(ZoomManager.zoom, 1, "Zoom level was restored");
- if (document.getElementById("zoom-controls")) {
- CustomizableUI.removeWidgetFromArea("zoom-controls", CustomizableUI.AREA_NAVBAR);
- ok(!document.getElementById("zoom-controls"), "Customizable zoom widget removed from toolbar");
- }
-
-});
-
-function promiseObserverNotification(aObserver) {
- let deferred = Promise.defer();
- function notificationCallback(e) {
- Services.obs.removeObserver(notificationCallback, aObserver, false);
- clearTimeout(timeoutId);
- deferred.resolve();
- }
- let timeoutId = setTimeout(() => {
- Services.obs.removeObserver(notificationCallback, aObserver, false);
- deferred.reject("Notification '" + aObserver + "' did not happen within 20 seconds.");
- }, kTimeoutInMS);
- Services.obs.addObserver(notificationCallback, aObserver, false);
- return deferred.promise;
-}
diff --git a/browser/modules/test/contentSearch.js b/browser/modules/test/contentSearch.js
deleted file mode 100644
index b5dddfe45..000000000
--- a/browser/modules/test/contentSearch.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/* 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/. */
-
-const TEST_MSG = "ContentSearchTest";
-const SERVICE_EVENT_TYPE = "ContentSearchService";
-const CLIENT_EVENT_TYPE = "ContentSearchClient";
-
-// Forward events from the in-content service to the test.
-content.addEventListener(SERVICE_EVENT_TYPE, event => {
- // The event dispatch code in content.js clones the event detail into the
- // content scope. That's generally the right thing, but causes us to end
- // up with an XrayWrapper to it here, which will screw us up when trying to
- // serialize the object in sendAsyncMessage. Waive Xrays for the benefit of
- // the test machinery.
- sendAsyncMessage(TEST_MSG, Components.utils.waiveXrays(event.detail));
-});
-
-// Forward messages from the test to the in-content service.
-addMessageListener(TEST_MSG, msg => {
- // If the message is a search, stop the page from loading and then tell the
- // test that it loaded.
- if (msg.data.type == "Search") {
- waitForLoadAndStopIt(msg.data.expectedURL, url => {
- sendAsyncMessage(TEST_MSG, {
- type: "loadStopped",
- url: url,
- });
- });
- }
-
- content.dispatchEvent(
- new content.CustomEvent(CLIENT_EVENT_TYPE, {
- detail: msg.data,
- })
- );
-});
-
-function waitForLoadAndStopIt(expectedURL, callback) {
- let Ci = Components.interfaces;
- let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebProgress);
- let listener = {
- onStateChange: function (webProg, req, flags, status) {
- if (req instanceof Ci.nsIChannel) {
- let url = req.originalURI.spec;
- dump("waitForLoadAndStopIt: onStateChange " + url + "\n");
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if ((flags & docStart) && webProg.isTopLevel && url == expectedURL) {
- webProgress.removeProgressListener(listener);
- req.cancel(Components.results.NS_ERROR_FAILURE);
- callback(url);
- }
- }
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIWebProgressListener,
- Ci.nsISupportsWeakReference,
- ]),
- };
- webProgress.addProgressListener(listener, Ci.nsIWebProgress.NOTIFY_ALL);
- dump("waitForLoadAndStopIt: Waiting for URL to load: " + expectedURL + "\n");
-}
diff --git a/browser/modules/test/contentSearchBadImage.xml b/browser/modules/test/contentSearchBadImage.xml
deleted file mode 100644
index 6e4cb60a5..000000000
--- a/browser/modules/test/contentSearchBadImage.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_ContentSearch contentSearchBadImage.xml</ShortName>
-<Url type="text/html" method="GET" template="http://browser-ContentSearch.com/contentSearchBadImage" rel="searchform"/>
-<Image width="16" height="16">data:image/x-icon;base64,notbase64</Image>
-</SearchPlugin>
diff --git a/browser/modules/test/contentSearchSuggestions.sjs b/browser/modules/test/contentSearchSuggestions.sjs
deleted file mode 100644
index 1978b4f66..000000000
--- a/browser/modules/test/contentSearchSuggestions.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(req, resp) {
- let suffixes = ["foo", "bar"];
- let data = [req.queryString, suffixes.map(s => req.queryString + s)];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
-}
diff --git a/browser/modules/test/contentSearchSuggestions.xml b/browser/modules/test/contentSearchSuggestions.xml
deleted file mode 100644
index 81c23379c..000000000
--- a/browser/modules/test/contentSearchSuggestions.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_ContentSearch contentSearchSuggestions.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/modules/test/contentSearchSuggestions.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://browser-ContentSearch.com/contentSearchSuggestions" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/modules/test/head.js b/browser/modules/test/head.js
deleted file mode 100644
index be0215156..000000000
--- a/browser/modules/test/head.js
+++ /dev/null
@@ -1,113 +0,0 @@
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const SINGLE_TRY_TIMEOUT = 100;
-const NUMBER_OF_TRIES = 30;
-
-function waitForConditionPromise(condition, timeoutMsg, tryCount=NUMBER_OF_TRIES) {
- let defer = Promise.defer();
- let tries = 0;
- function checkCondition() {
- if (tries >= tryCount) {
- defer.reject(timeoutMsg);
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- return defer.reject(e);
- }
- if (conditionPassed) {
- return defer.resolve();
- }
- tries++;
- setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
- return undefined;
- }
- setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
- return defer.promise;
-}
-
-function waitForCondition(condition, nextTest, errorMsg) {
- waitForConditionPromise(condition, errorMsg).then(nextTest, (reason) => {
- ok(false, reason + (reason.stack ? "\n" + reason.stack : ""));
- });
-}
-
-/**
- * Checks if the snapshotted keyed scalars contain the expected
- * data.
- *
- * @param {Object} scalars
- * The snapshot of the keyed scalars.
- * @param {String} scalarName
- * The name of the keyed scalar to check.
- * @param {String} key
- * The key that must be within the keyed scalar.
- * @param {String|Boolean|Number} expectedValue
- * The expected value for the provided key in the scalar.
- */
-function checkKeyedScalar(scalars, scalarName, key, expectedValue) {
- Assert.ok(scalarName in scalars,
- scalarName + " must be recorded.");
- Assert.ok(key in scalars[scalarName],
- scalarName + " must contain the '" + key + "' key.");
- Assert.ok(scalars[scalarName][key], expectedValue,
- scalarName + "['" + key + "'] must contain the expected value");
-}
-
-/**
- * An utility function to write some text in the search input box
- * in a content page.
- * @param {Object} browser
- * The browser that contains the content.
- * @param {String} text
- * The string to write in the search field.
- * @param {String} fieldName
- * The name of the field to write to.
- */
-let typeInSearchField = Task.async(function* (browser, text, fieldName) {
- yield ContentTask.spawn(browser, { fieldName, text }, function* ({fieldName, text}) {
- // Avoid intermittent failures.
- if (fieldName === "searchText") {
- content.wrappedJSObject.gContentSearchController.remoteTimeout = 5000;
- }
- // Put the focus on the search box.
- let searchInput = content.document.getElementById(fieldName);
- searchInput.focus();
- searchInput.value = text;
- });
-});
-
-/**
- * Clear and get the SEARCH_COUNTS histogram.
- */
-function getSearchCountsHistogram() {
- let search_hist = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
- search_hist.clear();
- return search_hist;
-}
-
-/**
- * Check that the keyed histogram contains the right value.
- */
-function checkKeyedHistogram(h, key, expectedValue) {
- const snapshot = h.snapshot();
- Assert.ok(key in snapshot, `The histogram must contain ${key}.`);
- Assert.equal(snapshot[key].sum, expectedValue, `The key ${key} must contain ${expectedValue}.`);
-}
-
-function checkEvents(events, expectedEvents) {
- if (!Services.telemetry.canRecordExtended) {
- // Currently we only collect the tested events when extended Telemetry is enabled.
- return;
- }
-
- Assert.equal(events.length, expectedEvents.length, "Should have matching amount of events.");
-
- // Strip timestamps from the events for easier comparison.
- events = events.map(e => e.slice(1));
-
- for (let i = 0; i < events.length; ++i) {
- Assert.deepEqual(events[i], expectedEvents[i], "Events should match.");
- }
-}
diff --git a/browser/modules/test/unit/social/.eslintrc.js b/browser/modules/test/unit/social/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/browser/modules/test/unit/social/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/unit/social/blocklist.xml b/browser/modules/test/unit/social/blocklist.xml
deleted file mode 100644
index c8d72d624..000000000
--- a/browser/modules/test/unit/social/blocklist.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">
- <emItems>
- <emItem blockID="s1" id="bad.com@services.mozilla.org"></emItem>
- </emItems>
-</blocklist>
diff --git a/browser/modules/test/unit/social/head.js b/browser/modules/test/unit/social/head.js
deleted file mode 100644
index 0beabb685..000000000
--- a/browser/modules/test/unit/social/head.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* 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/. */
-
-var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var Social, SocialService;
-
-var manifests = [
- {
- name: "provider 1",
- origin: "https://example1.com",
- sidebarURL: "https://example1.com/sidebar/",
- },
- {
- name: "provider 2",
- origin: "https://example2.com",
- sidebarURL: "https://example1.com/sidebar/",
- }
-];
-
-const MANIFEST_PREFS = Services.prefs.getBranch("social.manifest.");
-
-// SocialProvider class relies on blocklisting being enabled. To enable
-// blocklisting, we have to setup an app and initialize the blocklist (see
-// initApp below).
-const gProfD = do_get_profile();
-
-function createAppInfo(ID, name, version, platformVersion="1.0") {
- let tmp = {};
- Cu.import("resource://testing-common/AppInfo.jsm", tmp);
- tmp.updateAppInfo({
- ID, name, version, platformVersion,
- crashReporter: true,
- });
- gAppInfo = tmp.getAppInfo();
-}
-
-function initApp() {
- createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9");
- // prepare a blocklist file for the blocklist service
- var blocklistFile = gProfD.clone();
- blocklistFile.append("blocklist.xml");
- if (blocklistFile.exists())
- blocklistFile.remove(false);
- var source = do_get_file("blocklist.xml");
- source.copyTo(gProfD, "blocklist.xml");
- blocklistFile.lastModifiedTime = Date.now();
-
-
- let internalManager = Cc["@mozilla.org/addons/integration;1"].
- getService(Ci.nsIObserver).
- QueryInterface(Ci.nsITimerCallback);
-
- internalManager.observe(null, "addons-startup", null);
-}
-
-function setManifestPref(manifest) {
- let string = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- string.data = JSON.stringify(manifest);
- Services.prefs.setComplexValue("social.manifest." + manifest.origin, Ci.nsISupportsString, string);
-}
-
-function do_wait_observer(obsTopic, cb) {
- function observer(subject, topic, data) {
- Services.obs.removeObserver(observer, topic);
- cb();
- }
- Services.obs.addObserver(observer, obsTopic, false);
-}
-
-function do_add_providers(cb) {
- // run only after social is already initialized
- SocialService.addProvider(manifests[0], function() {
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.providers.length, 2, "2 providers installed");
- do_execute_soon(cb);
- });
- SocialService.addProvider(manifests[1]);
- });
-}
-
-function do_initialize_social(enabledOnStartup, cb) {
- initApp();
-
- if (enabledOnStartup) {
- // set prefs before initializing social
- manifests.forEach(function (manifest) {
- setManifestPref(manifest);
- });
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- for (let m of manifests)
- active[m.origin] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- do_register_cleanup(function() {
- manifests.forEach(function (manifest) {
- Services.prefs.clearUserPref("social.manifest." + manifest.origin);
- });
- Services.prefs.clearUserPref("social.activeProviders");
- });
-
- // expecting 2 providers installed
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.providers.length, 2, "2 providers installed");
- do_execute_soon(cb);
- });
- }
-
- // import and initialize everything
- SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
- do_check_eq(enabledOnStartup, SocialService.hasEnabledProviders, "Service has enabled providers");
- Social = Cu.import("resource:///modules/Social.jsm", {}).Social;
- do_check_false(Social.initialized, "Social is not initialized");
- Social.init();
- do_check_true(Social.initialized, "Social is initialized");
- if (!enabledOnStartup)
- do_execute_soon(cb);
-}
-
-function AsyncRunner() {
- do_test_pending();
- do_register_cleanup(() => this.destroy());
-
- this._callbacks = {
- done: do_test_finished,
- error: function (err) {
- // xpcshell test functions like do_check_eq throw NS_ERROR_ABORT on
- // failure. Ignore those so they aren't rethrown here.
- if (err !== Cr.NS_ERROR_ABORT) {
- if (err.stack) {
- err = err + " - See following stack:\n" + err.stack +
- "\nUseless do_throw stack";
- }
- do_throw(err);
- }
- },
- consoleError: function (scriptErr) {
- // Try to ensure the error is related to the test.
- let filename = scriptErr.sourceName || scriptErr.toString() || "";
- if (filename.indexOf("/toolkit/components/social/") >= 0)
- do_throw(scriptErr);
- },
- };
- this._iteratorQueue = [];
-
- // This catches errors reported to the console, e.g., via Cu.reportError, but
- // not on the runner's stack.
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- registerListener(this);
-}
-
-AsyncRunner.prototype = {
-
- appendIterator: function appendIterator(iter) {
- this._iteratorQueue.push(iter);
- },
-
- next: function next(arg) {
- if (!this._iteratorQueue.length) {
- this.destroy();
- this._callbacks.done();
- return;
- }
-
- try {
- var { done, value: val } = this._iteratorQueue[0].next(arg);
- if (done) {
- this._iteratorQueue.shift();
- this.next();
- return;
- }
- }
- catch (err) {
- this._callbacks.error(err);
- }
-
- // val is an iterator => prepend it to the queue and start on it
- // val is otherwise truthy => call next
- if (val) {
- if (typeof(val) != "boolean")
- this._iteratorQueue.unshift(val);
- this.next();
- }
- },
-
- destroy: function destroy() {
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- unregisterListener(this);
- this.destroy = function alreadyDestroyed() {};
- },
-
- observe: function observe(msg) {
- if (msg instanceof Ci.nsIScriptError &&
- !(msg.flags & Ci.nsIScriptError.warningFlag))
- {
- this._callbacks.consoleError(msg);
- }
- },
-};
diff --git a/browser/modules/test/unit/social/test_SocialService.js b/browser/modules/test/unit/social/test_SocialService.js
deleted file mode 100644
index e6f354fed..000000000
--- a/browser/modules/test/unit/social/test_SocialService.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* 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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-function run_test() {
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifests = [
- { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- shareURL: "https://example1.com/share/",
- },
- { // provider without workerURL
- name: "provider 2",
- origin: "https://example2.com",
- shareURL: "https://example2.com/share/",
- }
- ];
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testAddProviders(manifests, next));
- runner.appendIterator(testGetProvider(manifests, next));
- runner.appendIterator(testGetProviderList(manifests, next));
- runner.appendIterator(testAddRemoveProvider(manifests, next));
- runner.appendIterator(testIsSameOrigin(manifests, next));
- runner.appendIterator(testResolveUri (manifests, next));
- runner.appendIterator(testOrderedProviders(manifests, next));
- runner.appendIterator(testRemoveProviders(manifests, next));
- runner.next();
-}
-
-function* testAddProviders(manifests, next) {
- do_check_false(SocialService.enabled);
- let provider = yield SocialService.addProvider(manifests[0], next);
- do_check_true(SocialService.enabled);
- do_check_false(provider.enabled);
- provider = yield SocialService.addProvider(manifests[1], next);
- do_check_false(provider.enabled);
-}
-
-function* testRemoveProviders(manifests, next) {
- do_check_true(SocialService.enabled);
- yield SocialService.disableProvider(manifests[0].origin, next);
- yield SocialService.disableProvider(manifests[1].origin, next);
- do_check_false(SocialService.enabled);
-}
-
-function* testGetProvider(manifests, next) {
- for (let i = 0; i < manifests.length; i++) {
- let manifest = manifests[i];
- let provider = yield SocialService.getProvider(manifest.origin, next);
- do_check_neq(provider, null);
- do_check_eq(provider.name, manifest.name);
- do_check_eq(provider.workerURL, manifest.workerURL);
- do_check_eq(provider.origin, manifest.origin);
- }
- do_check_eq((yield SocialService.getProvider("bogus", next)), null);
-}
-
-function* testGetProviderList(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- do_check_true(providers.length >= manifests.length);
- for (let i = 0; i < manifests.length; i++) {
- let providerIdx = providers.map(p => p.origin).indexOf(manifests[i].origin);
- let provider = providers[providerIdx];
- do_check_true(!!provider);
- do_check_false(provider.enabled);
- do_check_eq(provider.workerURL, manifests[i].workerURL);
- do_check_eq(provider.name, manifests[i].name);
- }
-}
-
-function* testAddRemoveProvider(manifests, next) {
- var threw;
- try {
- // Adding a provider whose origin already exists should fail
- SocialService.addProvider(manifests[0]);
- } catch (ex) {
- threw = ex;
- }
- do_check_neq(threw.toString().indexOf("SocialService.addProvider: provider with this origin already exists"), -1);
-
- let originalProviders = yield SocialService.getProviderList(next);
-
- // Check that provider installation succeeds
- let newProvider = yield SocialService.addProvider({
- name: "foo",
- origin: "http://example3.com"
- }, next);
- let retrievedNewProvider = yield SocialService.getProvider(newProvider.origin, next);
- do_check_eq(newProvider, retrievedNewProvider);
-
- let providersAfter = yield SocialService.getProviderList(next);
- do_check_eq(providersAfter.length, originalProviders.length + 1);
- do_check_neq(providersAfter.indexOf(newProvider), -1);
-
- // Now remove the provider
- yield SocialService.disableProvider(newProvider.origin, next);
- providersAfter = yield SocialService.getProviderList(next);
- do_check_eq(providersAfter.length, originalProviders.length);
- do_check_eq(providersAfter.indexOf(newProvider), -1);
- newProvider = yield SocialService.getProvider(newProvider.origin, next);
- do_check_true(!newProvider);
-}
-
-function* testIsSameOrigin(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- let provider = providers[0];
- // provider.origin is a string.
- do_check_true(provider.isSameOrigin(provider.origin));
- do_check_true(provider.isSameOrigin(Services.io.newURI(provider.origin, null, null)));
- do_check_true(provider.isSameOrigin(provider.origin + "/some-sub-page"));
- do_check_true(provider.isSameOrigin(Services.io.newURI(provider.origin + "/some-sub-page", null, null)));
- do_check_false(provider.isSameOrigin("http://something.com"));
- do_check_false(provider.isSameOrigin(Services.io.newURI("http://something.com", null, null)));
- do_check_false(provider.isSameOrigin("data:text/html,<p>hi"));
- do_check_true(provider.isSameOrigin("data:text/html,<p>hi", true));
- do_check_false(provider.isSameOrigin(Services.io.newURI("data:text/html,<p>hi", null, null)));
- do_check_true(provider.isSameOrigin(Services.io.newURI("data:text/html,<p>hi", null, null), true));
- // we explicitly handle null and return false
- do_check_false(provider.isSameOrigin(null));
-}
-
-function* testResolveUri(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- let provider = providers[0];
- do_check_eq(provider.resolveUri(provider.origin).spec, provider.origin + "/");
- do_check_eq(provider.resolveUri("foo.html").spec, provider.origin + "/foo.html");
- do_check_eq(provider.resolveUri("/foo.html").spec, provider.origin + "/foo.html");
- do_check_eq(provider.resolveUri("http://somewhereelse.com/foo.html").spec, "http://somewhereelse.com/foo.html");
- do_check_eq(provider.resolveUri("data:text/html,<p>hi").spec, "data:text/html,<p>hi");
-}
-
-function* testOrderedProviders(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
-
- // add visits for only one of the providers
- let visits = [];
- let startDate = Date.now() * 1000;
- for (let i = 0; i < 10; i++) {
- visits.push({
- uri: Services.io.newURI(providers[1].shareURL + i, null, null),
- visitDate: startDate + i
- });
- }
-
- PlacesTestUtils.addVisits(visits).then(next);
- yield;
- let orderedProviders = yield SocialService.getOrderedProviderList(next);
- do_check_eq(orderedProviders[0], providers[1]);
- do_check_eq(orderedProviders[1], providers[0]);
- do_check_true(orderedProviders[0].frecency > orderedProviders[1].frecency);
- PlacesTestUtils.clearHistory().then(next);
- yield;
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration21.js b/browser/modules/test/unit/social/test_SocialServiceMigration21.js
deleted file mode 100644
index dfe6183bf..000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration21.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-const DEFAULT_PREFS = Services.prefs.getDefaultBranch("social.manifest.");
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- builtin: true // as of fx22 this should be true for default prefs
- };
-
- DEFAULT_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
- Services.prefs.setBoolPref("social.active", true);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_false(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_true(SocialService.enabled);
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString);
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin]);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- do_check_true(JSON.parse(DEFAULT_PREFS.getCharPref(manifest.origin)).builtin);
-
- let userPref = JSON.parse(MANIFEST_PREFS.getCharPref(manifest.origin));
- do_check_true(parseInt(userPref.updateDate) > 0);
- // migrated providers wont have an installDate
- do_check_true(userPref.installDate === 0);
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration22.js b/browser/modules/test/unit/social/test_SocialServiceMigration22.js
deleted file mode 100644
index 1a3953175..000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration22.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* 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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-const DEFAULT_PREFS = Services.prefs.getDefaultBranch("social.manifest.");
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- builtin: true // as of fx22 this should be true for default prefs
- };
-
- DEFAULT_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
-
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- active[manifest.origin] = 1;
- // bad.origin tests that a missing manifest does not break migration, bug 859715
- active["bad.origin"] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_false(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_true(SocialService.enabled);
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString);
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin]);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- do_check_true(JSON.parse(DEFAULT_PREFS.getCharPref(manifest.origin)).builtin);
-
- let userPref = JSON.parse(MANIFEST_PREFS.getCharPref(manifest.origin));
- do_check_true(parseInt(userPref.updateDate) > 0);
- // migrated providers wont have an installDate
- do_check_true(userPref.installDate === 0);
-
- // bug 859715, this should have been removed during migration
- do_check_false(!!activeProviders["bad.origin"]);
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration29.js b/browser/modules/test/unit/social/test_SocialServiceMigration29.js
deleted file mode 100644
index 824673ddf..000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration29.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* 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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- };
-
- MANIFEST_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
-
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- active[manifest.origin] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- // social.enabled pref is the key focus of this test. We set the user pref,
- // and then migration should a) remove the provider from activeProviders and
- // b) unset social.enabled
- Services.prefs.setBoolPref("social.enabled", false);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_true(Services.prefs.prefHasUserValue("social.enabled"));
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_false(SocialService.enabled);
- do_check_false(Services.prefs.prefHasUserValue("social.enabled"));
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString).data;
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin] == undefined);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
-}
diff --git a/browser/modules/test/unit/social/test_social.js b/browser/modules/test/unit/social/test_social.js
deleted file mode 100644
index 3117306c1..000000000
--- a/browser/modules/test/unit/social/test_social.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* 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/. */
-
-function run_test() {
- // we are testing worker startup specifically
- do_test_pending();
- add_test(testStartupEnabled);
- add_test(testDisableAfterStartup);
- do_initialize_social(true, run_next_test);
-}
-
-function testStartupEnabled() {
- // wait on startup before continuing
- do_check_eq(Social.providers.length, 2, "two social providers enabled");
- do_check_true(Social.providers[0].enabled, "provider 0 is enabled");
- do_check_true(Social.providers[1].enabled, "provider 1 is enabled");
- run_next_test();
-}
-
-function testDisableAfterStartup() {
- let SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
- SocialService.disableProvider(Social.providers[0].origin, function() {
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.enabled, false, "Social is disabled");
- do_check_eq(Social.providers.length, 0, "no social providers available");
- do_test_finished();
- run_next_test();
- });
- SocialService.disableProvider(Social.providers[0].origin)
- });
-}
diff --git a/browser/modules/test/unit/social/test_socialDisabledStartup.js b/browser/modules/test/unit/social/test_socialDisabledStartup.js
deleted file mode 100644
index a2f7a1d5a..000000000
--- a/browser/modules/test/unit/social/test_socialDisabledStartup.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* 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/. */
-
-function run_test() {
- // we are testing worker startup specifically
- do_test_pending();
- add_test(testStartupDisabled);
- add_test(testEnableAfterStartup);
- do_initialize_social(false, run_next_test);
-}
-
-function testStartupDisabled() {
- // wait on startup before continuing
- do_check_false(Social.enabled, "Social is disabled");
- do_check_eq(Social.providers.length, 0, "zero social providers available");
- run_next_test();
-}
-
-function testEnableAfterStartup() {
- do_add_providers(function () {
- do_check_true(Social.enabled, "Social is enabled");
- do_check_eq(Social.providers.length, 2, "two social providers available");
- do_check_true(Social.providers[0].enabled, "provider 0 is enabled");
- do_check_true(Social.providers[1].enabled, "provider 1 is enabled");
- do_test_finished();
- run_next_test();
- });
-}
diff --git a/browser/modules/test/unit/social/xpcshell.ini b/browser/modules/test/unit/social/xpcshell.ini
deleted file mode 100644
index 277dd4f49..000000000
--- a/browser/modules/test/unit/social/xpcshell.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files = blocklist.xml
-
-[test_social.js]
-[test_socialDisabledStartup.js]
-[test_SocialService.js]
-[test_SocialServiceMigration21.js]
-[test_SocialServiceMigration22.js]
-[test_SocialServiceMigration29.js]
diff --git a/browser/modules/test/usageTelemetrySearchSuggestions.sjs b/browser/modules/test/usageTelemetrySearchSuggestions.sjs
deleted file mode 100644
index 1978b4f66..000000000
--- a/browser/modules/test/usageTelemetrySearchSuggestions.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(req, resp) {
- let suffixes = ["foo", "bar"];
- let data = [req.queryString, suffixes.map(s => req.queryString + s)];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
-}
diff --git a/browser/modules/test/usageTelemetrySearchSuggestions.xml b/browser/modules/test/usageTelemetrySearchSuggestions.xml
deleted file mode 100644
index 76276045d..000000000
--- a/browser/modules/test/usageTelemetrySearchSuggestions.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>browser_UsageTelemetry usageTelemetrySearchSuggestions.xml</ShortName>
-<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/modules/test/usageTelemetrySearchSuggestions.sjs?{searchTerms}"/>
-<Url type="text/html" method="GET" template="http://example.com" rel="searchform"/>
-</SearchPlugin>
diff --git a/browser/modules/test/xpcshell/.eslintrc.js b/browser/modules/test/xpcshell/.eslintrc.js
deleted file mode 100644
index fee088c17..000000000
--- a/browser/modules/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/xpcshell/test_AttributionCode.js b/browser/modules/test/xpcshell/test_AttributionCode.js
deleted file mode 100644
index d979ae845..000000000
--- a/browser/modules/test/xpcshell/test_AttributionCode.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-const {interfaces: Ci, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/AppConstants.jsm");
-Cu.import("resource:///modules/AttributionCode.jsm");
-Cu.import('resource://gre/modules/osfile.jsm');
-Cu.import("resource://gre/modules/Services.jsm");
-
-let validAttrCodes = [
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D(not%20set)%26content%3D(not%20set)",
- parsed: {"source": "google.com", "medium": "organic",
- "campaign": "(not%20set)", "content": "(not%20set)"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D%26content%3D",
- parsed: {"source": "google.com", "medium": "organic"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D(not%20set)",
- parsed: {"source": "google.com", "medium": "organic", "campaign": "(not%20set)"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic",
- parsed: {"source": "google.com", "medium": "organic"}},
- {code: "source%3Dgoogle.com",
- parsed: {"source": "google.com"}},
- {code: "medium%3Dgoogle.com",
- parsed: {"medium": "google.com"}},
- {code: "campaign%3Dgoogle.com",
- parsed: {"campaign": "google.com"}},
- {code: "content%3Dgoogle.com",
- parsed: {"content": "google.com"}}
-];
-
-let invalidAttrCodes = [
- // Empty string
- "",
- // Not escaped
- "source=google.com&medium=organic&campaign=(not set)&content=(not set)",
- // Too long
- "source%3Dreallyreallyreallyreallyreallyreallyreallyreallyreallylongdomain.com%26medium%3Dorganic%26campaign%3D(not%20set)%26content%3Dalmostexactlyenoughcontenttomakethisstringlongerthanthe200characterlimit",
- // Unknown key name
- "source%3Dgoogle.com%26medium%3Dorganic%26large%3Dgeneticallymodified",
- // Empty key name
- "source%3Dgoogle.com%26medium%3Dorganic%26%3Dgeneticallymodified"
-];
-
-function* writeAttributionFile(data) {
- let appDir = Services.dirsvc.get("LocalAppData", Ci.nsIFile);
- let file = appDir.clone();
- file.append(Services.appinfo.vendor || "mozilla");
- file.append(AppConstants.MOZ_APP_NAME);
-
- yield OS.File.makeDir(file.path,
- {from: appDir.path, ignoreExisting: true});
-
- file.append("postSigningData");
- yield OS.File.writeAtomic(file.path, data);
-}
-
-/**
- * Test validation of attribution codes,
- * to make sure we reject bad ones and accept good ones.
- */
-add_task(function* testValidAttrCodes() {
- for (let entry of validAttrCodes) {
- AttributionCode._clearCache();
- yield writeAttributionFile(entry.code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, entry.parsed,
- "Parsed code should match expected value, code was: " + entry.code);
- }
- AttributionCode._clearCache();
-});
-
-/**
- * Make sure codes with various formatting errors are not seen as valid.
- */
-add_task(function* testInvalidAttrCodes() {
- for (let code of invalidAttrCodes) {
- AttributionCode._clearCache();
- yield writeAttributionFile(code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, {},
- "Code should have failed to parse: " + code);
- }
- AttributionCode._clearCache();
-});
-
-/**
- * Test the cache by deleting the attribution data file
- * and making sure we still get the expected code.
- */
-add_task(function* testDeletedFile() {
- // Set up the test by clearing the cache and writing a valid file.
- yield writeAttributionFile(validAttrCodes[0].code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, validAttrCodes[0].parsed,
- "The code should be readable directly from the file");
-
- // Delete the file and make sure we can still read the value back from cache.
- yield AttributionCode.deleteFileAsync();
- result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, validAttrCodes[0].parsed,
- "The code should be readable from the cache");
-
- // Clear the cache and check we can't read anything.
- AttributionCode._clearCache();
- result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, {},
- "Shouldn't be able to get a code after file is deleted and cache is cleared");
-});
diff --git a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
deleted file mode 100644
index 712f52fa6..000000000
--- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
+++ /dev/null
@@ -1,1854 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-/**
- * This file tests the DirectoryLinksProvider singleton in the DirectoryLinksProvider.jsm module.
- */
-
-var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu, Constructor: CC } = Components;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource:///modules/DirectoryLinksProvider.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Http.jsm");
-Cu.import("resource://testing-common/httpd.js");
-Cu.import("resource://gre/modules/osfile.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
- "resource://gre/modules/NewTabUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-do_get_profile();
-
-const DIRECTORY_LINKS_FILE = "directoryLinks.json";
-const DIRECTORY_FRECENCY = 1000;
-const SUGGESTED_FRECENCY = Infinity;
-const kURLData = {"directory": [{"url":"http://example.com", "title":"LocalSource"}]};
-const kTestURL = 'data:application/json,' + JSON.stringify(kURLData);
-
-// DirectoryLinksProvider preferences
-const kLocalePref = DirectoryLinksProvider._observedPrefs.prefSelectedLocale;
-const kSourceUrlPref = DirectoryLinksProvider._observedPrefs.linksURL;
-const kPingUrlPref = "browser.newtabpage.directory.ping";
-const kNewtabEnhancedPref = "browser.newtabpage.enhanced";
-
-// httpd settings
-var server;
-const kDefaultServerPort = 9000;
-const kBaseUrl = "http://localhost:" + kDefaultServerPort;
-const kExamplePath = "/exampleTest/";
-const kFailPath = "/fail/";
-const kPingPath = "/ping/";
-const kExampleURL = kBaseUrl + kExamplePath;
-const kFailURL = kBaseUrl + kFailPath;
-const kPingUrl = kBaseUrl + kPingPath;
-
-// app/profile/firefox.js are not avaialble in xpcshell: hence, preset them
-Services.prefs.setCharPref(kLocalePref, "en-US");
-Services.prefs.setCharPref(kSourceUrlPref, kTestURL);
-Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-Services.prefs.setBoolPref(kNewtabEnhancedPref, true);
-
-const kHttpHandlerData = {};
-kHttpHandlerData[kExamplePath] = {"directory": [{"url":"http://example.com", "title":"RemoteSource"}]};
-
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-var gLastRequestPath;
-
-var suggestedTile1 = {
- url: "http://turbotax.com",
- type: "affiliate",
- lastVisitDate: 4,
- adgroup_name: "Adgroup1",
- frecent_sites: [
- "taxact.com",
- "hrblock.com",
- "1040.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile2 = {
- url: "http://irs.gov",
- type: "affiliate",
- lastVisitDate: 3,
- adgroup_name: "Adgroup2",
- frecent_sites: [
- "taxact.com",
- "hrblock.com",
- "freetaxusa.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile3 = {
- url: "http://hrblock.com",
- type: "affiliate",
- lastVisitDate: 2,
- adgroup_name: "Adgroup3",
- frecent_sites: [
- "taxact.com",
- "freetaxusa.com",
- "1040.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile4 = {
- url: "http://sponsoredtile.com",
- type: "sponsored",
- lastVisitDate: 1,
- adgroup_name: "Adgroup4",
- frecent_sites: [
- "sponsoredtarget.com"
- ]
-}
-var suggestedTile5 = {
- url: "http://eviltile.com",
- type: "affiliate",
- lastVisitDate: 5,
- explanation: "This is an evil tile <form><button formaction='javascript:alert(1)''>X</button></form> muhahaha",
- adgroup_name: "WE ARE EVIL <link rel='import' href='test.svg'/>",
- frecent_sites: [
- "eviltarget.com"
- ]
-}
-var someOtherSite = {url: "http://someothersite.com", title: "Not_A_Suggested_Site"};
-
-function getHttpHandler(path) {
- let code = 200;
- let body = JSON.stringify(kHttpHandlerData[path]);
- if (path == kFailPath) {
- code = 204;
- }
- return function(aRequest, aResponse) {
- gLastRequestPath = aRequest.path;
- aResponse.setStatusLine(null, code);
- aResponse.setHeader("Content-Type", "application/json");
- aResponse.write(body);
- };
-}
-
-function isIdentical(actual, expected) {
- if (expected == null) {
- do_check_eq(actual, expected);
- }
- else if (typeof expected == "object") {
- // Make sure all the keys match up
- do_check_eq(Object.keys(actual).sort() + "", Object.keys(expected).sort());
-
- // Recursively check each value individually
- Object.keys(expected).forEach(key => {
- isIdentical(actual[key], expected[key]);
- });
- }
- else {
- do_check_eq(actual, expected);
- }
-}
-
-function fetchData() {
- let deferred = Promise.defer();
-
- DirectoryLinksProvider.getLinks(linkData => {
- deferred.resolve(linkData);
- });
- return deferred.promise;
-}
-
-function readJsonFile(jsonFile = DIRECTORY_LINKS_FILE) {
- let decoder = new TextDecoder();
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.localProfileDir, jsonFile);
- return OS.File.read(directoryLinksFilePath).then(array => {
- let json = decoder.decode(array);
- return JSON.parse(json);
- }, () => { return "" });
-}
-
-function cleanJsonFile(jsonFile = DIRECTORY_LINKS_FILE) {
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.localProfileDir, jsonFile);
- return OS.File.remove(directoryLinksFilePath);
-}
-
-function LinksChangeObserver() {
- this.deferred = Promise.defer();
- this.onManyLinksChanged = () => this.deferred.resolve();
- this.onDownloadFail = this.onManyLinksChanged;
-}
-
-function promiseDirectoryDownloadOnPrefChange(pref, newValue) {
- let oldValue = Services.prefs.getCharPref(pref);
- if (oldValue != newValue) {
- // if the preference value is already equal to newValue
- // the pref service will not call our observer and we
- // deadlock. Hence only setup observer if values differ
- let observer = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(observer);
- Services.prefs.setCharPref(pref, newValue);
- return observer.deferred.promise.then(() => {
- DirectoryLinksProvider.removeObserver(observer);
- });
- }
- return Promise.resolve();
-}
-
-function promiseSetupDirectoryLinksProvider(options = {}) {
- return Task.spawn(function*() {
- let linksURL = options.linksURL || kTestURL;
- yield DirectoryLinksProvider.init();
- yield promiseDirectoryDownloadOnPrefChange(kLocalePref, options.locale || "en-US");
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, linksURL);
- do_check_eq(DirectoryLinksProvider._linksURL, linksURL);
- DirectoryLinksProvider._lastDownloadMS = options.lastDownloadMS || 0;
- });
-}
-
-function promiseCleanDirectoryLinksProvider() {
- return Task.spawn(function*() {
- yield promiseDirectoryDownloadOnPrefChange(kLocalePref, "en-US");
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kTestURL);
- yield DirectoryLinksProvider._clearFrequencyCap();
- yield DirectoryLinksProvider._loadInadjacentSites();
- DirectoryLinksProvider._lastDownloadMS = 0;
- DirectoryLinksProvider.reset();
- });
-}
-
-function run_test() {
- // Set up a mock HTTP server to serve a directory page
- server = new HttpServer();
- server.registerPrefixHandler(kExamplePath, getHttpHandler(kExamplePath));
- server.registerPrefixHandler(kFailPath, getHttpHandler(kFailPath));
- server.start(kDefaultServerPort);
- NewTabUtils.init();
-
- run_next_test();
-
- // Teardown.
- do_register_cleanup(function() {
- server.stop(function() { });
- DirectoryLinksProvider.reset();
- Services.prefs.clearUserPref(kLocalePref);
- Services.prefs.clearUserPref(kSourceUrlPref);
- Services.prefs.clearUserPref(kPingUrlPref);
- Services.prefs.clearUserPref(kNewtabEnhancedPref);
- });
-}
-
-
-function setTimeout(fun, timeout) {
- let timer = Components.classes["@mozilla.org/timer;1"]
- .createInstance(Components.interfaces.nsITimer);
- var event = {
- notify: function () {
- fun();
- }
- };
- timer.initWithCallback(event, timeout,
- Components.interfaces.nsITimer.TYPE_ONE_SHOT);
- return timer;
-}
-
-add_task(function test_shouldUpdateSuggestedTile() {
- let suggestedLink = {
- targetedSite: "somesite.com"
- };
-
- // DirectoryLinksProvider has no suggested tile and no top sites => no need to update
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 0);
- isIdentical(NewTabUtils.getProviderLinks(), []);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), false);
-
- // DirectoryLinksProvider has a suggested tile and no top sites => need to update
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = (provider) => [suggestedLink];
-
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 0);
- isIdentical(NewTabUtils.getProviderLinks(), [suggestedLink]);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), true);
-
- // DirectoryLinksProvider has a suggested tile and 8 top sites => no need to update
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 8);
- isIdentical(NewTabUtils.getProviderLinks(), [suggestedLink]);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), false);
-
- // DirectoryLinksProvider has no suggested tile and 8 top sites => need to update
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 8);
- isIdentical(NewTabUtils.getProviderLinks(), []);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), true);
-
- // Cleanup
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function* test_updateSuggestedTile() {
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
-
- // Initial setup
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestFirstRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- function TestFirstRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- links.unshift(link);
- let possibleLinks = [suggestedTile1.url, suggestedTile2.url, suggestedTile3.url];
-
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "1040.com", "freetaxusa.com"]);
- do_check_true(possibleLinks.indexOf(link.url) > -1);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.type, "affiliate");
- resolve();
- };
- });
- }
-
- function TestChangingSuggestedTile() {
- this.count = 0;
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- this.count++;
- let possibleLinks = [suggestedTile1.url, suggestedTile2.url, suggestedTile3.url];
-
- do_check_true(possibleLinks.indexOf(link.url) > -1);
- do_check_eq(link.type, "affiliate");
- do_check_true(this.count <= 2);
-
- if (this.count == 1) {
- // The removed suggested link is the one we added initially.
- do_check_eq(link.url, links.shift().url);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- } else {
- links.unshift(link);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- }
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "freetaxusa.com"]);
- resolve();
- }
- });
- }
-
- function TestRemovingSuggestedTile() {
- this.count = 0;
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- this.count++;
-
- do_check_eq(link.type, "affiliate");
- do_check_eq(this.count, 1);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.url, links.shift().url);
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], []);
- resolve();
- }
- });
- }
-
- // Test first call to '_updateSuggestedTile()', called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // Removing a top site that doesn't have a suggested link should
- // not change the current suggested tile.
- let removedTopsite = topSites.shift();
- do_check_eq(removedTopsite, "site0.com");
- do_check_false(NewTabUtils.isTopPlacesSite(removedTopsite));
- let updateSuggestedTile = DirectoryLinksProvider._handleLinkChanged({
- url: "http://" + removedTopsite,
- type: "history",
- });
- do_check_false(updateSuggestedTile);
-
- // Removing a top site that has a suggested link should
- // remove any current suggested tile and add a new one.
- testObserver = new TestChangingSuggestedTile();
- DirectoryLinksProvider.addObserver(testObserver);
- removedTopsite = topSites.shift();
- do_check_eq(removedTopsite, "1040.com");
- do_check_false(NewTabUtils.isTopPlacesSite(removedTopsite));
- DirectoryLinksProvider.onLinkChanged(DirectoryLinksProvider, {
- url: "http://" + removedTopsite,
- type: "history",
- });
- yield testObserver.promise;
- do_check_eq(testObserver.count, 2);
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // Removing all top sites with suggested links should remove
- // the current suggested link and not replace it.
- topSites = [];
- testObserver = new TestRemovingSuggestedTile();
- DirectoryLinksProvider.addObserver(testObserver);
- DirectoryLinksProvider.onManyLinksChanged();
- yield testObserver.promise;
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function* test_suggestedLinksMap() {
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3, suggestedTile4], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- // Ensure the suggested tiles were not considered directory tiles.
- do_check_eq(links.length, 1);
- let expected_data = [{url: "http://someothersite.com", title: "Not_A_Suggested_Site", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
- isIdentical(links, expected_data);
-
- // Check for correctly saved suggested tiles data.
- expected_data = {
- "taxact.com": [suggestedTile1, suggestedTile2, suggestedTile3],
- "hrblock.com": [suggestedTile1, suggestedTile2],
- "1040.com": [suggestedTile1, suggestedTile3],
- "taxslayer.com": [suggestedTile1, suggestedTile2, suggestedTile3],
- "freetaxusa.com": [suggestedTile2, suggestedTile3],
- "sponsoredtarget.com": [suggestedTile4],
- };
-
- let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
- do_check_eq(suggestedSites.indexOf("sponsoredtarget.com"), 5);
- do_check_eq(suggestedSites.length, Object.keys(expected_data).length);
-
- DirectoryLinksProvider._suggestedLinks.forEach((suggestedLinks, site) => {
- let suggestedLinksItr = suggestedLinks.values();
- for (let link of expected_data[site]) {
- let linkCopy = JSON.parse(JSON.stringify(link));
- linkCopy.targetedName = link.adgroup_name;
- linkCopy.explanation = "";
- isIdentical(suggestedLinksItr.next().value, linkCopy);
- }
- })
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_topSitesWithSuggestedLinks() {
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- // Mock out getProviderLinks() so we don't have to populate cache in NewTabUtils
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return [];
- }
-
- // We start off with no top sites with suggested links.
- do_check_eq(DirectoryLinksProvider._topSitesWithSuggestedLinks.size, 0);
-
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- yield fetchData();
-
- // Check we've populated suggested links as expected.
- do_check_eq(DirectoryLinksProvider._suggestedLinks.size, 5);
-
- // When many sites change, we update _topSitesWithSuggestedLinks as expected.
- let expectedTopSitesWithSuggestedLinks = ["hrblock.com", "1040.com", "freetaxusa.com"];
- DirectoryLinksProvider._handleManyLinksChanged();
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Removing site6.com as a topsite has no impact on _topSitesWithSuggestedLinks.
- let popped = topSites.pop();
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Removing freetaxusa.com as a topsite will remove it from _topSitesWithSuggestedLinks.
- popped = topSites.pop();
- expectedTopSitesWithSuggestedLinks.pop();
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Re-adding freetaxusa.com as a topsite will add it to _topSitesWithSuggestedLinks.
- topSites.push(popped);
- expectedTopSitesWithSuggestedLinks.push(popped);
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
-});
-
-add_task(function* test_suggestedAttributes() {
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let frecent_sites = "addons.mozilla.org,air.mozilla.org,blog.mozilla.org,bugzilla.mozilla.org,developer.mozilla.org,etherpad.mozilla.org,forums.mozillazine.org,hacks.mozilla.org,hg.mozilla.org,mozilla.org,planet.mozilla.org,quality.mozilla.org,support.mozilla.org,treeherder.mozilla.org,wiki.mozilla.org".split(",");
- let imageURI = "https://image/";
- let title = "the title";
- let type = "affiliate";
- let url = "http://test.url/";
- let adgroup_name = "Mozilla";
- let data = {
- suggested: [{
- frecent_sites,
- imageURI,
- title,
- type,
- url,
- adgroup_name
- }]
- };
- let dataURI = "data:application/json," + escape(JSON.stringify(data));
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- // Make sure we get the expected attributes on the suggested tile
- let link = gLinks.getLinks()[0];
- do_check_eq(link.imageURI, imageURI);
- do_check_eq(link.targetedName, "Mozilla");
- do_check_eq(link.targetedSite, frecent_sites[0]);
- do_check_eq(link.title, title);
- do_check_eq(link.type, type);
- do_check_eq(link.url, url);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
-});
-
-add_task(function* test_frequencyCappedSites_views() {
- Services.prefs.setCharPref(kPingUrlPref, "");
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let testUrl = "http://frequency.capped/link";
- let targets = ["top.site.com"];
- let data = {
- suggested: [{
- type: "affiliate",
- frecent_sites: targets,
- url: testUrl,
- frequency_caps: {daily: 5},
- adgroup_name: "Test"
- }],
- directory: [{
- type: "organic",
- url: "http://directory.site/"
- }]
- };
- let dataURI = "data:application/json," + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- function synthesizeAction(action) {
- DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: targets[0],
- url: testUrl
- }
- }], action, 0);
- }
-
- function checkFirstTypeAndLength(type, length) {
- let links = gLinks.getLinks();
- do_check_eq(links[0].type, type);
- do_check_eq(links.length, length);
- }
-
- // Make sure we get 5 views of the link before it is removed
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("organic", 1);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
- Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-});
-
-add_task(function* test_frequencyCappedSites_click() {
- Services.prefs.setCharPref(kPingUrlPref, "");
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let testUrl = "http://frequency.capped/link";
- let targets = ["top.site.com"];
- let data = {
- suggested: [{
- type: "affiliate",
- frecent_sites: targets,
- url: testUrl,
- adgroup_name: "Test"
- }],
- directory: [{
- type: "organic",
- url: "http://directory.site/"
- }]
- };
- let dataURI = "data:application/json," + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- function synthesizeAction(action) {
- DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: targets[0],
- url: testUrl
- }
- }], action, 0);
- }
-
- function checkFirstTypeAndLength(type, length) {
- let links = gLinks.getLinks();
- do_check_eq(links[0].type, type);
- do_check_eq(links.length, length);
- }
-
- // Make sure the link disappears after the first click
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("click");
- checkFirstTypeAndLength("organic", 1);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
- Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-});
-
-add_task(function* test_fetchAndCacheLinks_local() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // Trigger cache of data or chrome uri files in profD
- yield DirectoryLinksProvider._fetchAndCacheLinks(kTestURL);
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-});
-
-add_task(function* test_fetchAndCacheLinks_remote() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // this must trigger directory links json download and save it to cache file
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kExampleURL + "%LOCALE%");
- do_check_eq(gLastRequestPath, kExamplePath + "en-US");
- let data = yield readJsonFile();
- isIdentical(data, kHttpHandlerData[kExamplePath]);
-});
-
-add_task(function* test_fetchAndCacheLinks_malformedURI() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- let someJunk = "some junk";
- try {
- yield DirectoryLinksProvider._fetchAndCacheLinks(someJunk);
- do_throw("Malformed URIs should fail")
- } catch (e) {
- do_check_eq(e, "Error fetching " + someJunk)
- }
-
- // File should be empty.
- let data = yield readJsonFile();
- isIdentical(data, "");
-});
-
-add_task(function* test_fetchAndCacheLinks_unknownHost() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- let nonExistentServer = "http://localhost:56789/";
- try {
- yield DirectoryLinksProvider._fetchAndCacheLinks(nonExistentServer);
- do_throw("BAD URIs should fail");
- } catch (e) {
- do_check_true(e.startsWith("Fetching " + nonExistentServer + " results in error code: "))
- }
-
- // File should be empty.
- let data = yield readJsonFile();
- isIdentical(data, "");
-});
-
-add_task(function* test_fetchAndCacheLinks_non200Status() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kFailURL);
- do_check_eq(gLastRequestPath, kFailPath);
- let data = yield readJsonFile();
- isIdentical(data, {});
-});
-
-// To test onManyLinksChanged observer, trigger a fetch
-add_task(function* test_DirectoryLinksProvider__linkObservers() {
- yield DirectoryLinksProvider.init();
-
- let testObserver = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(testObserver);
- do_check_eq(DirectoryLinksProvider._observers.size, 1);
- DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
-
- yield testObserver.deferred.promise;
- DirectoryLinksProvider._removeObservers();
- do_check_eq(DirectoryLinksProvider._observers.size, 0);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider__prefObserver_url() {
- yield promiseSetupDirectoryLinksProvider({linksURL: kTestURL});
-
- let links = yield fetchData();
- do_check_eq(links.length, 1);
- let expectedData = [{url: "http://example.com", title: "LocalSource", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
- isIdentical(links, expectedData);
-
- // tests these 2 things:
- // 1. _linksURL is properly set after the pref change
- // 2. invalid source url is correctly handled
- let exampleUrl = 'http://localhost:56789/bad';
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, exampleUrl);
- do_check_eq(DirectoryLinksProvider._linksURL, exampleUrl);
-
- // since the download fail, the directory file must remain the same
- let newLinks = yield fetchData();
- isIdentical(newLinks, expectedData);
-
- // now remove the file, and re-download
- yield cleanJsonFile();
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, exampleUrl + " ");
- // we now should see empty links
- newLinks = yield fetchData();
- isIdentical(newLinks, []);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinks_noDirectoryData() {
- let data = {
- "directory": [],
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 0);
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinks_badData() {
- let data = {
- "en-US": {
- "en-US": [{url: "http://example.com", title: "US"}],
- },
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Make sure we get nothing for incorrectly formatted data
- let links = yield fetchData();
- do_check_eq(links.length, 0);
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function test_DirectoryLinksProvider_needsDownload() {
- // test timestamping
- DirectoryLinksProvider._lastDownloadMS = 0;
- do_check_true(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = Date.now();
- do_check_false(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = Date.now() - (60*60*24 + 1)*1000;
- do_check_true(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = 0;
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchAndCacheLinksIfNecessary() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // explicitly change source url to cause the download during setup
- yield promiseSetupDirectoryLinksProvider({linksURL: kTestURL+" "});
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary();
-
- // inspect lastDownloadMS timestamp which should be 5 seconds less then now()
- let lastDownloadMS = DirectoryLinksProvider._lastDownloadMS;
- do_check_true((Date.now() - lastDownloadMS) < 5000);
-
- // we should have fetched a new file during setup
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- // attempt to download again - the timestamp should not change
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary();
- do_check_eq(DirectoryLinksProvider._lastDownloadMS, lastDownloadMS);
-
- // clean the file and force the download
- yield cleanJsonFile();
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- // make sure that failed download does not corrupt the file, nor changes lastDownloadMS
- lastDownloadMS = DirectoryLinksProvider._lastDownloadMS;
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, "http://");
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- data = yield readJsonFile();
- isIdentical(data, kURLData);
- do_check_eq(DirectoryLinksProvider._lastDownloadMS, lastDownloadMS);
-
- // _fetchAndCacheLinksIfNecessary must return same promise if download is in progress
- let downloadPromise = DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- let anotherPromise = DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- do_check_true(downloadPromise === anotherPromise);
- yield downloadPromise;
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnPrefChange() {
- yield DirectoryLinksProvider.init();
-
- let testObserver = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield cleanJsonFile();
- // ensure that provider does not think it needs to download
- do_check_false(DirectoryLinksProvider._needsDownload);
-
- // change the source URL, which should force directory download
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kExampleURL);
- // then wait for testObserver to fire and test that json is downloaded
- yield testObserver.deferred.promise;
- do_check_eq(gLastRequestPath, kExamplePath);
- let data = yield readJsonFile();
- isIdentical(data, kHttpHandlerData[kExamplePath]);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnShow() {
- yield promiseSetupDirectoryLinksProvider();
-
- // set lastdownload to 0 to make DirectoryLinksProvider want to download
- DirectoryLinksProvider._lastDownloadMS = 0;
- do_check_true(DirectoryLinksProvider._needsDownload);
-
- // download should happen on view
- yield DirectoryLinksProvider.reportSitesAction([], "view");
- do_check_true(DirectoryLinksProvider._lastDownloadMS != 0);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnInit() {
- // ensure preferences are set to defaults
- yield promiseSetupDirectoryLinksProvider();
- // now clean to provider, so we can init it again
- yield promiseCleanDirectoryLinksProvider();
-
- yield cleanJsonFile();
- yield DirectoryLinksProvider.init();
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinksFromCorruptedFile() {
- yield promiseSetupDirectoryLinksProvider();
-
- // write bogus json to a file and attempt to fetch from it
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.profileDir, DIRECTORY_LINKS_FILE);
- yield OS.File.writeAtomic(directoryLinksFilePath, '{"en-US":');
- let data = yield fetchData();
- isIdentical(data, []);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedLinks() {
- let data = {"directory": [
- {url: "ftp://example.com"},
- {url: "http://example.net"},
- {url: "javascript:5"},
- {url: "https://example.com"},
- {url: "httpJUNKjavascript:42"},
- {url: "data:text/plain,hi"},
- {url: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining url should be http and https
- do_check_eq(links[0].url, data["directory"][1].url);
- do_check_eq(links[1].url, data["directory"][3].url);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedImages() {
- let data = {"directory": [
- {url: "http://example.com", imageURI: "ftp://example.com"},
- {url: "http://example.com", imageURI: "http://example.net"},
- {url: "http://example.com", imageURI: "javascript:5"},
- {url: "http://example.com", imageURI: "https://example.com"},
- {url: "http://example.com", imageURI: "httpJUNKjavascript:42"},
- {url: "http://example.com", imageURI: "data:text/plain,hi"},
- {url: "http://example.com", imageURI: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining images should be https and data
- do_check_eq(links[0].imageURI, data["directory"][3].imageURI);
- do_check_eq(links[1].imageURI, data["directory"][5].imageURI);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedImages_base() {
- let data = {"directory": [
- {url: "http://example1.com", imageURI: "https://example.com"},
- {url: "http://example2.com", imageURI: "https://tiles.cdn.mozilla.net"},
- {url: "http://example3.com", imageURI: "https://tiles2.cdn.mozilla.net"},
- {url: "http://example4.com", enhancedImageURI: "https://mozilla.net"},
- {url: "http://example5.com", imageURI: "data:text/plain,hi"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Pretend we're using the default pref to trigger base matching
- DirectoryLinksProvider.__linksURLModified = false;
-
- let links = yield fetchData();
- do_check_eq(links.length, 4);
-
- // The only remaining images should be https with mozilla.net or data URI
- do_check_eq(links[0].url, data["directory"][1].url);
- do_check_eq(links[1].url, data["directory"][2].url);
- do_check_eq(links[2].url, data["directory"][3].url);
- do_check_eq(links[3].url, data["directory"][4].url);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedEnhancedImages() {
- let data = {"directory": [
- {url: "http://example.com", enhancedImageURI: "ftp://example.com"},
- {url: "http://example.com", enhancedImageURI: "http://example.net"},
- {url: "http://example.com", enhancedImageURI: "javascript:5"},
- {url: "http://example.com", enhancedImageURI: "https://example.com"},
- {url: "http://example.com", enhancedImageURI: "httpJUNKjavascript:42"},
- {url: "http://example.com", enhancedImageURI: "data:text/plain,hi"},
- {url: "http://example.com", enhancedImageURI: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining enhancedImages should be http and https and data
- do_check_eq(links[0].enhancedImageURI, data["directory"][3].enhancedImageURI);
- do_check_eq(links[1].enhancedImageURI, data["directory"][5].enhancedImageURI);
-});
-
-add_task(function* test_DirectoryLinksProvider_getEnhancedLink() {
- let data = {"enhanced": [
- {url: "http://example.net", enhancedImageURI: "data:,net1"},
- {url: "http://example.com", enhancedImageURI: "data:,com1"},
- {url: "http://example.com", enhancedImageURI: "data:,com2"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 0); // There are no directory links.
-
- function checkEnhanced(url, image) {
- let enhanced = DirectoryLinksProvider.getEnhancedLink({url: url});
- do_check_eq(enhanced && enhanced.enhancedImageURI, image);
- }
-
- // Get the expected image for the same site
- checkEnhanced("http://example.net/", "data:,net1");
- checkEnhanced("http://example.net/path", "data:,net1");
- checkEnhanced("https://www.example.net/", "data:,net1");
- checkEnhanced("https://www3.example.net/", "data:,net1");
-
- // Get the image of the last entry
- checkEnhanced("http://example.com", "data:,com2");
-
- // Get the inline enhanced image
- let inline = DirectoryLinksProvider.getEnhancedLink({
- url: "http://example.com/echo",
- enhancedImageURI: "data:,echo",
- });
- do_check_eq(inline.enhancedImageURI, "data:,echo");
- do_check_eq(inline.url, "http://example.com/echo");
-
- // Undefined for not enhanced
- checkEnhanced("http://sub.example.net/", undefined);
- checkEnhanced("http://example.org", undefined);
- checkEnhanced("http://localhost", undefined);
- checkEnhanced("http://127.0.0.1", undefined);
-
- // Make sure old data is not cached
- data = {"enhanced": [
- {url: "http://example.com", enhancedImageURI: "data:,fresh"},
- ]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- links = yield fetchData();
- do_check_eq(links.length, 0); // There are no directory links.
- checkEnhanced("http://example.net", undefined);
- checkEnhanced("http://example.com", "data:,fresh");
-});
-
-add_task(function* test_DirectoryLinksProvider_enhancedURIs() {
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let data = {
- "suggested": [
- {url: "http://example.net", enhancedImageURI: "data:,net1", title:"SuggestedTitle", adgroup_name: "Test", frecent_sites: ["test.com"]}
- ],
- "directory": [
- {url: "http://example.net", enhancedImageURI: "data:,net2", title:"DirectoryTitle"}
- ]
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- // Check that we've saved the directory tile.
- let links = yield fetchData();
- do_check_eq(links.length, 1);
- do_check_eq(links[0].title, "DirectoryTitle");
- do_check_eq(links[0].enhancedImageURI, "data:,net2");
-
- // Check that the suggested tile with the same URL replaces the directory tile.
- links = gLinks.getLinks();
- do_check_eq(links.length, 1);
- do_check_eq(links[0].title, "SuggestedTitle");
- do_check_eq(links[0].enhancedImageURI, "data:,net1");
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
-});
-
-add_task(function test_DirectoryLinksProvider_setDefaultEnhanced() {
- function checkDefault(expected) {
- Services.prefs.clearUserPref(kNewtabEnhancedPref);
- do_check_eq(Services.prefs.getBoolPref(kNewtabEnhancedPref), expected);
- }
-
- // Use the default donottrack prefs (enabled = false)
- Services.prefs.clearUserPref("privacy.donottrackheader.enabled");
- checkDefault(true);
-
- // Turn on DNT - no track
- Services.prefs.setBoolPref("privacy.donottrackheader.enabled", true);
- checkDefault(false);
-
- // Turn off DNT header
- Services.prefs.clearUserPref("privacy.donottrackheader.enabled");
- checkDefault(true);
-
- // Clean up
- Services.prefs.clearUserPref("privacy.donottrackheader.value");
-});
-
-add_task(function* test_timeSensetiveSuggestedTiles() {
- // make tile json with start and end dates
- let testStartTime = Date.now();
- // start date is now + 1 seconds
- let startDate = new Date(testStartTime + 1000);
- // end date is now + 3 seconds
- let endDate = new Date(testStartTime + 3000);
- let suggestedTile = Object.assign({
- time_limits: {
- start: startDate.toISOString(),
- end: endDate.toISOString(),
- }
- }, suggestedTile1);
-
- // Initial setup
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestTimingRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // this tester will fire twice: when start limit is reached and when tile link
- // is removed upon end of the campaign, in which case deleteFlag will be set
- function TestTimingRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link, ignoreFlag, deleteFlag) => {
- // if we are not deleting, add link to links, so we can catch it's removal
- if (!deleteFlag) {
- links.unshift(link);
- }
-
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "1040.com"]);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- let timeDelta = Date.now() - testStartTime;
- if (!deleteFlag) {
- // this is start timeout corresponding to campaign start
- // a seconds must pass and targetedSite must be set
- do_print("TESTING START timeDelta: " + timeDelta);
- do_check_true(timeDelta >= 1000 / 2); // check for at least half time
- do_check_eq(link.targetedSite, "hrblock.com");
- do_check_true(DirectoryLinksProvider._campaignTimeoutID);
- }
- else {
- // this is the campaign end timeout, so 3 seconds must pass
- // and timeout should be cleared
- do_print("TESTING END timeDelta: " + timeDelta);
- do_check_true(timeDelta >= 3000 / 2); // check for at least half time
- do_check_false(link.targetedSite);
- do_check_false(DirectoryLinksProvider._campaignTimeoutID);
- resolve();
- }
- };
- });
- }
-
- // _updateSuggestedTile() is called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // shoudl suggest nothing
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // set links back to contain directory tile only
- links.shift();
-
- // drop the end time - we should pick up the tile
- suggestedTile.time_limits.end = null;
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
-
- // redownload json and getLinks to force time recomputation
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
-
- // ensure that there's a link returned by _updateSuggestedTile and no timeout
- let deferred = Promise.defer();
- DirectoryLinksProvider.getLinks(() => {
- let link = DirectoryLinksProvider._updateSuggestedTile();
- // we should have a suggested tile and no timeout
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- do_check_false(DirectoryLinksProvider._campaignTimeoutID);
- deferred.resolve();
- });
- yield deferred.promise;
-
- // repeat the test for end time only
- suggestedTile.time_limits.start = null;
- suggestedTile.time_limits.end = (new Date(Date.now() + 3000)).toISOString();
-
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
-
- // redownload json and call getLinks() to force time recomputation
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
-
- // ensure that there's a link returned by _updateSuggestedTile and timeout set
- deferred = Promise.defer();
- DirectoryLinksProvider.getLinks(() => {
- let link = DirectoryLinksProvider._updateSuggestedTile();
- // we should have a suggested tile and timeout set
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- do_check_true(DirectoryLinksProvider._campaignTimeoutID);
- DirectoryLinksProvider._clearCampaignTimeout();
- deferred.resolve();
- });
- yield deferred.promise;
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function test_setupStartEndTime() {
- let currentTime = Date.now();
- let dt = new Date(currentTime);
- let link = {
- time_limits: {
- start: dt.toISOString()
- }
- };
-
- // test ISO translation
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_eq(link.startTime, currentTime);
-
- // test localtime translation
- let shiftedDate = new Date(currentTime - dt.getTimezoneOffset()*60*1000);
- link.time_limits.start = shiftedDate.toISOString().replace(/Z$/, "");
-
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_eq(link.startTime, currentTime);
-
- // throw some garbage into date string
- delete link.startTime;
- link.time_limits.start = "no date"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-
- link.time_limits.start = "2015-99999-01T00:00:00"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-
- link.time_limits.start = "20150501T00:00:00"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-});
-
-add_task(function* test_DirectoryLinksProvider_frequencyCapSetup() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- yield promiseCleanDirectoryLinksProvider();
- yield DirectoryLinksProvider._readFrequencyCapFile();
- isIdentical(DirectoryLinksProvider._frequencyCaps, {});
-
- // setup few links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "2",
- frequency_caps: {daily: 1, total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "3",
- frequency_caps: {total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "4",
- frequency_caps: {daily: 1}
- });
- let freqCapsObject = DirectoryLinksProvider._frequencyCaps;
- let capObject = freqCapsObject["1"];
- let defaultDaily = capObject.dailyCap;
- let defaultTotal = capObject.totalCap;
- // check if we have defaults set
- do_check_true(capObject.dailyCap > 0);
- do_check_true(capObject.totalCap > 0);
- // check if defaults are properly handled
- do_check_eq(freqCapsObject["2"].dailyCap, 1);
- do_check_eq(freqCapsObject["2"].totalCap, 2);
- do_check_eq(freqCapsObject["3"].dailyCap, defaultDaily);
- do_check_eq(freqCapsObject["3"].totalCap, 2);
- do_check_eq(freqCapsObject["4"].dailyCap, 1);
- do_check_eq(freqCapsObject["4"].totalCap, defaultTotal);
-
- // write object to file
- yield DirectoryLinksProvider._writeFrequencyCapFile();
- // empty out freqCapsObject and read file back
- DirectoryLinksProvider._frequencyCaps = {};
- yield DirectoryLinksProvider._readFrequencyCapFile();
- // re-ran tests - they should all pass
- do_check_eq(freqCapsObject["2"].dailyCap, 1);
- do_check_eq(freqCapsObject["2"].totalCap, 2);
- do_check_eq(freqCapsObject["3"].dailyCap, defaultDaily);
- do_check_eq(freqCapsObject["3"].totalCap, 2);
- do_check_eq(freqCapsObject["4"].dailyCap, 1);
- do_check_eq(freqCapsObject["4"].totalCap, defaultTotal);
-
- // wait a second and prune frequency caps
- yield new Promise(resolve => {
- setTimeout(resolve, 1100);
- });
-
- // update one link and create another
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "3",
- frequency_caps: {daily: 1, total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "7",
- frequency_caps: {daily: 1, total: 2}
- });
- // now prune the ones that have been in the object longer than 1 second
- DirectoryLinksProvider._pruneFrequencyCapUrls(1000);
- // make sure all keys but "3" and "7" are deleted
- Object.keys(DirectoryLinksProvider._frequencyCaps).forEach(key => {
- do_check_true(key == "3" || key == "7");
- });
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getFrequencyCapLogic() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- frequency_caps: {daily: 2, total: 4}
- });
-
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- // exhaust daily views
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // now step into the furture
- let _wasTodayOrig = DirectoryLinksProvider._wasToday;
- DirectoryLinksProvider._wasToday = function () { return false; }
- // exhaust total views
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- DirectoryLinksProvider._addFrequencyCapView("1")
- // reached totalViews 4, should return false
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // add more views by updating configuration
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- frequency_caps: {daily: 5, total: 10}
- });
- // should be true, since we have more total views
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // set click flag
- DirectoryLinksProvider._setFrequencyCapClick("1");
- // always false after click
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // use unknown urls and ensure nothing breaks
- DirectoryLinksProvider._addFrequencyCapView("nosuch.url");
- DirectoryLinksProvider._setFrequencyCapClick("nosuch.url");
- // testing unknown url should always return false
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("nosuch.url"));
-
- // reset _wasToday back to original function
- DirectoryLinksProvider._wasToday = _wasTodayOrig;
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getFrequencyCapReportSiteAction() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "bar.com",
- frequency_caps: {daily: 2, total: 4}
- });
-
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("bar.com"));
- // report site action
- yield DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: "foo.com",
- url: "bar.com"
- },
- isPinned: function() { return false; },
- }], "view", 0);
-
- // read file content and ensure that view counters are updated
- let data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_eq(data["bar.com"].dailyViews, 1);
- do_check_eq(data["bar.com"].totalViews, 1);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_ClickRemoval() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
- let landingUrl = "http://foo.com";
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: landingUrl,
- frequency_caps: {daily: 2, total: 4}
- });
-
- // add views
- DirectoryLinksProvider._addFrequencyCapView(landingUrl)
- DirectoryLinksProvider._addFrequencyCapView(landingUrl)
- // make a click
- DirectoryLinksProvider._setFrequencyCapClick(landingUrl);
-
- // views must be 2 and click must be set
- do_check_eq(DirectoryLinksProvider._frequencyCaps[landingUrl].totalViews, 2);
- do_check_true(DirectoryLinksProvider._frequencyCaps[landingUrl].clicked);
-
- // now insert a visit into places
- yield new Promise(resolve => {
- PlacesUtils.asyncHistory.updatePlaces(
- {
- uri: NetUtil.newURI(landingUrl),
- title: "HELLO",
- visits: [{
- visitDate: Date.now()*1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK
- }]
- },
- {
- handleError: function () { do_check_true(false); },
- handleResult: function () {},
- handleCompletion: function () { resolve(); }
- }
- );
- });
-
- function UrlDeletionTester() {
- this.promise = new Promise(resolve => {
- this.onDeleteURI = (directoryLinksProvider, link) => {
- resolve();
- };
- this.onClearHistory = (directoryLinksProvider) => {
- resolve();
- };
- });
- }
-
- let testObserver = new UrlDeletionTester();
- DirectoryLinksProvider.addObserver(testObserver);
-
- PlacesUtils.bhistory.removePage(NetUtil.newURI(landingUrl));
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
- // views must be 2 and click should not exist
- do_check_eq(DirectoryLinksProvider._frequencyCaps[landingUrl].totalViews, 2);
- do_check_false(DirectoryLinksProvider._frequencyCaps[landingUrl].hasOwnProperty("clicked"));
-
- // verify that disk written data is kosher
- let data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_eq(data[landingUrl].totalViews, 2);
- do_check_false(data[landingUrl].hasOwnProperty("clicked"));
-
- // now test clear history
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: landingUrl,
- frequency_caps: {daily: 2, total: 4}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "http://bar.com",
- frequency_caps: {daily: 2, total: 4}
- });
-
- DirectoryLinksProvider._setFrequencyCapClick(landingUrl);
- DirectoryLinksProvider._setFrequencyCapClick("http://bar.com");
- // both tiles must have clicked
- do_check_true(DirectoryLinksProvider._frequencyCaps[landingUrl].clicked);
- do_check_true(DirectoryLinksProvider._frequencyCaps["http://bar.com"].clicked);
-
- testObserver = new UrlDeletionTester();
- DirectoryLinksProvider.addObserver(testObserver);
- yield PlacesTestUtils.clearHistory();
-
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
- // no clicks should remain in the cap object
- do_check_false(DirectoryLinksProvider._frequencyCaps[landingUrl].hasOwnProperty("clicked"));
- do_check_false(DirectoryLinksProvider._frequencyCaps["http://bar.com"].hasOwnProperty("clicked"));
-
- // verify that disk written data is kosher
- data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_false(data[landingUrl].hasOwnProperty("clicked"));
- do_check_false(data["http://bar.com"].hasOwnProperty("clicked"));
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function test_DirectoryLinksProvider_anonymous() {
- do_check_true(DirectoryLinksProvider._newXHR().mozAnon);
-});
-
-add_task(function* test_sanitizeExplanation() {
- // Note: this is a basic test to ensure we applied sanitization to the link explanation.
- // Full testing for appropriate sanitization is done in parser/xml/test/unit/test_sanitizer.js.
- let data = {"suggested": [suggestedTile5]};
- let dataURI = 'data:application/json,' + encodeURIComponent(JSON.stringify(data));
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- yield fetchData();
-
- let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
- do_check_eq(suggestedSites.indexOf("eviltarget.com"), 0);
- do_check_eq(suggestedSites.length, 1);
-
- let suggestedLink = [...DirectoryLinksProvider._suggestedLinks.get(suggestedSites[0]).values()][0];
- do_check_eq(suggestedLink.explanation, "This is an evil tile X muhahaha");
- do_check_eq(suggestedLink.targetedName, "WE ARE EVIL ");
-});
-
-add_task(function* test_inadjecentSites() {
- let suggestedTile = Object.assign({
- check_inadjacency: true
- }, suggestedTile1);
-
- // Initial setup
- let topSites = ["1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestFirstRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => {
- origCurrentTopSiteCount.apply(DirectoryLinksProvider);
- return 8;
- };
-
- // store oroginal inadjacent sites url
- let origInadjacentSitesUrl = DirectoryLinksProvider._inadjacentSitesUrl;
-
- // loading inadjacent sites list function
- function setInadjacentSites(sites) {
- let badSiteB64 = [];
- sites.forEach(site => {
- badSiteB64.push(DirectoryLinksProvider._generateHash(site));
- });
- let theList = {"domains": badSiteB64};
- let uri = 'data:application/json,' + JSON.stringify(theList);
- DirectoryLinksProvider._inadjacentSitesUrl = uri;
- return DirectoryLinksProvider._loadInadjacentSites();
- }
-
- // setup gLinks loader
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
-
- function updateNewTabCache() {
- gLinks.populateCache();
- return new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
- }
-
- // no suggested file
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
- // _avoidInadjacentSites should be set, since link.check_inadjacency is on
- do_check_true(DirectoryLinksProvider._avoidInadjacentSites);
- // make sure example.com is included in inadjacent sites list
- do_check_true(DirectoryLinksProvider._isInadjacentLink({baseDomain: "example.com"}));
-
- function TestFirstRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- do_check_eq(link.url, suggestedTile.url);
- do_check_eq(link.type, "affiliate");
- resolve();
- };
- });
- }
-
- // Test first call to '_updateSuggestedTile()', called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // update newtab cache
- yield updateNewTabCache();
- // this should have set
- do_check_true(DirectoryLinksProvider._avoidInadjacentSites);
-
- // there should be siggested link
- let link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_eq(link.url, "http://turbotax.com");
- // and it should have avoidInadjacentSites flag
- do_check_true(link.check_inadjacency);
-
- // make someothersite.com inadjacent
- yield setInadjacentSites(["someothersite.com"]);
-
- // there should be no suggested link
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_false(link);
- do_check_true(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // _handleLinkChanged must return true on inadjacent site
- do_check_true(DirectoryLinksProvider._handleLinkChanged({
- url: "http://someothersite.com",
- type: "history",
- }));
- // _handleLinkChanged must return false on ok site
- do_check_false(DirectoryLinksProvider._handleLinkChanged({
- url: "http://foobar.com",
- type: "history",
- }));
-
- // change inadjacent list to sites not on newtab page
- yield setInadjacentSites(["foo.com", "bar.com"]);
-
- link = DirectoryLinksProvider._updateSuggestedTile();
- // we should now have a link
- do_check_true(link);
- do_check_eq(link.url, "http://turbotax.com");
-
- // make newtab offending again
- yield setInadjacentSites(["someothersite.com", "foo.com"]);
- // there should be no suggested link
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_false(link);
- do_check_true(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // remove avoidInadjacentSites flag from suggested tile and reload json
- delete suggestedTile.check_inadjacency;
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
- yield fetchData();
-
- // inadjacent checking should be disabled
- do_check_false(DirectoryLinksProvider._avoidInadjacentSites);
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(link);
- do_check_eq(link.url, "http://turbotax.com");
- do_check_false(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // _handleLinkChanged should return false now, even if newtab has bad site
- do_check_false(DirectoryLinksProvider._handleLinkChanged({
- url: "http://someothersite.com",
- type: "history",
- }));
-
- // test _isInadjacentLink
- do_check_true(DirectoryLinksProvider._isInadjacentLink({baseDomain: "someothersite.com"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({baseDomain: "bar.com"}));
- do_check_true(DirectoryLinksProvider._isInadjacentLink({url: "http://www.someothersite.com"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "http://www.bar.com"}));
- // try to crash _isInadjacentLink
- do_check_false(DirectoryLinksProvider._isInadjacentLink({baseDomain: ""}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: ""}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "http://localhost:8081/"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "abracodabra"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({}));
-
- // test _checkForInadjacentSites
- do_check_true(DirectoryLinksProvider._checkForInadjacentSites());
-
- // Cleanup
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider._inadjacentSitesUrl = origInadjacentSitesUrl;
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_blockSuggestedTiles() {
- // Initial setup
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- // load the links
- yield new Promise(resolve => {
- DirectoryLinksProvider.getLinks(resolve);
- });
-
- // ensure that tile is suggested
- let suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // block suggested tile in a regular way
- DirectoryLinksProvider.reportSitesAction([{
- isPinned: function() { return false; },
- link: Object.assign({frecency: 1000}, suggestedLink)
- }], "block", 0);
-
- // suggested tile still must be recommended
- suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // timestamp suggested_block in the frequency cap object
- DirectoryLinksProvider.handleSuggestedTileBlock();
- // no more recommendations should be seen
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // move lastUpdated for suggested tile into the past
- DirectoryLinksProvider._frequencyCaps["ignore://suggested_block"].lastUpdated = Date.now() - 25*60*60*1000;
- // ensure that suggested tile updates again
- suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
diff --git a/browser/modules/test/xpcshell/test_LaterRun.js b/browser/modules/test/xpcshell/test_LaterRun.js
deleted file mode 100644
index 7b45c7cd5..000000000
--- a/browser/modules/test/xpcshell/test_LaterRun.js
+++ /dev/null
@@ -1,138 +0,0 @@
-"use strict";
-
-const kEnabledPref = "browser.laterrun.enabled";
-const kPagePrefRoot = "browser.laterrun.pages.";
-const kSessionCountPref = "browser.laterrun.bookkeeping.sessionCount";
-const kProfileCreationTime = "browser.laterrun.bookkeeping.profileCreationTime";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource:///modules/LaterRun.jsm");
-
-Services.prefs.setBoolPref(kEnabledPref, true);
-Components.utils.import("resource://testing-common/AppInfo.jsm");
-updateAppInfo();
-
-add_task(function* test_page_applies() {
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "https://www.mozilla.org/%VENDOR%/%NAME%/%ID%/%VERSION%/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
-
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get included in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 1, "Got 1 page");
- let page = pages[0];
- Assert.equal(page.pref, kPagePrefRoot + "test_LaterRun_unittest.", "Should know its own pref");
- Assert.equal(page.minimumHoursSinceInstall, 10, "Needs to have 10 hours since install");
- Assert.equal(page.minimumSessionCount, 3, "Needs to have 3 sessions");
- Assert.equal(page.requireBoth, false, "Either requirement is enough");
- let expectedURL = "https://www.mozilla.org/" +
- Services.appinfo.vendor + "/" +
- Services.appinfo.name + "/" +
- Services.appinfo.ID + "/" +
- Services.appinfo.version + "/";
- Assert.equal(page.url, expectedURL, "URL is stored correctly");
-
- Assert.ok(page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Applies when session count has been met.");
- Assert.ok(page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Applies when session count has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Applies when total session time has been met.");
- Assert.ok(page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Applies when total session time has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Applies when both time and session count have been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when neither time and session count have been met.");
-
- page.requireBoth = true;
-
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Does not apply when only session count has been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Does not apply when only session count has been exceeded.");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Does not apply when only total session time has been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Does not apply when only total session time has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Applies when both time and session count have been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when neither time and session count have been met.");
-
- // Check that pages that have run never apply:
- Services.prefs.setBoolPref(kPagePrefRoot + "test_LaterRun_unittest.hasRun", true);
- page.requireBoth = false;
-
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Does not apply when page has already run (sessionCount equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Does not apply when page has already run (sessionCount exceeding).");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Does not apply when page has already run (hoursSinceInstall equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Does not apply when page has already run (hoursSinceInstall exceeding).");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Does not apply when page has already run (both criteria equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when page has already run (both criteria insufficient anyway).");
-
- clearAllPagePrefs();
-});
-
-add_task(function* test_get_URL() {
- Services.prefs.setIntPref(kProfileCreationTime, Math.floor((Date.now() - 11 * 60 * 60 * 1000) / 1000));
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "https://www.mozilla.org/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get included in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 1, "Should only be 1 matching page");
- let page = pages[0];
- let url;
- do {
- url = LaterRun.getURL();
- // We have to loop because it's possible Firefox ships with other URLs that get triggered by
- // this test.
- } while (url && url != "https://www.mozilla.org/");
- Assert.equal(url, "https://www.mozilla.org/", "URL should be as expected when prefs are set.");
- Assert.ok(Services.prefs.prefHasUserValue(kPagePrefRoot + "test_LaterRun_unittest.hasRun"), "Should have set pref");
- Assert.ok(Services.prefs.getBoolPref(kPagePrefRoot + "test_LaterRun_unittest.hasRun"), "Should have set pref to true");
- Assert.ok(page.hasRun, "Other page objects should know it has run, too.");
-
- clearAllPagePrefs();
-});
-
-add_task(function* test_insecure_urls() {
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "http://www.mozilla.org/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get triggered in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 0, "URL with non-https scheme should get ignored");
- clearAllPagePrefs();
-});
-
-add_task(function* test_dynamic_pref_getter_setter() {
- delete LaterRun._sessionCount;
- Services.prefs.setIntPref(kSessionCountPref, 0);
- Assert.equal(LaterRun.sessionCount, 0, "Should start at 0");
-
- LaterRun.sessionCount++;
- Assert.equal(LaterRun.sessionCount, 1, "Should increment.");
- Assert.equal(Services.prefs.getIntPref(kSessionCountPref), 1, "Should update pref");
-});
-
-function clearAllPagePrefs() {
- let allChangedPrefs = Services.prefs.getChildList(kPagePrefRoot);
- for (let pref of allChangedPrefs) {
- Services.prefs.clearUserPref(pref);
- }
-}
-
diff --git a/browser/modules/test/xpcshell/test_SitePermissions.js b/browser/modules/test/xpcshell/test_SitePermissions.js
deleted file mode 100644
index 808d96599..000000000
--- a/browser/modules/test/xpcshell/test_SitePermissions.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-Components.utils.import("resource:///modules/SitePermissions.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-add_task(function* testPermissionsListing() {
- Assert.deepEqual(SitePermissions.listPermissions().sort(),
- ["camera", "cookie", "desktop-notification", "geo", "image",
- "indexedDB", "install", "microphone", "popup", "screen"],
- "Correct list of all permissions");
-});
-
-add_task(function* testGetAllByURI() {
- // check that it returns an empty array on an invalid URI
- // like a file URI, which doesn't support site permissions
- let wrongURI = Services.io.newURI("file:///example.js", null, null)
- Assert.deepEqual(SitePermissions.getAllByURI(wrongURI), []);
-
- let uri = Services.io.newURI("https://example.com", null, null)
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
-
- SitePermissions.set(uri, "camera", SitePermissions.ALLOW);
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW }
- ]);
-
- SitePermissions.set(uri, "microphone", SitePermissions.SESSION);
- SitePermissions.set(uri, "desktop-notification", SitePermissions.BLOCK);
-
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW },
- { id: "microphone", state: SitePermissions.SESSION },
- { id: "desktop-notification", state: SitePermissions.BLOCK }
- ]);
-
- SitePermissions.remove(uri, "microphone");
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW },
- { id: "desktop-notification", state: SitePermissions.BLOCK }
- ]);
-
- SitePermissions.remove(uri, "camera");
- SitePermissions.remove(uri, "desktop-notification");
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
-
- // XXX Bug 1303108 - Control Center should only show non-default permissions
- SitePermissions.set(uri, "addon", SitePermissions.BLOCK);
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
- SitePermissions.remove(uri, "addon");
-});
-
-add_task(function* testGetPermissionDetailsByURI() {
- // check that it returns an empty array on an invalid URI
- // like a file URI, which doesn't support site permissions
- let wrongURI = Services.io.newURI("file:///example.js", null, null)
- Assert.deepEqual(SitePermissions.getPermissionDetailsByURI(wrongURI), []);
-
- let uri = Services.io.newURI("https://example.com", null, null)
-
- SitePermissions.set(uri, "camera", SitePermissions.ALLOW);
- SitePermissions.set(uri, "cookie", SitePermissions.SESSION);
- SitePermissions.set(uri, "popup", SitePermissions.BLOCK);
-
- let permissions = SitePermissions.getPermissionDetailsByURI(uri);
-
- let camera = permissions.find(({id}) => id === "camera");
- Assert.deepEqual(camera, {
- id: "camera",
- label: "Use the Camera",
- state: SitePermissions.ALLOW,
- availableStates: [
- { id: SitePermissions.UNKNOWN, label: "Always Ask" },
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- // check that removed permissions (State.UNKNOWN) are skipped
- SitePermissions.remove(uri, "camera");
- permissions = SitePermissions.getPermissionDetailsByURI(uri);
-
- camera = permissions.find(({id}) => id === "camera");
- Assert.equal(camera, undefined);
-
- // check that different available state values are represented
-
- let cookie = permissions.find(({id}) => id === "cookie");
- Assert.deepEqual(cookie, {
- id: "cookie",
- label: "Set Cookies",
- state: SitePermissions.SESSION,
- availableStates: [
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.SESSION, label: "Allow for Session" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- let popup = permissions.find(({id}) => id === "popup");
- Assert.deepEqual(popup, {
- id: "popup",
- label: "Open Pop-up Windows",
- state: SitePermissions.BLOCK,
- availableStates: [
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- SitePermissions.remove(uri, "cookie");
- SitePermissions.remove(uri, "popup");
-});
diff --git a/browser/modules/test/xpcshell/xpcshell.ini b/browser/modules/test/xpcshell/xpcshell.ini
deleted file mode 100644
index 28df9c4ed..000000000
--- a/browser/modules/test/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head =
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_AttributionCode.js]
-skip-if = os != 'win'
-[test_DirectoryLinksProvider.js]
-[test_SitePermissions.js]
-[test_LaterRun.js]
diff --git a/devtools/client/framework/test/browser.ini b/devtools/client/framework/test/browser.ini
index f34cd66f0..2404490ce 100644
--- a/devtools/client/framework/test/browser.ini
+++ b/devtools/client/framework/test/browser.ini
@@ -91,5 +91,3 @@ skip-if = os == "mac" && os_version == "10.8" || os == "win" && os_version == "5
[browser_toolbox_window_title_frame_select.js]
[browser_toolbox_zoom.js]
[browser_two_tabs.js]
-# We want this test to run for mochitest-dt as well, so we include it here:
-[../../../../browser/base/content/test/general/browser_parsable_css.js]
diff --git a/devtools/shared/webconsole/test/chrome.ini b/devtools/shared/webconsole/test/chrome.ini
index ae867b821..fde5a79fd 100644
--- a/devtools/shared/webconsole/test/chrome.ini
+++ b/devtools/shared/webconsole/test/chrome.ini
@@ -8,8 +8,6 @@ support-files =
network_requests_iframe.html
sandboxed_iframe.html
console-test-worker.js
- !/browser/base/content/test/general/browser_star_hsts.sjs
- !/browser/base/content/test/general/pinning_headers.sjs
[test_basics.html]
[test_bug819670_getter_throws.html]